]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Merge pull request #557 from jl777/kolo-assets-new
[VerusCoin.git] / src / miner.cpp
CommitLineData
d247a5d1 1// Copyright (c) 2009-2010 Satoshi Nakamoto
f914f1a7 2// Copyright (c) 2009-2014 The Bitcoin Core developers
78253fcb 3// Distributed under the MIT software license, see the accompanying
d247a5d1
JG
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
d247a5d1 6#include "miner.h"
8e8b6d70 7#ifdef ENABLE_MINING
c7aaab7a 8#include "pow/tromp/equi_miner.h"
2cc0a252 9#endif
51ed9ec9 10
eda37330 11#include "amount.h"
8e8b6d70 12#include "base58.h"
bebe7282 13#include "chainparams.h"
691161d4 14#include "consensus/consensus.h"
be126699 15#include "consensus/upgrades.h"
da29ecbc 16#include "consensus/validation.h"
8e8b6d70
JG
17#ifdef ENABLE_MINING
18#include "crypto/equihash.h"
19#endif
85aab2a0 20#include "hash.h"
d247a5d1 21#include "main.h"
a6df7ab5 22#include "metrics.h"
51ed9ec9 23#include "net.h"
df852d2b 24#include "pow.h"
bebe7282 25#include "primitives/transaction.h"
8e165d57 26#include "random.h"
22c4272b 27#include "timedata.h"
8e8b6d70 28#include "ui_interface.h"
ad49c256
WL
29#include "util.h"
30#include "utilmoneystr.h"
df840de5 31#ifdef ENABLE_WALLET
50c72f23 32#include "wallet/wallet.h"
df840de5 33#endif
09eb201b 34
fdda3c50
JG
35#include "sodium.h"
36
ad49c256 37#include <boost/thread.hpp>
a3c26c2e 38#include <boost/tuple/tuple.hpp>
8e8b6d70
JG
39#ifdef ENABLE_MINING
40#include <functional>
41#endif
5a360a5c 42#include <mutex>
ad49c256 43
09eb201b 44using namespace std;
7b4737c8 45
d247a5d1
JG
46//////////////////////////////////////////////////////////////////////////////
47//
48// BitcoinMiner
49//
50
c6cb21d1
GA
51//
52// Unconfirmed transactions in the memory pool often depend on other
53// transactions in the memory pool. When we select transactions from the
54// pool, we select by highest priority or fee rate, so we might consider
55// transactions that depend on transactions that aren't yet in the block.
56// The COrphan class keeps track of these 'temporary orphans' while
57// CreateBlock is figuring out which transactions to include.
58//
d247a5d1
JG
59class COrphan
60{
61public:
4d707d51 62 const CTransaction* ptx;
d247a5d1 63 set<uint256> setDependsOn;
c6cb21d1 64 CFeeRate feeRate;
02bec4b2 65 double dPriority;
d247a5d1 66
c6cb21d1 67 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 68 {
d247a5d1 69 }
d247a5d1
JG
70};
71
51ed9ec9
BD
72uint64_t nLastBlockTx = 0;
73uint64_t nLastBlockSize = 0;
d247a5d1 74
c6cb21d1
GA
75// We want to sort transactions by priority and fee rate, so:
76typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
77class TxPriorityCompare
78{
79 bool byFee;
0655fac0 80
d247a5d1
JG
81public:
82 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
0655fac0 83
d247a5d1
JG
84 bool operator()(const TxPriority& a, const TxPriority& b)
85 {
86 if (byFee)
87 {
88 if (a.get<1>() == b.get<1>())
89 return a.get<0>() < b.get<0>();
90 return a.get<1>() < b.get<1>();
91 }
92 else
93 {
94 if (a.get<0>() == b.get<0>())
95 return a.get<1>() < b.get<1>();
96 return a.get<0>() < b.get<0>();
97 }
98 }
99};
100
bebe7282 101void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 102{
103 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
22c4272b 104}
105
5416af1d 106#include "komodo_defs.h"
107
16c7bf6b 108extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
94a465a6 109extern uint32_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION;
7c130297 110extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
f24b36ca 111extern std::string NOTARY_PUBKEY;
94a465a6 112extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 113uint32_t Mining_start,Mining_height;
8683bd8d 114int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 115int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
9cc05f24 116uint64_t komodo_paxtotal();
d63fdb34 117int32_t komodo_baseid(char *origbase);
654dfaaf 118int32_t komodo_is_issuer();
635dd34d 119int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
48a3cd18 120int32_t komodo_isrealtime(int32_t *kmdheightp);
3bc88f14 121int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
7652ed92 122
48265f3c 123CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
d247a5d1 124{
ab918767 125 uint64_t deposits; int32_t isrealtime,kmdheight; const CChainParams& chainparams = Params();
d247a5d1 126 // Create new block
08c58194 127 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 128 if(!pblocktemplate.get())
1b5b89ba 129 {
130 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 131 return NULL;
1b5b89ba 132 }
d247a5d1 133 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
41ebe9c6 134 if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
a5e36fdd 135 {
48a3cd18 136 isrealtime = komodo_isrealtime(&kmdheight);
3da07d2e 137 deposits = komodo_paxtotal();
5ba0ce9d 138 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
ec7ad5f6 139 {
79562bf3 140 deposits = komodo_paxtotal();
16c7bf6b 141 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
79562bf3 142 {
bbaa688c 143 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
79562bf3 144 }
2bec17cb 145 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
4a21ccd2 146 {
eb928486 147 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);
79562bf3 148 break;
4a21ccd2 149 }
6fd0ae11 150 sleep(10);
ec7ad5f6 151 }
f24b36ca 152 KOMODO_ON_DEMAND = 0;
16cd9f2d 153 if ( 0 && deposits != 0 )
79562bf3 154 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());
a5e36fdd 155 }
dbca89b7
GA
156 // -regtest only: allow overriding block.nVersion with
157 // -blockversion=N to test forking scenarios
158 if (Params().MineBlocksOnDemand())
159 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
160
4949004d
PW
161 // Add dummy coinbase tx as first transaction
162 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
163 pblocktemplate->vTxFees.push_back(-1); // updated at end
164 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
165
166 // Largest block you're willing to create:
ad898b40 167 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
168 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
169 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
170
171 // How much of the block should be dedicated to high-priority transactions,
172 // included regardless of the fees they pay
173 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
174 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
175
176 // Minimum block size you want to create; block will be filled with free transactions
177 // until there are no more or the block reaches this size:
037b4f14 178 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1
JG
179 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
180
181 // Collect memory pool transactions into the block
a372168e 182 CAmount nFees = 0;
0655fac0 183
d247a5d1
JG
184 {
185 LOCK2(cs_main, mempool.cs);
48265f3c 186 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 187 const int nHeight = pindexPrev->nHeight + 1;
be126699 188 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
75a4d512 189 pblock->nTime = GetAdjustedTime();
a1d3c6fb 190 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
7c70438d 191 CCoinsViewCache view(pcoinsTip);
0a4ad821 192 uint32_t expired;
6ff77181 193
d247a5d1
JG
194 // Priority order to process transactions
195 list<COrphan> vOrphan; // list memory doesn't move
196 map<uint256, vector<COrphan*> > mapDependers;
197 bool fPrintPriority = GetBoolArg("-printpriority", false);
198
199 // This vector will be sorted into a priority queue:
200 vector<TxPriority> vecPriority;
201 vecPriority.reserve(mempool.mapTx.size());
e328fa32 202 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 203 mi != mempool.mapTx.end(); ++mi)
d247a5d1 204 {
e328fa32 205 const CTransaction& tx = mi->GetTx();
a1d3c6fb
MF
206
207 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
208 ? nMedianTimePast
209 : pblock->GetBlockTime();
210
9bb37bf0 211 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
14aa6cc0 212 continue;
bbaa0f9d 213 if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,2) < 0 )
6ff77181 214 {
14aa6cc0 215 fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n");
d247a5d1 216 continue;
14aa6cc0 217 }
d247a5d1
JG
218 COrphan* porphan = NULL;
219 double dPriority = 0;
a372168e 220 CAmount nTotalIn = 0;
d247a5d1
JG
221 bool fMissingInputs = false;
222 BOOST_FOREACH(const CTxIn& txin, tx.vin)
223 {
224 // Read prev transaction
225 if (!view.HaveCoins(txin.prevout.hash))
226 {
227 // This should never happen; all transactions in the memory
228 // pool should connect to either transactions in the chain
229 // or other transactions in the memory pool.
230 if (!mempool.mapTx.count(txin.prevout.hash))
231 {
881a85a2 232 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
233 if (fDebug) assert("mempool transaction missing input" == 0);
234 fMissingInputs = true;
235 if (porphan)
236 vOrphan.pop_back();
237 break;
238 }
239
240 // Has to wait for dependencies
241 if (!porphan)
242 {
243 // Use list for automatic deletion
244 vOrphan.push_back(COrphan(&tx));
245 porphan = &vOrphan.back();
246 }
247 mapDependers[txin.prevout.hash].push_back(porphan);
248 porphan->setDependsOn.insert(txin.prevout.hash);
e328fa32 249 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
250 continue;
251 }
629d75fa
PW
252 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
253 assert(coins);
d247a5d1 254
a372168e 255 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1
JG
256 nTotalIn += nValueIn;
257
b867e409 258 int nConf = nHeight - coins->nHeight;
d247a5d1
JG
259
260 dPriority += (double)nValueIn * nConf;
261 }
2b2bc69e
SB
262 nTotalIn += tx.GetJoinSplitValueIn();
263
d247a5d1
JG
264 if (fMissingInputs) continue;
265
d6eb2599 266 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 267 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 268 dPriority = tx.ComputePriority(dPriority, nTxSize);
d247a5d1 269
805344dc 270 uint256 hash = tx.GetHash();
2a72d459
LD
271 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
272
c6cb21d1 273 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
d247a5d1
JG
274
275 if (porphan)
276 {
277 porphan->dPriority = dPriority;
c6cb21d1 278 porphan->feeRate = feeRate;
d247a5d1
JG
279 }
280 else
e328fa32 281 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1
JG
282 }
283
284 // Collect transactions into block
51ed9ec9
BD
285 uint64_t nBlockSize = 1000;
286 uint64_t nBlockTx = 0;
355ca565 287 int64_t interest;
d247a5d1
JG
288 int nBlockSigOps = 100;
289 bool fSortedByFee = (nBlockPrioritySize <= 0);
290
291 TxPriorityCompare comparer(fSortedByFee);
292 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
293
294 while (!vecPriority.empty())
295 {
296 // Take highest priority transaction off the priority queue:
297 double dPriority = vecPriority.front().get<0>();
c6cb21d1 298 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 299 const CTransaction& tx = *(vecPriority.front().get<2>());
d247a5d1
JG
300
301 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
302 vecPriority.pop_back();
303
304 // Size limits
305 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
306 if (nBlockSize + nTxSize >= nBlockMaxSize)
307 continue;
308
309 // Legacy limits on sigOps:
310 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
311 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
312 continue;
313
314 // Skip free transactions if we're past the minimum block size:
805344dc 315 const uint256& hash = tx.GetHash();
2a72d459 316 double dPriorityDelta = 0;
a372168e 317 CAmount nFeeDelta = 0;
2a72d459 318 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 319 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
d247a5d1
JG
320 continue;
321
2a72d459 322 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
323 // transactions:
324 if (!fSortedByFee &&
325 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
326 {
327 fSortedByFee = true;
328 comparer = TxPriorityCompare(fSortedByFee);
329 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
330 }
331
332 if (!view.HaveInputs(tx))
333 continue;
334
1141b678 335 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
d247a5d1
JG
336
337 nTxSigOps += GetP2SHSigOpCount(tx, view);
338 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
339 continue;
340
68f7d1d7
PT
341 // Note that flags: we don't want to set mempool/IsStandard()
342 // policy here, but we still have to ensure that the block we
343 // create only contains transactions that are valid in new blocks.
d247a5d1 344 CValidationState state;
6514771a 345 PrecomputedTransactionData txdata(tx);
be126699 346 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
d247a5d1
JG
347 continue;
348
8cb98d91 349 UpdateCoins(tx, view, nHeight);
d247a5d1
JG
350
351 // Added
352 pblock->vtx.push_back(tx);
353 pblocktemplate->vTxFees.push_back(nTxFees);
354 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
355 nBlockSize += nTxSize;
356 ++nBlockTx;
357 nBlockSigOps += nTxSigOps;
358 nFees += nTxFees;
359
360 if (fPrintPriority)
361 {
3f0813b3 362 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1
JG
363 }
364
365 // Add transactions that depend on this one to the priority queue
366 if (mapDependers.count(hash))
367 {
368 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
369 {
370 if (!porphan->setDependsOn.empty())
371 {
372 porphan->setDependsOn.erase(hash);
373 if (porphan->setDependsOn.empty())
374 {
c6cb21d1 375 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
376 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
377 }
378 }
379 }
380 }
381 }
382
383 nLastBlockTx = nBlockTx;
384 nLastBlockSize = nBlockSize;
f48742c2 385 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
d247a5d1 386
f3ffa3d2 387 // Create coinbase tx
072099d7 388 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
389 txNew.vin.resize(1);
390 txNew.vin[0].prevout.SetNull();
d581f229 391 txNew.vout.resize(1);
f3ffa3d2 392 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
c9b1071d 393 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
9bb37bf0 394 txNew.nExpiryHeight = 0;
f3ffa3d2
SB
395 // Add fees
396 txNew.vout[0].nValue += nFees;
b867e409 397 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
8683bd8d 398 /*if ( ASSETCHAINS_SYMBOL[0] == 0 )
c9b1071d 399 {
8683bd8d 400 int32_t i,opretlen; uint8_t opret[256],*ptr;
44caf46a 401 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
c9b1071d 402 {
b4810651 403 if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed
d9a9d562 404 {
405 txNew.vout.resize(2);
406 txNew.vout[1].scriptPubKey.resize(opretlen);
407 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
408 for (i=0; i<opretlen; i++)
409 ptr[i] = opret[i];
410 txNew.vout[1].nValue = 0;
411 //fprintf(stderr,"opretlen.%d\n",opretlen);
768dccac 412 } //else printf("null opretlen for prices\n");
8683bd8d 413 }
c9b1071d 414 }
654dfaaf 415 else if ( komodo_is_issuer() != 0 )
c9b1071d 416 {
7322eaa0 417 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
1ecb8541 418 if ( txNew.vout.size() > 1 )
4a21ccd2 419 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
8683bd8d 420 }*/
8f3aa743 421
4949004d 422 pblock->vtx[0] = txNew;
d247a5d1 423 pblocktemplate->vTxFees[0] = -nFees;
8e165d57
JG
424 // Randomise nonce
425 arith_uint256 nonce = UintToArith256(GetRandHash());
426 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
427 nonce <<= 32;
428 nonce >>= 16;
429 pblock->nNonce = ArithToUint256(nonce);
430
d247a5d1
JG
431 // Fill in header
432 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 433 pblock->hashReserved = uint256();
b366cab9 434 //UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
4f5e03db 435 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
fdda3c50 436 pblock->nSolution.clear();
d247a5d1
JG
437 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
438
c583e2a9 439 CValidationState state;
0af2786d 440 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
af805d53 441 {
d0f7ead0 442 static uint32_t counter;
443 if ( counter++ < 100 )
d4190a2a 444 fprintf(stderr,"warning: testblockvalidity failed\n");
14aa6cc0 445 return(0);
af805d53 446 }
d247a5d1
JG
447 }
448
449 return pblocktemplate.release();
450}
451
1a31463b 452/*
8e8b6d70
JG
453#ifdef ENABLE_WALLET
454boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
455#else
456boost::optional<CScript> GetMinerScriptPubKey()
457#endif
458{
459 CKeyID keyID;
460 CBitcoinAddress addr;
461 if (addr.SetString(GetArg("-mineraddress", ""))) {
462 addr.GetKeyID(keyID);
463 } else {
464#ifdef ENABLE_WALLET
465 CPubKey pubkey;
466 if (!reservekey.GetReservedKey(pubkey)) {
467 return boost::optional<CScript>();
468 }
469 keyID = pubkey.GetID();
470#else
471 return boost::optional<CScript>();
472#endif
473 }
474
475 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
476 return scriptPubKey;
477}
478
1a31463b 479#ifdef ENABLE_WALLET
48265f3c 480CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 481{
8e8b6d70
JG
482 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
483#else
484CBlockTemplate* CreateNewBlockWithKey()
485{
486 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
487#endif
acfa0333 488
8e8b6d70
JG
489 if (!scriptPubKey) {
490 return NULL;
491 }
492 return CreateNewBlock(*scriptPubKey);
945f015d 493}*/
acfa0333 494
c1de826f
JG
495//////////////////////////////////////////////////////////////////////////////
496//
497// Internal miner
498//
499
2cc0a252 500#ifdef ENABLE_MINING
c1de826f 501
d247a5d1
JG
502void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
503{
504 // Update nExtraNonce
505 static uint256 hashPrevBlock;
506 if (hashPrevBlock != pblock->hashPrevBlock)
507 {
508 nExtraNonce = 0;
509 hashPrevBlock = pblock->hashPrevBlock;
510 }
511 ++nExtraNonce;
512 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
513 CMutableTransaction txCoinbase(pblock->vtx[0]);
514 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
515 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
d247a5d1 516
4949004d 517 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
518 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
519}
520
4a85e067 521#ifdef ENABLE_WALLET
acfa0333
WL
522//////////////////////////////////////////////////////////////////////////////
523//
524// Internal miner
525//
acfa0333 526
48265f3c 527CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 528{
f6c647ed 529 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 530 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 531 {
7bfc207a 532 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 533 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 534 }
535 else
536 {
537 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 538 {
f6c647ed 539 return NULL;
1b5b89ba 540 }
f6c647ed 541 scriptPubKey.resize(35);
f66f65ec 542 ptr = (uint8_t *)pubkey.begin();
f6c647ed 543 script = (uint8_t *)scriptPubKey.data();
544 script[0] = 33;
545 for (i=0; i<33; i++)
546 script[i+1] = ptr[i];
547 script[34] = OP_CHECKSIG;
548 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
549 }
48265f3c 550 return CreateNewBlock(scriptPubKey);
acfa0333
WL
551}
552
945f015d 553
269d8ba0 554static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
555#else
556static bool ProcessBlockFound(CBlock* pblock)
557#endif // ENABLE_WALLET
d247a5d1 558{
81212588 559 LogPrintf("%s\n", pblock->ToString());
35915149 560 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
d247a5d1
JG
561
562 // Found a solution
563 {
564 LOCK(cs_main);
4c6d41b8 565 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
ba8419c7 566 {
567 uint256 hash; int32_t i;
568 hash = pblock->hashPrevBlock;
92266e99 569 for (i=31; i>=0; i--)
ba8419c7 570 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 571 fprintf(stderr," <- prev (stale)\n");
ba8419c7 572 hash = chainActive.Tip()->GetBlockHash();
92266e99 573 for (i=31; i>=0; i--)
ba8419c7 574 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 575 fprintf(stderr," <- chainTip (stale)\n");
ba8419c7 576
2e500f50 577 return error("KomodoMiner: generated block is stale");
ba8419c7 578 }
18e72167 579 }
d247a5d1 580
8e8b6d70 581#ifdef ENABLE_WALLET
18e72167 582 // Remove key from key pool
998397aa 583 if ( IS_KOMODO_NOTARY == 0 )
945f015d 584 {
585 if (GetArg("-mineraddress", "").empty()) {
586 // Remove key from key pool
587 reservekey.KeepKey();
588 }
8e8b6d70 589 }
18e72167 590 // Track how many getdata requests this block gets
438ba9c1 591 //if ( 0 )
18e72167
PW
592 {
593 LOCK(wallet.cs_wallet);
594 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 595 }
8e8b6d70 596#endif
d247a5d1 597
18e72167
PW
598 // Process this block the same as if we had received it from another node
599 CValidationState state;
35915149 600 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 601 return error("KomodoMiner: ProcessNewBlock, block not accepted");
18e72167 602
d793f94b 603 TrackMinedBlock(pblock->GetHash());
a6df7ab5 604
d247a5d1
JG
605 return true;
606}
607
078f6af1 608int32_t komodo_baseid(char *origbase);
8c654ec5 609int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
8ee93080 610int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 611extern int32_t KOMODO_LASTMINED;
8b51b9e4 612int32_t roundrobin_delay;
078f6af1 613
8e8b6d70 614#ifdef ENABLE_WALLET
d247a5d1 615void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
616#else
617void static BitcoinMiner()
618#endif
d247a5d1 619{
2e500f50 620 LogPrintf("KomodoMiner started\n");
d247a5d1 621 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 622 RenameThread("komodo-miner");
bebe7282 623 const CChainParams& chainparams = Params();
d247a5d1 624
8e8b6d70
JG
625#ifdef ENABLE_WALLET
626 // Each thread has its own key
d247a5d1 627 CReserveKey reservekey(pwallet);
8e8b6d70
JG
628#endif
629
630 // Each thread has its own counter
d247a5d1
JG
631 unsigned int nExtraNonce = 0;
632
e9574728
JG
633 unsigned int n = chainparams.EquihashN();
634 unsigned int k = chainparams.EquihashK();
8683bd8d 635 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
b7ba6413 636 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 637 {
638 sleep(1);
4e624c04 639 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
640 break;
755ead98 641 }
952b9905 642 //sleep(60);
8683bd8d 643 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
fdda3c50 644
755ead98 645 std::string solver;
e1e65cef 646 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
755ead98 647 solver = "tromp";
e1e65cef 648 //else solver = "default";
5f0009b2 649 assert(solver == "tromp" || solver == "default");
c7aaab7a 650 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 651 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 652 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
653 std::mutex m_cs;
654 bool cancelSolver = false;
655 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
656 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
657 std::lock_guard<std::mutex> lock{m_cs};
658 cancelSolver = true;
659 }
660 );
07be8f7e 661 miningTimer.start();
5a360a5c 662
0655fac0 663 try {
ad84148d 664 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 665 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 666 while (true)
667 {
2c70b583 668 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 669 {
a96fd7b5 670 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
671 // break;
0655fac0
PK
672 // Busy-wait for the network to come online so we don't waste time mining
673 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 674 miningTimer.stop();
bba7c249
GM
675 do {
676 bool fvNodesEmpty;
677 {
678 LOCK(cs_vNodes);
679 fvNodesEmpty = vNodes.empty();
680 }
269fe243 681 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 682 break;
f8e367eb 683 MilliSleep(5000);
ad84148d 684 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
f8e367eb 685
bba7c249 686 } while (true);
ad84148d 687 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 688 miningTimer.start();
0655fac0 689 }
f70ced6a 690 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
8fc7222d 691 {
692 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
693 sleep(3);
d82623d2 694 }*/
0655fac0
PK
695 //
696 // Create new block
697 //
698 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 699 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 700 if ( Mining_height != pindexPrev->nHeight+1 )
701 {
702 Mining_height = pindexPrev->nHeight+1;
703 Mining_start = (uint32_t)time(NULL);
704 }
2825c0b5 705 if ( ASSETCHAINS_SYMBOL[0] != 0 )
706 {
40304479 707 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2825c0b5 708 sleep(3);
709 }
8e8b6d70 710#ifdef ENABLE_WALLET
08d0b73c 711 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
8e8b6d70 712#else
945f015d 713 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 714#endif
08d0b73c 715 if ( ptr == 0 )
716 {
d0f7ead0 717 static uint32_t counter;
718 if ( counter++ < 100 )
1b5b89ba 719 fprintf(stderr,"created illegal block, retry\n");
d0f7ead0 720 continue;
08d0b73c 721 }
722 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 723 if (!pblocktemplate.get())
6c37f7fd 724 {
8e8b6d70 725 if (GetArg("-mineraddress", "").empty()) {
945f015d 726 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
727 } else {
728 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 729 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 730 }
0655fac0 731 return;
6c37f7fd 732 }
0655fac0 733 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 734 if ( ASSETCHAINS_SYMBOL[0] != 0 )
735 {
8683bd8d 736 if ( ASSETCHAINS_REWARD == 0 )
16c7bf6b 737 {
8683bd8d 738 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
739 {
740 static uint32_t counter;
741 if ( counter++ < 10 )
742 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
743 sleep(10);
744 continue;
745 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
746 }
16c7bf6b 747 }
0655fac0 748 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 749 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
0655fac0
PK
750 //
751 // Search
752 //
8b51b9e4 753 uint8_t pubkeys[66][33]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
404391b5 754 savebits = pblock->nBits;
3505af19 755 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
f0100e72 756 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 757 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 758 {
fda5f849 759 j = 65;
5a471ba9 760 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 761 {
8c654ec5 762 komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
29e60e48 763 if ( nonzpkeys > 0 )
764 {
ccb71a6e 765 for (i=0; i<33; i++)
766 if( pubkeys[0][i] != 0 )
767 break;
768 if ( i == 33 )
769 externalflag = 1;
770 else externalflag = 0;
49b49585 771 if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) )
b176c125 772 {
345e545e 773 for (i=1; i<66; i++)
774 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
775 break;
ccb71a6e 776 if ( externalflag == 0 && i != 66 )
345e545e 777 printf("VIOLATION at %d\n",i);
2c7ad758 778 for (j=gpucount=0; j<65; j++)
779 {
49b49585 780 if ( mids[j] >= 0 || notaryid == 34 )
8fa91017 781 fprintf(stderr,"%d ",mids[j]);
782 else fprintf(stderr,"GPU ");
2c7ad758 783 if ( mids[j] == -1 )
784 gpucount++;
785 }
b000fa04 786 if ( gpucount > j/2 )
f0100e72 787 {
dd98c02d 788 double delta;
d2d3c766 789 if ( notaryid < 0 )
790 i = (rand() % 64);
791 else i = ((Mining_height + notaryid) % 64);
b000fa04 792 delta = sqrt((double)gpucount - j/2) / 2.;
dd98c02d 793 roundrobin_delay += ((delta * i) / 64) - delta;
67478d4a 794 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
f0100e72 795 }
796 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
b176c125 797 }
29e60e48 798 for (j=0; j<65; j++)
799 if ( mids[j] == notaryid )
800 break;
49b49585 801 if ( j == 65 )
802 KOMODO_LASTMINED = 0;
965f0f7e 803 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 804 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 805 {
806 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
807 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
808 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 809 } else Mining_start = 0;
d7d27bb3 810 } else Mining_start = 0;
e725f1cb 811 while (true)
812 {
16c7bf6b 813 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
16cd9f2d 814 {
815 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
816 sleep(10);
817 break;
16c7bf6b 818 }*/
7213c0b1 819 // Hash state
8c22eb46 820 KOMODO_CHOSEN_ONE = 0;
7213c0b1 821 crypto_generichash_blake2b_state state;
e9574728 822 EhInitialiseState(n, k, state);
7213c0b1
JG
823 // I = the block header minus nonce and solution.
824 CEquihashInput I{*pblock};
825 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
826 ss << I;
7213c0b1
JG
827 // H(I||...
828 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
829 // H(I||V||...
830 crypto_generichash_blake2b_state curr_state;
831 curr_state = state;
7a4c01c9 832 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 833 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 834 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
6be3b162 835 //fprintf(stderr,"running solver\n");
5be6abbf 836 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 837#ifdef ENABLE_WALLET
51eb5273 838 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70
JG
839#else
840 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
841#endif
5be6abbf 842 (std::vector<unsigned char> soln) {
51eb5273
JG
843 // Write the solution to the hash and compute the result.
844 LogPrint("pow", "- Checking solution against target\n");
8e165d57 845 pblock->nSolution = soln;
e7d59bbc 846 solutionTargetChecks.increment();
7a4c01c9 847 if ( UintToArith256(pblock->GetHash()) > hashTarget )
e5430f52 848 {
bd6ef155 849 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
7c3b0491 850 // fprintf(stderr," missed target\n");
51eb5273 851 return false;
e5430f52 852 }
b35ca433 853 if ( /*ASSETCHAINS_SYMBOL[0] == 0 &&*/ Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
d7d27bb3 854 {
f0100e72 855 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
856 int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
52e87248 857 if ( nseconds > 0 )
858 sleep(nseconds);
320a2e35 859 MilliSleep((rand() % 1700) + 1);
d7d27bb3 860 }
2825c0b5 861 else if ( ASSETCHAINS_SYMBOL[0] != 0 )
d2d3c766 862 {
863 sleep(rand() % 30);
864 }
b3183e3e 865 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
866 // Found a solution
867 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 868 LogPrintf("KomodoMiner:\n");
a6a0d913 869 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
8e8b6d70 870#ifdef ENABLE_WALLET
5a360a5c 871 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
8e8b6d70
JG
872#else
873 if (ProcessBlockFound(pblock)) {
874#endif
a6a0d913 875 // Ignore chain updates caused by us
876 std::lock_guard<std::mutex> lock{m_cs};
5a360a5c
JG
877 cancelSolver = false;
878 }
8c22eb46 879 KOMODO_CHOSEN_ONE = 0;
8e165d57 880 SetThreadPriority(THREAD_PRIORITY_LOWEST);
8e165d57 881 // In regression test mode, stop mining after a block is found.
a6df7ab5
JG
882 if (chainparams.MineBlocksOnDemand()) {
883 // Increment here because throwing skips the call below
884 ehSolverRuns.increment();
8e165d57 885 throw boost::thread_interrupted();
a6df7ab5 886 }
b78471c2 887 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
888 // sleep(1800);
51eb5273
JG
889 return true;
890 };
891 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
892 std::lock_guard<std::mutex> lock{m_cs};
893 return cancelSolver;
894 };
c7aaab7a 895
5f0009b2 896 // TODO: factor this out into a function with the same API for each solver.
e1e65cef 897 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
c7aaab7a
DH
898 // Create solver and initialize it.
899 equi eq(1);
900 eq.setstate(&curr_state);
901
c938fb1f 902 // Initialization done, start algo driver.
c7aaab7a
DH
903 eq.digit0(0);
904 eq.xfull = eq.bfull = eq.hfull = 0;
905 eq.showbsizes(0);
906 for (u32 r = 1; r < WK; r++) {
907 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
908 eq.xfull = eq.bfull = eq.hfull = 0;
909 eq.showbsizes(r);
910 }
911 eq.digitK(0);
a6df7ab5 912 ehSolverRuns.increment();
c7aaab7a
DH
913
914 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
915 for (size_t s = 0; s < eq.nsols; s++) {
916 LogPrint("pow", "Checking solution %d\n", s+1);
917 std::vector<eh_index> index_vector(PROOFSIZE);
918 for (size_t i = 0; i < PROOFSIZE; i++) {
919 index_vector[i] = eq.sols[s][i];
920 }
921 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
922
923 if (validBlock(sol_char)) {
924 // If we find a POW solution, do not try other solutions
925 // because they become invalid as we created a new block in blockchain.
926 break;
927 }
928 }
929 } else {
930 try {
931 // If we find a valid block, we rebuild
a6df7ab5
JG
932 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
933 ehSolverRuns.increment();
934 if (found) {
a8aa4375 935 int32_t i; uint256 hash = pblock->GetHash();
936 for (i=0; i<32; i++)
937 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
938 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
b78471c2 939 FOUND_BLOCK = 1;
8ee93080 940 KOMODO_MAYBEMINED = Mining_height;
c7aaab7a 941 break;
a6df7ab5 942 }
c7aaab7a
DH
943 } catch (EhSolverCancelledException&) {
944 LogPrint("pow", "Equihash solver cancelled\n");
945 std::lock_guard<std::mutex> lock{m_cs};
946 cancelSolver = false;
947 }
48265f3c 948 }
d247a5d1 949
0655fac0
PK
950 // Check for stop or if block needs to be rebuilt
951 boost::this_thread::interruption_point();
952 // Regtest mode doesn't require peers
b78471c2 953 if ( FOUND_BLOCK != 0 )
954 {
955 FOUND_BLOCK = 0;
956 fprintf(stderr,"FOUND_BLOCK!\n");
9152feb5 957 //sleep(2000);
b78471c2 958 }
bebe7282 959 if (vNodes.empty() && chainparams.MiningRequiresPeers())
e5430f52 960 {
f70ced6a 961 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
10694486 962 {
bd6ef155 963 fprintf(stderr,"no nodes, break\n");
d90cef0b 964 break;
10694486 965 }
e5430f52 966 }
8e165d57 967 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
e5430f52 968 {
198286a5 969 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 970 fprintf(stderr,"0xffff, break\n");
0655fac0 971 break;
e5430f52 972 }
0655fac0 973 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
e5430f52 974 {
6be3b162 975 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 976 fprintf(stderr,"timeout, break\n");
0655fac0 977 break;
e5430f52 978 }
979 if ( pindexPrev != chainActive.Tip() )
980 {
6be3b162 981 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 982 fprintf(stderr,"Tip advanced, break\n");
0655fac0 983 break;
e5430f52 984 }
8e165d57
JG
985 // Update nNonce and nTime
986 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
404391b5 987 pblock->nBits = savebits;
bebe7282
JT
988 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
989 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
48265f3c
WL
990 {
991 // Changing pblock->nTime can change work required on testnet:
992 hashTarget.SetCompact(pblock->nBits);
993 }
d247a5d1
JG
994 }
995 }
0655fac0 996 }
27df4123 997 catch (const boost::thread_interrupted&)
d247a5d1 998 {
07be8f7e 999 miningTimer.stop();
5e9b555f 1000 c.disconnect();
2e500f50 1001 LogPrintf("KomodoMiner terminated\n");
d247a5d1
JG
1002 throw;
1003 }
bba7c249
GM
1004 catch (const std::runtime_error &e)
1005 {
07be8f7e 1006 miningTimer.stop();
5e9b555f 1007 c.disconnect();
2e500f50 1008 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
bba7c249
GM
1009 return;
1010 }
07be8f7e 1011 miningTimer.stop();
5a360a5c 1012 c.disconnect();
d247a5d1
JG
1013}
1014
8e8b6d70 1015#ifdef ENABLE_WALLET
c8b74258 1016void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70
JG
1017#else
1018void GenerateBitcoins(bool fGenerate, int nThreads)
1019#endif
d247a5d1
JG
1020{
1021 static boost::thread_group* minerThreads = NULL;
1022
2854c4e3
WL
1023 if (nThreads < 0)
1024 nThreads = GetNumCores();
d247a5d1
JG
1025
1026 if (minerThreads != NULL)
1027 {
1028 minerThreads->interrupt_all();
1029 delete minerThreads;
1030 minerThreads = NULL;
1031 }
1032
1033 if (nThreads == 0 || !fGenerate)
1034 return;
1035
1036 minerThreads = new boost::thread_group();
8e8b6d70
JG
1037 for (int i = 0; i < nThreads; i++) {
1038#ifdef ENABLE_WALLET
d247a5d1 1039 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
8e8b6d70
JG
1040#else
1041 minerThreads->create_thread(&BitcoinMiner);
1042#endif
1043 }
d247a5d1
JG
1044}
1045
2cc0a252 1046#endif // ENABLE_MINING
This page took 0.539642 seconds and 4 git commands to generate.