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