]> Git Repo - VerusCoin.git/blob - src/miner.cpp
lastmined
[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 60
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,uint8_t *pubkey33);
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,0));
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 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
524 int32_t FOUND_BLOCK;
525 extern int32_t KOMODO_LASTMINED;
526
527 void static BitcoinMiner(CWallet *pwallet)
528 {
529     LogPrintf("KomodoMiner started\n");
530     SetThreadPriority(THREAD_PRIORITY_LOWEST);
531     RenameThread("komodo-miner");
532     const CChainParams& chainparams = Params();
533
534     // Each thread has its own key and counter
535     CReserveKey reservekey(pwallet);
536     unsigned int nExtraNonce = 0;
537
538     unsigned int n = chainparams.EquihashN();
539     unsigned int k = chainparams.EquihashK();
540     int32_t notaryid = -1;
541     while ( ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0 )
542     {
543         sleep(1);
544         if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
545             break;
546     }
547     komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
548
549     std::string solver;
550     //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
551         solver = "tromp";
552     //else solver = "default";
553     assert(solver == "tromp" || solver == "default");
554     LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
555     //fprintf(stderr,"Mining with %s\n",solver.c_str());
556     std::mutex m_cs;
557     bool cancelSolver = false;
558     boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
559         [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
560             std::lock_guard<std::mutex> lock{m_cs};
561             cancelSolver = true;
562         }
563     );
564
565     try {
566         //fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
567         while (true)
568         {
569             if (chainparams.MiningRequiresPeers())
570             {
571                 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
572                 //    break;
573                 // Busy-wait for the network to come online so we don't waste time mining
574                 // on an obsolete chain. In regtest mode we expect to fly solo.
575                 //fprintf(stderr,"Wait for peers...\n");
576                 do {
577                     bool fvNodesEmpty;
578                     {
579                         LOCK(cs_vNodes);
580                         fvNodesEmpty = vNodes.empty();
581                     }
582                     if (!fvNodesEmpty && !IsInitialBlockDownload())
583                         break;
584                     MilliSleep(5000);
585                     //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
586
587                 } while (true);
588                 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
589             }
590             /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
591             {
592                 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
593                 sleep(3);
594             }*/
595             //
596             // Create new block
597             //
598             unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
599             CBlockIndex* pindexPrev = chainActive.Tip();
600             if ( Mining_height != pindexPrev->nHeight+1 )
601             {
602                 Mining_height = pindexPrev->nHeight+1;
603                 Mining_start = (uint32_t)time(NULL);
604             }
605             if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
606                 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
607
608             unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
609             if (!pblocktemplate.get())
610             {
611                 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
612                 return;
613             }
614             CBlock *pblock = &pblocktemplate->block;
615             IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
616             LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
617             //
618             // Search
619             //
620             uint8_t pubkeys[66][33]; int mids[66],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
621             savebits = pblock->nBits;
622             arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
623             if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )//komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
624             {
625                 j = 65;
626                 if ( (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
627                 {
628                     komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
629                     if ( nonzpkeys > 0 )
630                     {
631                         for (i=0; i<33; i++)
632                             if( pubkeys[0][i] != 0 )
633                                 break;
634                         if ( i == 33 )
635                             externalflag = 1;
636                         else externalflag = 0;
637                         if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 )
638                         {
639                             for (i=1; i<66; i++)
640                                 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
641                                     break;
642                             if ( externalflag == 0 && i != 66 )
643                                 printf("VIOLATION at %d\n",i);
644                             for (i=0; i<66; i++)
645                             {break;
646                                 for (j=0; j<33; j++)
647                                     printf("%02x",pubkeys[i][j]);
648                                 printf(" p%d -> %d\n",i,komodo_minerid(pindexPrev->nHeight-i,pubkeys[i]));
649                             }
650                             for (j=gpucount=0; j<65; j++)
651                             {
652                                 fprintf(stderr,"%d ",mids[j]);
653                                 if ( mids[j] == -1 )
654                                     gpucount++;
655                             }
656                             fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%%\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j);
657                         }
658                         for (j=0; j<65; j++)
659                             if ( mids[j] == notaryid )
660                                 break;
661                     } else fprintf(stderr,"no nonz pubkeys\n");
662                     if ( j == 65 && Mining_height > KOMODO_LASTMINED+64 )
663                     {
664                         hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
665                         fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
666                     } //else fprintf(stderr,"duplicate at j.%d\n",j);
667                 } else Mining_start = 0;
668             } else Mining_start = 0;
669             while (true)
670             {
671                 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
672                 {
673                     fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
674                     sleep(10);
675                     break;
676                 }
677                 // Hash state
678                 KOMODO_CHOSEN_ONE = 0;
679                 crypto_generichash_blake2b_state state;
680                 EhInitialiseState(n, k, state);
681                 // I = the block header minus nonce and solution.
682                 CEquihashInput I{*pblock};
683                 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
684                 ss << I;
685                 // H(I||...
686                 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
687                 // H(I||V||...
688                 crypto_generichash_blake2b_state curr_state;
689                 curr_state = state;
690                 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
691                 // (x_1, x_2, ...) = A(I, V, n, k)
692                 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
693                 //fprintf(stderr,"running solver\n");
694                 std::function<bool(std::vector<unsigned char>)> validBlock =
695                         [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
696                         (std::vector<unsigned char> soln)
697                 {
698                     // Write the solution to the hash and compute the result.
699                     LogPrint("pow", "- Checking solution against target\n");
700                     pblock->nSolution = soln;
701                     solutionTargetChecks.increment();
702                     if ( UintToArith256(pblock->GetHash()) > hashTarget )
703                     {
704                         if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
705                             fprintf(stderr,"missed target\n");
706                         return false;
707                     }
708                     if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
709                     {
710                         //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
711                         int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
712                         if ( nseconds > 0 )
713                             sleep(nseconds);
714                         MilliSleep((rand() % 700) + 1);
715                     }
716                     KOMODO_CHOSEN_ONE = 1;
717                     // Found a solution
718                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
719                     LogPrintf("KomodoMiner:\n");
720                     LogPrintf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
721                     if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
722                         // Ignore chain updates caused by us
723                         std::lock_guard<std::mutex> lock{m_cs};
724                         cancelSolver = false;
725                     }
726                     KOMODO_CHOSEN_ONE = 0;
727                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
728                     // In regression test mode, stop mining after a block is found.
729                     if (chainparams.MineBlocksOnDemand()) {
730                         // Increment here because throwing skips the call below
731                         ehSolverRuns.increment();
732                         throw boost::thread_interrupted();
733                     }
734                     //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
735                     //    sleep(1800);
736                     return true;
737                 };
738                 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
739                     std::lock_guard<std::mutex> lock{m_cs};
740                     return cancelSolver;
741                 };
742
743                 // TODO: factor this out into a function with the same API for each solver.
744                 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
745                     // Create solver and initialize it.
746                     equi eq(1);
747                     eq.setstate(&curr_state);
748
749                     // Intialization done, start algo driver.
750                     eq.digit0(0);
751                     eq.xfull = eq.bfull = eq.hfull = 0;
752                     eq.showbsizes(0);
753                     for (u32 r = 1; r < WK; r++) {
754                         (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
755                         eq.xfull = eq.bfull = eq.hfull = 0;
756                         eq.showbsizes(r);
757                     }
758                     eq.digitK(0);
759                     ehSolverRuns.increment();
760
761                     // Convert solution indices to byte array (decompress) and pass it to validBlock method.
762                     for (size_t s = 0; s < eq.nsols; s++) {
763                         LogPrint("pow", "Checking solution %d\n", s+1);
764                         std::vector<eh_index> index_vector(PROOFSIZE);
765                         for (size_t i = 0; i < PROOFSIZE; i++) {
766                             index_vector[i] = eq.sols[s][i];
767                         }
768                         std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
769
770                         if (validBlock(sol_char)) {
771                             // If we find a POW solution, do not try other solutions
772                             // because they become invalid as we created a new block in blockchain.
773                             break;
774                         }
775                     }
776                 } else {
777                     try {
778                         // If we find a valid block, we rebuild
779                         bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
780                         ehSolverRuns.increment();
781                         if (found) {
782                             int32_t i; uint256 hash = pblock->GetHash();
783                             for (i=0; i<32; i++)
784                                 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
785                             fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
786                             FOUND_BLOCK = 1;
787                             break;
788                         }
789                     } catch (EhSolverCancelledException&) {
790                         LogPrint("pow", "Equihash solver cancelled\n");
791                         std::lock_guard<std::mutex> lock{m_cs};
792                         cancelSolver = false;
793                     }
794                 }
795
796                 // Check for stop or if block needs to be rebuilt
797                 boost::this_thread::interruption_point();
798                 // Regtest mode doesn't require peers
799                 if ( FOUND_BLOCK != 0 )
800                 {
801                     FOUND_BLOCK = 0;
802                     fprintf(stderr,"FOUND_BLOCK!\n");
803                     //sleep(2000);
804                 }
805                 if (vNodes.empty() && chainparams.MiningRequiresPeers())
806                 {
807                     if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
808                     {
809                         //fprintf(stderr,"no nodes, break\n");
810                         break;
811                     }
812                 }
813                 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
814                 {
815                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
816                         fprintf(stderr,"0xffff, break\n");
817                     break;
818                 }
819                 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
820                 {
821                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
822                         fprintf(stderr,"timeout, break\n");
823                     break;
824                 }
825                 if ( pindexPrev != chainActive.Tip() )
826                 {
827                     if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
828                         fprintf(stderr,"Tip advanced, break\n");
829                     break;
830                 }
831                 // Update nNonce and nTime
832                 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
833                 pblock->nBits = savebits;
834                 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
835                 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
836                 {
837                     // Changing pblock->nTime can change work required on testnet:
838                     hashTarget.SetCompact(pblock->nBits);
839                 }
840             }
841         }
842     }
843     catch (const boost::thread_interrupted&)
844     {
845         c.disconnect();
846         LogPrintf("KomodoMiner terminated\n");
847         throw;
848     }
849     catch (const std::runtime_error &e)
850     {
851         c.disconnect();
852         LogPrintf("KomodoMiner runtime error: %s\n", e.what());
853         return;
854     }
855     c.disconnect();
856 }
857
858 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
859 {
860     static boost::thread_group* minerThreads = NULL;
861
862     if (nThreads < 0) {
863         // In regtest threads defaults to 1
864         if (Params().DefaultMinerThreads())
865             nThreads = Params().DefaultMinerThreads();
866         else
867             nThreads = boost::thread::hardware_concurrency();
868     }
869
870     if (minerThreads != NULL)
871     {
872         minerThreads->interrupt_all();
873         delete minerThreads;
874         minerThreads = NULL;
875     }
876
877     if (nThreads == 0 || !fGenerate)
878         return;
879
880     minerThreads = new boost::thread_group();
881     for (int i = 0; i < nThreads; i++)
882         minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
883 }
884
885 #endif // ENABLE_WALLET
This page took 0.076529 seconds and 4 git commands to generate.