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