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