]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Improve and complete getinfo output, cleanup unused reference
[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"
42181656 19#include "crypto/verus_hash.h"
8e8b6d70 20#endif
85aab2a0 21#include "hash.h"
42181656 22
d247a5d1 23#include "main.h"
a6df7ab5 24#include "metrics.h"
51ed9ec9 25#include "net.h"
df852d2b 26#include "pow.h"
bebe7282 27#include "primitives/transaction.h"
8e165d57 28#include "random.h"
22c4272b 29#include "timedata.h"
8e8b6d70 30#include "ui_interface.h"
ad49c256
WL
31#include "util.h"
32#include "utilmoneystr.h"
df840de5 33#ifdef ENABLE_WALLET
50c72f23 34#include "wallet/wallet.h"
df840de5 35#endif
09eb201b 36
fdda3c50
JG
37#include "sodium.h"
38
ad49c256 39#include <boost/thread.hpp>
a3c26c2e 40#include <boost/tuple/tuple.hpp>
8e8b6d70
JG
41#ifdef ENABLE_MINING
42#include <functional>
43#endif
5a360a5c 44#include <mutex>
ad49c256 45
09eb201b 46using namespace std;
7b4737c8 47
d247a5d1
JG
48//////////////////////////////////////////////////////////////////////////////
49//
50// BitcoinMiner
51//
52
c6cb21d1
GA
53//
54// Unconfirmed transactions in the memory pool often depend on other
55// transactions in the memory pool. When we select transactions from the
56// pool, we select by highest priority or fee rate, so we might consider
57// transactions that depend on transactions that aren't yet in the block.
58// The COrphan class keeps track of these 'temporary orphans' while
59// CreateBlock is figuring out which transactions to include.
60//
d247a5d1
JG
61class COrphan
62{
63public:
4d707d51 64 const CTransaction* ptx;
d247a5d1 65 set<uint256> setDependsOn;
c6cb21d1 66 CFeeRate feeRate;
02bec4b2 67 double dPriority;
e9e70b95 68
c6cb21d1 69 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 70 {
d247a5d1 71 }
d247a5d1
JG
72};
73
51ed9ec9
BD
74uint64_t nLastBlockTx = 0;
75uint64_t nLastBlockSize = 0;
d247a5d1 76
c6cb21d1
GA
77// We want to sort transactions by priority and fee rate, so:
78typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
79class TxPriorityCompare
80{
81 bool byFee;
e9e70b95 82
d247a5d1
JG
83public:
84 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
e9e70b95 85
d247a5d1
JG
86 bool operator()(const TxPriority& a, const TxPriority& b)
87 {
88 if (byFee)
89 {
90 if (a.get<1>() == b.get<1>())
91 return a.get<0>() < b.get<0>();
92 return a.get<1>() < b.get<1>();
93 }
94 else
95 {
96 if (a.get<0>() == b.get<0>())
97 return a.get<1>() < b.get<1>();
98 return a.get<0>() < b.get<0>();
99 }
100 }
101};
102
bebe7282 103void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 104{
4972b74b 105 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
22c4272b 106}
107
5416af1d 108#include "komodo_defs.h"
109
16c7bf6b 110extern 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;
48d800c2 111extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
42181656 112extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
113extern const char *ASSETCHAINS_ALGORITHMS[];
114extern int32_t ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
7c130297 115extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
f24b36ca 116extern std::string NOTARY_PUBKEY;
94a465a6 117extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 118uint32_t Mining_start,Mining_height;
8683bd8d 119int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 120int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
265660f7 121//uint64_t komodo_paxtotal();
d63fdb34 122int32_t komodo_baseid(char *origbase);
001bc04a 123//int32_t komodo_is_issuer();
124//int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
265660f7 125//int32_t komodo_isrealtime(int32_t *kmdheightp);
3bc88f14 126int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
29bd53a1 127int64_t komodo_block_unlocktime(uint32_t nHeight);
18443f69 128uint64_t komodo_commission(const CBlock *block);
d231a6a7 129int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
496f1fd2 130int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
7652ed92 131
48265f3c 132CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
d247a5d1 133{
9339a0cb 134 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
d247a5d1 135 // Create new block
08c58194 136 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 137 if(!pblocktemplate.get())
1b5b89ba 138 {
139 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 140 return NULL;
1b5b89ba 141 }
d247a5d1 142 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
265660f7 143 /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
a5e36fdd 144 {
48a3cd18 145 isrealtime = komodo_isrealtime(&kmdheight);
3da07d2e 146 deposits = komodo_paxtotal();
5ba0ce9d 147 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
ec7ad5f6 148 {
79562bf3 149 deposits = komodo_paxtotal();
16c7bf6b 150 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
79562bf3 151 {
bbaa688c 152 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
79562bf3 153 }
2bec17cb 154 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
4a21ccd2 155 {
eb928486 156 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 157 break;
4a21ccd2 158 }
6fd0ae11 159 sleep(10);
ec7ad5f6 160 }
f24b36ca 161 KOMODO_ON_DEMAND = 0;
16cd9f2d 162 if ( 0 && deposits != 0 )
79562bf3 163 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());
265660f7 164 }*/
dbca89b7
GA
165 // -regtest only: allow overriding block.nVersion with
166 // -blockversion=N to test forking scenarios
167 if (Params().MineBlocksOnDemand())
168 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
e9e70b95 169
4949004d
PW
170 // Add dummy coinbase tx as first transaction
171 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
172 pblocktemplate->vTxFees.push_back(-1); // updated at end
173 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
e9e70b95 174
d247a5d1 175 // Largest block you're willing to create:
ad898b40 176 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
177 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
178 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
e9e70b95 179
d247a5d1
JG
180 // How much of the block should be dedicated to high-priority transactions,
181 // included regardless of the fees they pay
182 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
183 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
e9e70b95 184
d247a5d1
JG
185 // Minimum block size you want to create; block will be filled with free transactions
186 // until there are no more or the block reaches this size:
037b4f14 187 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1 188 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
e9e70b95 189
d247a5d1 190 // Collect memory pool transactions into the block
a372168e 191 CAmount nFees = 0;
e9e70b95 192
d247a5d1
JG
193 {
194 LOCK2(cs_main, mempool.cs);
48265f3c 195 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 196 const int nHeight = pindexPrev->nHeight + 1;
be126699 197 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
a0dd01bc 198
a1d3c6fb 199 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
a0dd01bc 200 uint32_t proposedTime = GetAdjustedTime();
201 if (proposedTime == nMedianTimePast)
202 {
203 // too fast or stuck, this addresses the too fast issue, while moving
204 // forward as quickly as possible
205 for (int i; i < 100; i++)
206 {
207 proposedTime = GetAdjustedTime();
208 if (proposedTime == nMedianTimePast)
209 MilliSleep(10);
210 }
211 }
212 pblock->nTime = GetAdjustedTime();
213
7c70438d 214 CCoinsViewCache view(pcoinsTip);
f9155fec 215 uint32_t expired; uint64_t commission;
6ff77181 216
d247a5d1
JG
217 // Priority order to process transactions
218 list<COrphan> vOrphan; // list memory doesn't move
219 map<uint256, vector<COrphan*> > mapDependers;
220 bool fPrintPriority = GetBoolArg("-printpriority", false);
e9e70b95 221
d247a5d1
JG
222 // This vector will be sorted into a priority queue:
223 vector<TxPriority> vecPriority;
224 vecPriority.reserve(mempool.mapTx.size());
e328fa32 225 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 226 mi != mempool.mapTx.end(); ++mi)
d247a5d1 227 {
e328fa32 228 const CTransaction& tx = mi->GetTx();
e9e70b95 229
a1d3c6fb 230 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
e9e70b95 231 ? nMedianTimePast
232 : pblock->GetBlockTime();
233
9bb37bf0 234 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
61f8caf2 235 {
51376f3c 236 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
14aa6cc0 237 continue;
61f8caf2 238 }
161f617d 239 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
6ff77181 240 {
64b45b71 241 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
d247a5d1 242 continue;
14aa6cc0 243 }
d247a5d1
JG
244 COrphan* porphan = NULL;
245 double dPriority = 0;
a372168e 246 CAmount nTotalIn = 0;
d247a5d1
JG
247 bool fMissingInputs = false;
248 BOOST_FOREACH(const CTxIn& txin, tx.vin)
249 {
250 // Read prev transaction
251 if (!view.HaveCoins(txin.prevout.hash))
252 {
253 // This should never happen; all transactions in the memory
254 // pool should connect to either transactions in the chain
255 // or other transactions in the memory pool.
256 if (!mempool.mapTx.count(txin.prevout.hash))
257 {
881a85a2 258 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
259 if (fDebug) assert("mempool transaction missing input" == 0);
260 fMissingInputs = true;
261 if (porphan)
262 vOrphan.pop_back();
263 break;
264 }
e9e70b95 265
d247a5d1
JG
266 // Has to wait for dependencies
267 if (!porphan)
268 {
269 // Use list for automatic deletion
270 vOrphan.push_back(COrphan(&tx));
271 porphan = &vOrphan.back();
272 }
273 mapDependers[txin.prevout.hash].push_back(porphan);
274 porphan->setDependsOn.insert(txin.prevout.hash);
e328fa32 275 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
276 continue;
277 }
629d75fa
PW
278 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
279 assert(coins);
e9e70b95 280
a372168e 281 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1 282 nTotalIn += nValueIn;
e9e70b95 283
b867e409 284 int nConf = nHeight - coins->nHeight;
e9e70b95 285
d247a5d1
JG
286 dPriority += (double)nValueIn * nConf;
287 }
2b2bc69e 288 nTotalIn += tx.GetJoinSplitValueIn();
e9e70b95 289
d247a5d1 290 if (fMissingInputs) continue;
e9e70b95 291
d6eb2599 292 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 293 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 294 dPriority = tx.ComputePriority(dPriority, nTxSize);
e9e70b95 295
805344dc 296 uint256 hash = tx.GetHash();
2a72d459 297 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
e9e70b95 298
c6cb21d1 299 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
e9e70b95 300
d247a5d1
JG
301 if (porphan)
302 {
303 porphan->dPriority = dPriority;
c6cb21d1 304 porphan->feeRate = feeRate;
d247a5d1
JG
305 }
306 else
e328fa32 307 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1 308 }
e9e70b95 309
d247a5d1 310 // Collect transactions into block
51ed9ec9
BD
311 uint64_t nBlockSize = 1000;
312 uint64_t nBlockTx = 0;
355ca565 313 int64_t interest;
d247a5d1
JG
314 int nBlockSigOps = 100;
315 bool fSortedByFee = (nBlockPrioritySize <= 0);
e9e70b95 316
d247a5d1
JG
317 TxPriorityCompare comparer(fSortedByFee);
318 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
e9e70b95 319
d247a5d1
JG
320 while (!vecPriority.empty())
321 {
322 // Take highest priority transaction off the priority queue:
323 double dPriority = vecPriority.front().get<0>();
c6cb21d1 324 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 325 const CTransaction& tx = *(vecPriority.front().get<2>());
e9e70b95 326
d247a5d1
JG
327 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
328 vecPriority.pop_back();
e9e70b95 329
d247a5d1
JG
330 // Size limits
331 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
01fda4c1 332 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
61f8caf2 333 {
51376f3c 334 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
d247a5d1 335 continue;
61f8caf2 336 }
e9e70b95 337
d247a5d1
JG
338 // Legacy limits on sigOps:
339 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
a4a40a38 340 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 341 {
51376f3c 342 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
d247a5d1 343 continue;
61f8caf2 344 }
d247a5d1 345 // Skip free transactions if we're past the minimum block size:
805344dc 346 const uint256& hash = tx.GetHash();
2a72d459 347 double dPriorityDelta = 0;
a372168e 348 CAmount nFeeDelta = 0;
2a72d459 349 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 350 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
61f8caf2 351 {
51376f3c 352 //fprintf(stderr,"fee rate skip\n");
d247a5d1 353 continue;
61f8caf2 354 }
2a72d459 355 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
356 // transactions:
357 if (!fSortedByFee &&
358 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
359 {
360 fSortedByFee = true;
361 comparer = TxPriorityCompare(fSortedByFee);
362 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
363 }
e9e70b95 364
d247a5d1 365 if (!view.HaveInputs(tx))
61f8caf2 366 {
51376f3c 367 //fprintf(stderr,"dont have inputs\n");
d247a5d1 368 continue;
61f8caf2 369 }
1141b678 370 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
e9e70b95 371
d247a5d1 372 nTxSigOps += GetP2SHSigOpCount(tx, view);
a4a40a38 373 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 374 {
51376f3c 375 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
d247a5d1 376 continue;
61f8caf2 377 }
68f7d1d7
PT
378 // Note that flags: we don't want to set mempool/IsStandard()
379 // policy here, but we still have to ensure that the block we
380 // create only contains transactions that are valid in new blocks.
d247a5d1 381 CValidationState state;
6514771a 382 PrecomputedTransactionData txdata(tx);
be126699 383 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
61f8caf2 384 {
51376f3c 385 //fprintf(stderr,"context failure\n");
d247a5d1 386 continue;
61f8caf2 387 }
8cb98d91 388 UpdateCoins(tx, view, nHeight);
e9e70b95 389
d247a5d1
JG
390 // Added
391 pblock->vtx.push_back(tx);
392 pblocktemplate->vTxFees.push_back(nTxFees);
393 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
394 nBlockSize += nTxSize;
395 ++nBlockTx;
396 nBlockSigOps += nTxSigOps;
397 nFees += nTxFees;
e9e70b95 398
d247a5d1
JG
399 if (fPrintPriority)
400 {
3f0813b3 401 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1 402 }
e9e70b95 403
d247a5d1
JG
404 // Add transactions that depend on this one to the priority queue
405 if (mapDependers.count(hash))
406 {
407 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
408 {
409 if (!porphan->setDependsOn.empty())
410 {
411 porphan->setDependsOn.erase(hash);
412 if (porphan->setDependsOn.empty())
413 {
c6cb21d1 414 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
415 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
416 }
417 }
418 }
419 }
420 }
e9e70b95 421
d247a5d1
JG
422 nLastBlockTx = nBlockTx;
423 nLastBlockSize = nBlockSize;
d07308d2 424 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9a0f2798 425 //pblock->nTime = blocktime + 1;
357e4ca5 426 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
7dbeae5d 427 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
a4a40a38 428 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
429 {
69530bb2 430 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
d231a6a7 431 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
cfb55edb 432 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
433 // blocktime = pindexPrev->GetMedianTimePast() + 60;
d231a6a7 434 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
a4a40a38 435 {
66b4e563 436 CAmount txfees = 0;
de230f5e 437 if ( GetAdjustedTime() < blocktime-13 )
ba1587fd 438 return(0);
a4a40a38 439 pblock->vtx.push_back(txStaked);
a4a40a38 440 pblocktemplate->vTxFees.push_back(txfees);
d231a6a7 441 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
a4a40a38 442 nFees += txfees;
9339a0cb 443 pblock->nTime = blocktime;
de230f5e 444 //printf("PoS ht.%d t%u\n",(int32_t)chainActive.Tip()->nHeight+1,blocktime);
9464ac21 445 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
a4a40a38 446 }
e9e70b95 447
f3ffa3d2 448 // Create coinbase tx
072099d7 449 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
450 txNew.vin.resize(1);
451 txNew.vin[0].prevout.SetNull();
abb90a89
MT
452 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
453
d581f229 454 txNew.vout.resize(1);
f3ffa3d2 455 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
abb90a89 456 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees;
9bb37bf0 457 txNew.nExpiryHeight = 0;
48d800c2 458 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
abb90a89 459
29bd53a1 460 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
a0dd01bc 461 // to transaction if so, cast for GTE operator
462 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
abb90a89
MT
463 {
464 int32_t opretlen, p2shlen, scriptlen;
29bd53a1 465 CScriptExt opretScript = CScriptExt();
abb90a89
MT
466
467 txNew.vout.resize(2);
468
29bd53a1
MT
469 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
470 // protected only by the time lock rather than 100% inaccessible
471 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
472 if (!scriptPubKeyIn.IsPayToScriptHash())
473 opretScript += scriptPubKeyIn;
abb90a89 474
29bd53a1
MT
475 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
476 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
abb90a89 477 txNew.vout[1].nValue = 0;
48d800c2 478 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
479 else if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
c9b1071d 480 {
c000c9ca 481 int32_t i; uint8_t *ptr;
9ed1be03 482 txNew.vout.resize(2);
483 txNew.vout[1].nValue = commission;
484 txNew.vout[1].scriptPubKey.resize(35);
485 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
c000c9ca 486 ptr[0] = 33;
487 for (i=0; i<33; i++)
488 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
489 ptr[34] = OP_CHECKSIG;
146d2aa2 490 //printf("autocreate commision vout\n");
c9b1071d 491 }
48d800c2 492
4949004d 493 pblock->vtx[0] = txNew;
d247a5d1 494 pblocktemplate->vTxFees[0] = -nFees;
48d800c2 495
8e165d57
JG
496 // Randomise nonce
497 arith_uint256 nonce = UintToArith256(GetRandHash());
48d800c2 498
42181656 499 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
500 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
8e165d57
JG
501 nonce >>= 16;
502 pblock->nNonce = ArithToUint256(nonce);
e9e70b95 503
d247a5d1
JG
504 // Fill in header
505 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 506 pblock->hashReserved = uint256();
9a0f2798 507 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
508 {
509 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
510 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
511 }
fdda3c50 512 pblock->nSolution.clear();
d247a5d1 513 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
496f1fd2 514 if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
af805d53 515 {
496f1fd2 516 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
f31815fc 517 if ( pblock->nTime < pindexPrev->nTime+65 )
c670f024 518 pblock->nTime = pindexPrev->nTime + 65;
a893e994 519 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
496f1fd2 520 {
521 CAmount txfees = 0;
522 pblock->vtx.push_back(txNotary);
523 pblocktemplate->vTxFees.push_back(txfees);
524 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
525 nFees += txfees;
f31815fc 526 //fprintf(stderr,"added notaryvin\n");
0857c3d5 527 }
528 else
529 {
530 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
531 return(0);
532 }
707b061c 533 }
8fc79ac9 534 else
af805d53 535 {
8fc79ac9 536 CValidationState state;
537 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
538 {
539 //static uint32_t counter;
540 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
541 // fprintf(stderr,"warning: miner testblockvalidity failed\n");
542 return(0);
543 }
af805d53 544 }
d247a5d1 545 }
e9e70b95 546
d247a5d1
JG
547 return pblocktemplate.release();
548}
32b915c9 549
1a31463b 550/*
e9e70b95 551 #ifdef ENABLE_WALLET
552 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
553 #else
554 boost::optional<CScript> GetMinerScriptPubKey()
555 #endif
556 {
557 CKeyID keyID;
558 CBitcoinAddress addr;
559 if (addr.SetString(GetArg("-mineraddress", ""))) {
560 addr.GetKeyID(keyID);
561 } else {
562 #ifdef ENABLE_WALLET
563 CPubKey pubkey;
564 if (!reservekey.GetReservedKey(pubkey)) {
565 return boost::optional<CScript>();
566 }
567 keyID = pubkey.GetID();
568 #else
569 return boost::optional<CScript>();
570 #endif
571 }
572
573 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
574 return scriptPubKey;
575 }
576
577 #ifdef ENABLE_WALLET
578 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
579 {
580 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
581 #else
582 CBlockTemplate* CreateNewBlockWithKey()
583 {
584 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
585 #endif
586
587 if (!scriptPubKey) {
588 return NULL;
589 }
590 return CreateNewBlock(*scriptPubKey);
591 }*/
acfa0333 592
c1de826f
JG
593//////////////////////////////////////////////////////////////////////////////
594//
595// Internal miner
596//
597
2cc0a252 598#ifdef ENABLE_MINING
c1de826f 599
d247a5d1
JG
600void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
601{
602 // Update nExtraNonce
603 static uint256 hashPrevBlock;
604 if (hashPrevBlock != pblock->hashPrevBlock)
605 {
606 nExtraNonce = 0;
607 hashPrevBlock = pblock->hashPrevBlock;
608 }
609 ++nExtraNonce;
610 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
611 CMutableTransaction txCoinbase(pblock->vtx[0]);
612 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
613 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
e9e70b95 614
4949004d 615 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
616 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
617}
618
4a85e067 619#ifdef ENABLE_WALLET
acfa0333
WL
620//////////////////////////////////////////////////////////////////////////////
621//
622// Internal miner
623//
acfa0333 624
48265f3c 625CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 626{
f6c647ed 627 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 628 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 629 {
7bfc207a 630 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 631 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 632 }
633 else
634 {
635 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 636 {
f6c647ed 637 return NULL;
1b5b89ba 638 }
f6c647ed 639 scriptPubKey.resize(35);
f66f65ec 640 ptr = (uint8_t *)pubkey.begin();
f6c647ed 641 script = (uint8_t *)scriptPubKey.data();
642 script[0] = 33;
643 for (i=0; i<33; i++)
644 script[i+1] = ptr[i];
645 script[34] = OP_CHECKSIG;
646 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
647 }
48265f3c 648 return CreateNewBlock(scriptPubKey);
acfa0333
WL
649}
650
395f10cf 651void komodo_broadcast(CBlock *pblock,int32_t limit)
652{
653 int32_t n = 1;
654 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
655 {
656 LOCK(cs_vNodes);
657 BOOST_FOREACH(CNode* pnode, vNodes)
658 {
659 if ( pnode->hSocket == INVALID_SOCKET )
660 continue;
661 if ( (rand() % n) == 0 )
662 {
663 pnode->PushMessage("block", *pblock);
664 if ( n++ > limit )
665 break;
666 }
667 }
668 }
669 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
670}
945f015d 671
269d8ba0 672static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
673#else
674static bool ProcessBlockFound(CBlock* pblock)
675#endif // ENABLE_WALLET
d247a5d1 676{
81212588 677 LogPrintf("%s\n", pblock->ToString());
35915149 678 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
e9e70b95 679
d247a5d1
JG
680 // Found a solution
681 {
682 LOCK(cs_main);
4c6d41b8 683 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
ba8419c7 684 {
685 uint256 hash; int32_t i;
686 hash = pblock->hashPrevBlock;
92266e99 687 for (i=31; i>=0; i--)
ba8419c7 688 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 689 fprintf(stderr," <- prev (stale)\n");
ba8419c7 690 hash = chainActive.Tip()->GetBlockHash();
92266e99 691 for (i=31; i>=0; i--)
ba8419c7 692 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 693 fprintf(stderr," <- chainTip (stale)\n");
e9e70b95 694
2e500f50 695 return error("KomodoMiner: generated block is stale");
ba8419c7 696 }
18e72167 697 }
e9e70b95 698
8e8b6d70 699#ifdef ENABLE_WALLET
18e72167 700 // Remove key from key pool
998397aa 701 if ( IS_KOMODO_NOTARY == 0 )
945f015d 702 {
703 if (GetArg("-mineraddress", "").empty()) {
704 // Remove key from key pool
705 reservekey.KeepKey();
706 }
8e8b6d70 707 }
18e72167 708 // Track how many getdata requests this block gets
438ba9c1 709 //if ( 0 )
18e72167
PW
710 {
711 LOCK(wallet.cs_wallet);
712 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 713 }
8e8b6d70 714#endif
e9e70b95 715
18e72167
PW
716 // Process this block the same as if we had received it from another node
717 CValidationState state;
7bb789bb 718 if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 719 return error("KomodoMiner: ProcessNewBlock, block not accepted");
e9e70b95 720
d793f94b 721 TrackMinedBlock(pblock->GetHash());
395f10cf 722 komodo_broadcast(pblock,16);
d247a5d1
JG
723 return true;
724}
725
078f6af1 726int32_t komodo_baseid(char *origbase);
a30dd993 727int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
13691369 728arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
8ee93080 729int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 730extern int32_t KOMODO_LASTMINED;
8b51b9e4 731int32_t roundrobin_delay;
18443f69 732arith_uint256 HASHTarget,HASHTarget_POW;
078f6af1 733
5642c96c 734// wait for peers to connect
b45d65b4 735int32_t waitForPeers(const CChainParams &chainparams)
5642c96c 736{
737 if (chainparams.MiningRequiresPeers())
738 {
739 do {
740 bool fvNodesEmpty;
741 {
742 LOCK(cs_vNodes);
743 fvNodesEmpty = vNodes.empty();
744 }
745 if (!fvNodesEmpty )
746 break;
747 MilliSleep(1000);
748 } while (true);
749 }
750}
751
42181656 752#ifdef ENABLE_WALLET
753void static BitcoinMiner_noeq(CWallet *pwallet)
754#else
755void static BitcoinMiner_noeq()
756#endif
757{
05f6e633 758 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
05f6e633 759 RenameThread("verushash-miner");
42181656 760
761#ifdef ENABLE_WALLET
762 // Each thread has its own key
763 CReserveKey reservekey(pwallet);
764#endif
765
2910478b 766 const CChainParams& chainparams = Params();
42181656 767 // Each thread has its own counter
768 unsigned int nExtraNonce = 0;
769 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
770 solnPlaceholder.resize(Eh200_9.SolutionWidth);
42181656 771 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
772
773 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
774 {
775 sleep(1);
776 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
777 break;
778 }
9f3e2213 779
5642c96c 780 // try a nice clean peer connection to start
781 waitForPeers(chainparams);
6176a421 782 sleep(5);
9f3e2213 783 CBlockIndex* curTip;
784 do {
785 curTip = chainActive.Tip();
6176a421 786 printf("Verifying block height %d \n", chainActive.Tip()->nHeight);
204cf3fc 787 MilliSleep(1000 + rand() % 1900);
9f3e2213 788 } while (curTip != chainActive.Tip());
6176a421 789
790 SetThreadPriority(THREAD_PRIORITY_LOWEST);
791
792 sleep(5);
a62041d9 793 printf("Mining height %d\n", chainActive.Tip()->nHeight + 1);
9f3e2213 794
42181656 795 miningTimer.start();
796
797 try {
05f6e633 798 fprintf(stderr,"Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 799 while (true)
800 {
68334c8d 801 miningTimer.stop();
802 waitForPeers(chainparams);
803 miningTimer.start();
42181656 804
805 // Create new block
806 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
807 CBlockIndex* pindexPrev = chainActive.Tip();
808 if ( Mining_height != pindexPrev->nHeight+1 )
809 {
810 Mining_height = pindexPrev->nHeight+1;
811 Mining_start = (uint32_t)time(NULL);
812 }
813
814 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
815
816#ifdef ENABLE_WALLET
817 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
818#else
819 CBlockTemplate *ptr = CreateNewBlockWithKey();
820#endif
821 if ( ptr == 0 )
822 {
823 static uint32_t counter;
824 if ( counter++ < 100 )
825 fprintf(stderr,"created illegal block, retry\n");
826 continue;
827 }
828 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
829 if (!pblocktemplate.get())
830 {
831 if (GetArg("-mineraddress", "").empty()) {
05f6e633 832 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
833 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 834 } else {
835 // Should never reach here, because -mineraddress validity is checked in init.cpp
05f6e633 836 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
42181656 837 }
838 return;
839 }
840 CBlock *pblock = &pblocktemplate->block;
841 if ( ASSETCHAINS_SYMBOL[0] != 0 )
842 {
843 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
844 {
845 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
846 {
847 static uint32_t counter;
848 if ( counter++ < 10 )
849 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
850 sleep(10);
851 continue;
852 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
853 }
854 }
855 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
856 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
857 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
858 //
859 // Search
860 //
861 uint32_t savebits; int64_t nStart = GetTime();
862
863 pblock->nSolution = solnPlaceholder;
864 savebits = pblock->nBits;
865 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
866 arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
867
868 Mining_start = 0;
ef70c5b2 869
ef70c5b2 870 if ( pindexPrev != chainActive.Tip() )
05f6e633 871 {
6176a421 872 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
873 MilliSleep(250);
05f6e633 874 continue;
875 }
ef70c5b2 876
42181656 877 while (true)
878 {
879 // for speed check multiples at a time
880 for (int i = 0; i < ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; i++)
881 {
882 solutionTargetChecks.increment();
883
884 // Update nNonce and nTime
885 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
886
887 if ( UintToArith256(pblock->GetHash()) <= hashTarget )
888 {
889 SetThreadPriority(THREAD_PRIORITY_NORMAL);
890
ef70c5b2 891 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
892 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
893
42181656 894 LogPrintf("KomodoMiner using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
895 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
14d104e9 896 printf("Found block %d \n", Mining_height );
a62041d9 897 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
ef70c5b2 898 printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
899 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
900 printf("- timelocked until block %i\n", unlockTime);
901 else
902 printf("\n");
903
42181656 904#ifdef ENABLE_WALLET
905 ProcessBlockFound(pblock, *pwallet, reservekey);
906#else
907 ProcessBlockFound(pblock));
908#endif
909 SetThreadPriority(THREAD_PRIORITY_LOWEST);
910
911 // In regression test mode, stop mining after a block is found.
912 if (chainparams.MineBlocksOnDemand()) {
913 throw boost::thread_interrupted();
914 }
915 break;
916 }
ef70c5b2 917 else
42181656 918 {
ef70c5b2 919 if ((UintToArith256(pblock->nNonce) & mask) == mask)
920 {
921 break;
922 }
42181656 923 }
924 }
925
926 // Check for stop or if block needs to be rebuilt
927 boost::this_thread::interruption_point();
928
929 if (vNodes.empty() && chainparams.MiningRequiresPeers())
930 {
931 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
932 {
ef70c5b2 933 fprintf(stderr,"no nodes, attempting reconnect\n");
42181656 934 break;
935 }
936 }
937
938 if ((UintToArith256(pblock->nNonce) & mask) == mask)
939 {
5642c96c 940 fprintf(stderr,"%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
42181656 941 break;
942 }
943
944 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
945 {
ef70c5b2 946 fprintf(stderr,"timeout, retrying\n");
42181656 947 break;
948 }
949
950 if ( pindexPrev != chainActive.Tip() )
951 {
6176a421 952 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
42181656 953 break;
954 }
955
956 pblock->nBits = savebits;
957 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
958 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
959 {
960 // Changing pblock->nTime can change work required on testnet:
961 hashTarget.SetCompact(pblock->nBits);
962 }
963 }
964 }
965 }
966 catch (const boost::thread_interrupted&)
967 {
968 miningTimer.stop();
969 LogPrintf("KomodoMiner terminated\n");
970 throw;
971 }
972 catch (const std::runtime_error &e)
973 {
974 miningTimer.stop();
975 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
976 return;
977 }
978 miningTimer.stop();
979}
980
8e8b6d70 981#ifdef ENABLE_WALLET
d247a5d1 982void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
983#else
984void static BitcoinMiner()
985#endif
d247a5d1 986{
2e500f50 987 LogPrintf("KomodoMiner started\n");
d247a5d1 988 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 989 RenameThread("komodo-miner");
bebe7282 990 const CChainParams& chainparams = Params();
e9e70b95 991
8e8b6d70
JG
992#ifdef ENABLE_WALLET
993 // Each thread has its own key
d247a5d1 994 CReserveKey reservekey(pwallet);
8e8b6d70 995#endif
e9e70b95 996
8e8b6d70 997 // Each thread has its own counter
d247a5d1 998 unsigned int nExtraNonce = 0;
e9e70b95 999
e9574728
JG
1000 unsigned int n = chainparams.EquihashN();
1001 unsigned int k = chainparams.EquihashK();
8683bd8d 1002 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
b7ba6413 1003 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 1004 {
1005 sleep(1);
4e624c04 1006 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1007 break;
755ead98 1008 }
8683bd8d 1009 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
e9e70b95 1010
755ead98 1011 std::string solver;
e1e65cef 1012 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
e9e70b95 1013 solver = "tromp";
e1e65cef 1014 //else solver = "default";
5f0009b2 1015 assert(solver == "tromp" || solver == "default");
c7aaab7a 1016 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 1017 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 1018 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
1019 std::mutex m_cs;
1020 bool cancelSolver = false;
1021 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
e9e70b95 1022 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1023 std::lock_guard<std::mutex> lock{m_cs};
1024 cancelSolver = true;
1025 }
1026 );
07be8f7e 1027 miningTimer.start();
e9e70b95 1028
0655fac0 1029 try {
ad84148d 1030 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 1031 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 1032 while (true)
1033 {
2c70b583 1034 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 1035 {
a96fd7b5 1036 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
1037 // break;
0655fac0
PK
1038 // Busy-wait for the network to come online so we don't waste time mining
1039 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 1040 miningTimer.stop();
bba7c249
GM
1041 do {
1042 bool fvNodesEmpty;
1043 {
373668be 1044 //LOCK(cs_vNodes);
bba7c249
GM
1045 fvNodesEmpty = vNodes.empty();
1046 }
269fe243 1047 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 1048 break;
f8e367eb 1049 MilliSleep(5000);
ad84148d 1050 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
e9e70b95 1051
bba7c249 1052 } while (true);
ad84148d 1053 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 1054 miningTimer.start();
0655fac0 1055 }
f70ced6a 1056 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
e9e70b95 1057 {
1058 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
1059 sleep(3);
1060 }*/
0655fac0
PK
1061 //
1062 // Create new block
1063 //
1064 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 1065 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 1066 if ( Mining_height != pindexPrev->nHeight+1 )
1067 {
1068 Mining_height = pindexPrev->nHeight+1;
1069 Mining_start = (uint32_t)time(NULL);
1070 }
8e9ef91c 1071 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 1072 {
40304479 1073 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2825c0b5 1074 sleep(3);
1075 }
8e8b6d70 1076#ifdef ENABLE_WALLET
08d0b73c 1077 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
8e8b6d70 1078#else
945f015d 1079 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 1080#endif
08d0b73c 1081 if ( ptr == 0 )
1082 {
d0f7ead0 1083 static uint32_t counter;
5bb3d0fe 1084 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 1085 fprintf(stderr,"created illegal block, retry\n");
8fc79ac9 1086 sleep(1);
d0f7ead0 1087 continue;
08d0b73c 1088 }
1089 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 1090 if (!pblocktemplate.get())
6c37f7fd 1091 {
8e8b6d70 1092 if (GetArg("-mineraddress", "").empty()) {
945f015d 1093 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
1094 } else {
1095 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 1096 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 1097 }
0655fac0 1098 return;
6c37f7fd 1099 }
0655fac0 1100 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 1101 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1102 {
42181656 1103 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
16c7bf6b 1104 {
8683bd8d 1105 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1106 {
1107 static uint32_t counter;
1108 if ( counter++ < 10 )
1109 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1110 sleep(10);
1111 continue;
1112 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1113 }
16c7bf6b 1114 }
0655fac0 1115 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 1116 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
1117 //
1118 // Search
1119 //
a30dd993 1120 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
404391b5 1121 savebits = pblock->nBits;
88287857 1122 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
f0100e72 1123 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 1124 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 1125 {
fda5f849 1126 j = 65;
5a471ba9 1127 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 1128 {
4fff8a63 1129 int32_t dispflag = 0;
ef70c5b2 1130 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
4fff8a63 1131 dispflag = 1;
a30dd993 1132 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
29e60e48 1133 if ( nonzpkeys > 0 )
1134 {
ccb71a6e 1135 for (i=0; i<33; i++)
1136 if( pubkeys[0][i] != 0 )
1137 break;
1138 if ( i == 33 )
1139 externalflag = 1;
1140 else externalflag = 0;
e4a383e3 1141 if ( NOTARY_PUBKEY33[0] != 0 )
b176c125 1142 {
345e545e 1143 for (i=1; i<66; i++)
1144 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1145 break;
6494f040 1146 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1147 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
2c7ad758 1148 for (j=gpucount=0; j<65; j++)
1149 {
4fff8a63 1150 if ( dispflag != 0 )
e4a383e3 1151 {
1152 if ( mids[j] >= 0 )
1153 fprintf(stderr,"%d ",mids[j]);
1154 else fprintf(stderr,"GPU ");
1155 }
2c7ad758 1156 if ( mids[j] == -1 )
1157 gpucount++;
1158 }
b000fa04 1159 if ( gpucount > j/2 )
f0100e72 1160 {
dd98c02d 1161 double delta;
d2d3c766 1162 if ( notaryid < 0 )
1163 i = (rand() % 64);
1164 else i = ((Mining_height + notaryid) % 64);
b000fa04 1165 delta = sqrt((double)gpucount - j/2) / 2.;
dd98c02d 1166 roundrobin_delay += ((delta * i) / 64) - delta;
67478d4a 1167 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
f0100e72 1168 }
4fff8a63 1169 if ( dispflag != 0 )
2c7ba74d 1170 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 1171 }
29e60e48 1172 for (j=0; j<65; j++)
1173 if ( mids[j] == notaryid )
1174 break;
49b49585 1175 if ( j == 65 )
1176 KOMODO_LASTMINED = 0;
965f0f7e 1177 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 1178 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 1179 {
88287857 1180 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
fda5f849 1181 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
1182 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 1183 } else Mining_start = 0;
d7d27bb3 1184 } else Mining_start = 0;
deba7f20 1185 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
e725f1cb 1186 {
deba7f20 1187 int32_t percPoS,z;
d9935f2b 1188 /*if ( Mining_height <= 100 )
16cd9f2d 1189 {
c966741f 1190 sleep(60);
1191 continue;
16c7bf6b 1192 }*/
18443f69 1193 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
deba7f20 1194 for (z=31; z>=0; z--)
8fbee929 1195 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
b509fdae 1196 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
deba7f20 1197 }
e725f1cb 1198 while (true)
1199 {
16c7bf6b 1200 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
e9e70b95 1201 {
1202 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1203 sleep(10);
1204 break;
1205 }*/
7213c0b1 1206 // Hash state
8c22eb46 1207 KOMODO_CHOSEN_ONE = 0;
42181656 1208
7213c0b1 1209 crypto_generichash_blake2b_state state;
e9574728 1210 EhInitialiseState(n, k, state);
7213c0b1
JG
1211 // I = the block header minus nonce and solution.
1212 CEquihashInput I{*pblock};
1213 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1214 ss << I;
7213c0b1
JG
1215 // H(I||...
1216 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
1217 // H(I||V||...
1218 crypto_generichash_blake2b_state curr_state;
1219 curr_state = state;
7a4c01c9 1220 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 1221 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 1222 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
18443f69 1223 arith_uint256 hashTarget;
1224 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 )
1225 hashTarget = HASHTarget_POW;
1226 else hashTarget = HASHTarget;
5be6abbf 1227 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 1228#ifdef ENABLE_WALLET
e9e70b95 1229 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1230#else
e9e70b95 1231 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1232#endif
e9e70b95 1233 (std::vector<unsigned char> soln) {
c21c6306 1234 int32_t z; arith_uint256 h; CBlock B;
51eb5273
JG
1235 // Write the solution to the hash and compute the result.
1236 LogPrint("pow", "- Checking solution against target\n");
8e165d57 1237 pblock->nSolution = soln;
e7d59bbc 1238 solutionTargetChecks.increment();
eff2c3a3 1239 B = *pblock;
1240 h = UintToArith256(B.GetHash());
c21c6306 1241 if ( h > hashTarget )
51eb5273 1242 return false;
eff2c3a3 1243 /*for (z=31; z>=16; z--)
02c30aac 1244 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
aea2d1aa 1245 fprintf(stderr," mined ");
1246 for (z=31; z>=16; z--)
18443f69 1247 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
aea2d1aa 1248 fprintf(stderr," hashTarget ");
1249 for (z=31; z>=16; z--)
18443f69 1250 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
eff2c3a3 1251 fprintf(stderr," POW\n");*/
6181f7d5 1252 if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
d7d27bb3 1253 {
97e9d76e 1254 fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
596b05ba 1255 while ( GetAdjustedTime() < B.nTime-2 )
8e9ef91c 1256 {
eb1ba5a0 1257 sleep(1);
4cc387ec 1258 if ( chainActive.Tip()->nHeight >= Mining_height )
1259 {
1260 fprintf(stderr,"new block arrived\n");
1261 return(false);
1262 }
8e9ef91c 1263 }
eb1ba5a0 1264 }
8e9ef91c 1265 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 1266 {
9703f8a0 1267 if ( NOTARY_PUBKEY33[0] != 0 )
8e9ef91c 1268 {
26810a26 1269 int32_t r;
9703f8a0 1270 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
596b05ba 1271 MilliSleep((rand() % (r * 1000)) + 1000);
ef70c5b2 1272 }
e5430f52 1273 }
8e9ef91c 1274 else
d7d27bb3 1275 {
deba7f20 1276 if ( NOTARY_PUBKEY33[0] != 0 )
1277 {
ef70c5b2 1278 printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
eff2c3a3 1279 while ( GetAdjustedTime() < B.nTime )
deba7f20 1280 sleep(1);
1281 }
68d0354d 1282 else
1283 {
286d95b1 1284 uint256 tmp = B.GetHash();
b7aaca4b 1285 int32_t z; for (z=31; z>=0; z--)
1286 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1287 fprintf(stderr," mined block!\n");
68d0354d 1288 }
d7d27bb3 1289 }
8fc79ac9 1290 CValidationState state;
1291 if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
d2d3c766 1292 {
8fc79ac9 1293 h = UintToArith256(B.GetHash());
1294 for (z=31; z>=0; z--)
1295 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1296 fprintf(stderr," Invalid block mined, try again\n");
1297 return(false);
d2d3c766 1298 }
b3183e3e 1299 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
1300 // Found a solution
1301 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 1302 LogPrintf("KomodoMiner:\n");
eff2c3a3 1303 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 1304#ifdef ENABLE_WALLET
eff2c3a3 1305 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
8e8b6d70 1306#else
eff2c3a3 1307 if (ProcessBlockFound(&B)) {
8e8b6d70 1308#endif
e9e70b95 1309 // Ignore chain updates caused by us
1310 std::lock_guard<std::mutex> lock{m_cs};
1311 cancelSolver = false;
1312 }
1313 KOMODO_CHOSEN_ONE = 0;
1314 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1315 // In regression test mode, stop mining after a block is found.
1316 if (chainparams.MineBlocksOnDemand()) {
1317 // Increment here because throwing skips the call below
1318 ehSolverRuns.increment();
1319 throw boost::thread_interrupted();
1320 }
1321 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1322 // sleep(1800);
1323 return true;
1324 };
1325 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
a6a0d913 1326 std::lock_guard<std::mutex> lock{m_cs};
e9e70b95 1327 return cancelSolver;
1328 };
1329
1330 // TODO: factor this out into a function with the same API for each solver.
1331 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1332 // Create solver and initialize it.
1333 equi eq(1);
1334 eq.setstate(&curr_state);
1335
1336 // Initialization done, start algo driver.
1337 eq.digit0(0);
c7aaab7a 1338 eq.xfull = eq.bfull = eq.hfull = 0;
e9e70b95 1339 eq.showbsizes(0);
1340 for (u32 r = 1; r < WK; r++) {
1341 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1342 eq.xfull = eq.bfull = eq.hfull = 0;
1343 eq.showbsizes(r);
c7aaab7a 1344 }
e9e70b95 1345 eq.digitK(0);
1346 ehSolverRuns.increment();
1347
1348 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1349 for (size_t s = 0; s < eq.nsols; s++) {
1350 LogPrint("pow", "Checking solution %d\n", s+1);
1351 std::vector<eh_index> index_vector(PROOFSIZE);
1352 for (size_t i = 0; i < PROOFSIZE; i++) {
1353 index_vector[i] = eq.sols[s][i];
1354 }
1355 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1356
1357 if (validBlock(sol_char)) {
1358 // If we find a POW solution, do not try other solutions
1359 // because they become invalid as we created a new block in blockchain.
1360 break;
1361 }
1362 }
1363 } else {
1364 try {
1365 // If we find a valid block, we rebuild
1366 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1367 ehSolverRuns.increment();
1368 if (found) {
997ddd92 1369 int32_t i; uint256 hash = pblock->GetHash();
e9e70b95 1370 for (i=0; i<32; i++)
1371 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1372 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1373 FOUND_BLOCK = 1;
1374 KOMODO_MAYBEMINED = Mining_height;
1375 break;
1376 }
1377 } catch (EhSolverCancelledException&) {
1378 LogPrint("pow", "Equihash solver cancelled\n");
1379 std::lock_guard<std::mutex> lock{m_cs};
1380 cancelSolver = false;
c7aaab7a
DH
1381 }
1382 }
e9e70b95 1383
1384 // Check for stop or if block needs to be rebuilt
1385 boost::this_thread::interruption_point();
1386 // Regtest mode doesn't require peers
1387 if ( FOUND_BLOCK != 0 )
1388 {
1389 FOUND_BLOCK = 0;
1390 fprintf(stderr,"FOUND_BLOCK!\n");
1391 //sleep(2000);
1392 }
1393 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1394 {
1395 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1396 {
1397 fprintf(stderr,"no nodes, break\n");
c7aaab7a 1398 break;
a6df7ab5 1399 }
c7aaab7a 1400 }
997ddd92 1401 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
10694486 1402 {
e9e70b95 1403 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1404 fprintf(stderr,"0xffff, break\n");
d90cef0b 1405 break;
10694486 1406 }
e9e70b95 1407 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1408 {
1409 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1410 fprintf(stderr,"timeout, break\n");
1411 break;
1412 }
1413 if ( pindexPrev != chainActive.Tip() )
1414 {
1415 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1416 fprintf(stderr,"Tip advanced, break\n");
1417 break;
1418 }
1419 // Update nNonce and nTime
1420 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1421 pblock->nBits = savebits;
18dd6a3b 1422 /*if ( NOTARY_PUBKEY33[0] == 0 )
e9e70b95 1423 {
f8f740a9 1424 int32_t percPoS;
23fc88bb 1425 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1426 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1427 {
1428 // Changing pblock->nTime can change work required on testnet:
1429 HASHTarget.SetCompact(pblock->nBits);
18443f69 1430 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
23fc88bb 1431 }
18dd6a3b 1432 }*/
48265f3c 1433 }
d247a5d1
JG
1434 }
1435 }
e9e70b95 1436 catch (const boost::thread_interrupted&)
1437 {
1438 miningTimer.stop();
1439 c.disconnect();
1440 LogPrintf("KomodoMiner terminated\n");
1441 throw;
1442 }
1443 catch (const std::runtime_error &e)
1444 {
1445 miningTimer.stop();
1446 c.disconnect();
1447 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1448 return;
1449 }
07be8f7e 1450 miningTimer.stop();
5e9b555f 1451 c.disconnect();
bba7c249 1452 }
e9e70b95 1453
8e8b6d70 1454#ifdef ENABLE_WALLET
e9e70b95 1455 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70 1456#else
e9e70b95 1457 void GenerateBitcoins(bool fGenerate, int nThreads)
8e8b6d70 1458#endif
d247a5d1 1459 {
e9e70b95 1460 static boost::thread_group* minerThreads = NULL;
1461
1462 if (nThreads < 0)
1463 nThreads = GetNumCores();
1464
1465 if (minerThreads != NULL)
1466 {
1467 minerThreads->interrupt_all();
1468 delete minerThreads;
1469 minerThreads = NULL;
1470 }
1471
1472 if (nThreads == 0 || !fGenerate)
1473 return;
1474
1475 minerThreads = new boost::thread_group();
1476 for (int i = 0; i < nThreads; i++) {
8e8b6d70 1477#ifdef ENABLE_WALLET
42181656 1478 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1479 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1480 else
1481 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
8e8b6d70 1482#else
42181656 1483 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1484 minerThreads->create_thread(&BitcoinMiner);
1485 else
1486 minerThreads->create_thread(&BitcoinMiner_noeq);
8e8b6d70 1487#endif
e9e70b95 1488 }
8e8b6d70 1489 }
e9e70b95 1490
2cc0a252 1491#endif // ENABLE_MINING
This page took 0.657466 seconds and 4 git commands to generate.