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