]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Debugging
[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"
bebe7282 12#include "chainparams.h"
06f41160 13#include "cc/CoinbaseGuard.h"
20c3ac51 14#include "importcoin.h"
691161d4 15#include "consensus/consensus.h"
be126699 16#include "consensus/upgrades.h"
da29ecbc 17#include "consensus/validation.h"
8e8b6d70
JG
18#ifdef ENABLE_MINING
19#include "crypto/equihash.h"
42181656 20#include "crypto/verus_hash.h"
8e8b6d70 21#endif
85aab2a0 22#include "hash.h"
93bd00a0 23#include "key_io.h"
d247a5d1 24#include "main.h"
a6df7ab5 25#include "metrics.h"
51ed9ec9 26#include "net.h"
df852d2b 27#include "pow.h"
bebe7282 28#include "primitives/transaction.h"
8e165d57 29#include "random.h"
22c4272b 30#include "timedata.h"
8e8b6d70 31#include "ui_interface.h"
ad49c256
WL
32#include "util.h"
33#include "utilmoneystr.h"
df840de5 34#ifdef ENABLE_WALLET
50c72f23 35#include "wallet/wallet.h"
df840de5 36#endif
09eb201b 37
fdda3c50
JG
38#include "sodium.h"
39
ad49c256 40#include <boost/thread.hpp>
a3c26c2e 41#include <boost/tuple/tuple.hpp>
8e8b6d70
JG
42#ifdef ENABLE_MINING
43#include <functional>
44#endif
5a360a5c 45#include <mutex>
ad49c256 46
09eb201b 47using namespace std;
7b4737c8 48
d247a5d1
JG
49//////////////////////////////////////////////////////////////////////////////
50//
51// BitcoinMiner
52//
53
c6cb21d1
GA
54//
55// Unconfirmed transactions in the memory pool often depend on other
56// transactions in the memory pool. When we select transactions from the
57// pool, we select by highest priority or fee rate, so we might consider
58// transactions that depend on transactions that aren't yet in the block.
59// The COrphan class keeps track of these 'temporary orphans' while
60// CreateBlock is figuring out which transactions to include.
61//
d247a5d1
JG
62class COrphan
63{
64public:
4d707d51 65 const CTransaction* ptx;
d247a5d1 66 set<uint256> setDependsOn;
c6cb21d1 67 CFeeRate feeRate;
02bec4b2 68 double dPriority;
e9e70b95 69
c6cb21d1 70 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 71 {
d247a5d1 72 }
d247a5d1
JG
73};
74
51ed9ec9
BD
75uint64_t nLastBlockTx = 0;
76uint64_t nLastBlockSize = 0;
d247a5d1 77
c6cb21d1
GA
78// We want to sort transactions by priority and fee rate, so:
79typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
80class TxPriorityCompare
81{
82 bool byFee;
e9e70b95 83
d247a5d1
JG
84public:
85 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
e9e70b95 86
d247a5d1
JG
87 bool operator()(const TxPriority& a, const TxPriority& b)
88 {
89 if (byFee)
90 {
91 if (a.get<1>() == b.get<1>())
92 return a.get<0>() < b.get<0>();
93 return a.get<1>() < b.get<1>();
94 }
95 else
96 {
97 if (a.get<0>() == b.get<0>())
98 return a.get<1>() < b.get<1>();
99 return a.get<0>() < b.get<0>();
100 }
101 }
102};
103
bebe7282 104void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 105{
4972b74b 106 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
22c4272b 107}
108
5416af1d 109#include "komodo_defs.h"
110
69767347 111extern CCriticalSection cs_metrics;
6e78d3df 112extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
48d800c2 113extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
42181656 114extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
115extern const char *ASSETCHAINS_ALGORITHMS[];
5296a850 116extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
7c130297 117extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
d9f176ac 118extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
292809f7 119void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
d9f176ac 120
94a465a6 121extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 122uint32_t Mining_start,Mining_height;
28a62b60 123int32_t My_notaryid = -1;
8683bd8d 124int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 125int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
d63fdb34 126int32_t komodo_baseid(char *origbase);
3bc88f14 127int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
29bd53a1 128int64_t komodo_block_unlocktime(uint32_t nHeight);
18443f69 129uint64_t komodo_commission(const CBlock *block);
d231a6a7 130int32_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);
06f41160 131int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);
496f1fd2 132int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
7652ed92 133
5034d1c1 134CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
d247a5d1 135{
8626f666 136 CScript scriptPubKeyIn(_scriptPubKeyIn);
06f41160 137
138 CPubKey pk = CPubKey();
139 std::vector<std::vector<unsigned char>> vAddrs;
140 txnouttype txT;
141 if (Solver(scriptPubKeyIn, txT, vAddrs))
142 {
143 if (txT == TX_PUBKEY)
144 pk = CPubKey(vAddrs[0]);
145 }
146
9339a0cb 147 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
2a6a442a 148 //fprintf(stderr,"create new block\n");
17929553 149 // Create new block
16593898 150 if ( gpucount < 0 )
151 gpucount = KOMODO_MAXGPUCOUNT;
08c58194 152 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 153 if(!pblocktemplate.get())
1b5b89ba 154 {
155 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 156 return NULL;
1b5b89ba 157 }
d247a5d1 158 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
97a337f7 159 // -regtest only: allow overriding block.nVersion with
dbca89b7
GA
160 // -blockversion=N to test forking scenarios
161 if (Params().MineBlocksOnDemand())
162 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
e9e70b95 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
e9e70b95 168
d247a5d1 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));
e9e70b95 173
d247a5d1
JG
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);
e9e70b95 178
d247a5d1
JG
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 182 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
e9e70b95 183
d247a5d1 184 // Collect memory pool transactions into the block
a372168e 185 CAmount nFees = 0;
562852ab 186 CBlockIndex* pindexPrev = 0;
d247a5d1
JG
187 {
188 LOCK2(cs_main, mempool.cs);
562852ab 189 pindexPrev = chainActive.LastTip();
4b729ec5 190 const int nHeight = pindexPrev->GetHeight() + 1;
be126699 191 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
a0dd01bc 192
a1d3c6fb 193 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
a0dd01bc 194 uint32_t proposedTime = GetAdjustedTime();
195 if (proposedTime == nMedianTimePast)
196 {
197 // too fast or stuck, this addresses the too fast issue, while moving
198 // forward as quickly as possible
199 for (int i; i < 100; i++)
200 {
201 proposedTime = GetAdjustedTime();
202 if (proposedTime == nMedianTimePast)
203 MilliSleep(10);
204 }
205 }
206 pblock->nTime = GetAdjustedTime();
207
7c70438d 208 CCoinsViewCache view(pcoinsTip);
f9155fec 209 uint32_t expired; uint64_t commission;
6ff77181 210
4fc309f0 211 SaplingMerkleTree sapling_tree;
31a04d28
SB
212 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
213
d247a5d1
JG
214 // Priority order to process transactions
215 list<COrphan> vOrphan; // list memory doesn't move
216 map<uint256, vector<COrphan*> > mapDependers;
217 bool fPrintPriority = GetBoolArg("-printpriority", false);
e9e70b95 218
d247a5d1
JG
219 // This vector will be sorted into a priority queue:
220 vector<TxPriority> vecPriority;
221 vecPriority.reserve(mempool.mapTx.size());
e328fa32 222 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 223 mi != mempool.mapTx.end(); ++mi)
d247a5d1 224 {
e328fa32 225 const CTransaction& tx = mi->GetTx();
e9e70b95 226
a1d3c6fb 227 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
e9e70b95 228 ? nMedianTimePast
229 : pblock->GetBlockTime();
230
9bb37bf0 231 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
61f8caf2 232 {
51376f3c 233 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
14aa6cc0 234 continue;
61f8caf2 235 }
161f617d 236 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
6ff77181 237 {
64b45b71 238 //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 239 continue;
14aa6cc0 240 }
d247a5d1
JG
241 COrphan* porphan = NULL;
242 double dPriority = 0;
a372168e 243 CAmount nTotalIn = 0;
d247a5d1 244 bool fMissingInputs = false;
0cb91a8d 245 if (tx.IsCoinImport())
d247a5d1 246 {
0cb91a8d
SS
247 CAmount nValueIn = GetCoinImportValue(tx);
248 nTotalIn += nValueIn;
249 dPriority += (double)nValueIn * 1000; // flat multiplier
250 } else {
251 BOOST_FOREACH(const CTxIn& txin, tx.vin)
d247a5d1 252 {
0cb91a8d
SS
253 // Read prev transaction
254 if (!view.HaveCoins(txin.prevout.hash))
d247a5d1 255 {
0cb91a8d
SS
256 // This should never happen; all transactions in the memory
257 // pool should connect to either transactions in the chain
258 // or other transactions in the memory pool.
259 if (!mempool.mapTx.count(txin.prevout.hash))
260 {
261 LogPrintf("ERROR: mempool transaction missing input\n");
262 if (fDebug) assert("mempool transaction missing input" == 0);
263 fMissingInputs = true;
264 if (porphan)
265 vOrphan.pop_back();
266 break;
267 }
268
269 // Has to wait for dependencies
270 if (!porphan)
271 {
272 // Use list for automatic deletion
273 vOrphan.push_back(COrphan(&tx));
274 porphan = &vOrphan.back();
275 }
276 mapDependers[txin.prevout.hash].push_back(porphan);
277 porphan->setDependsOn.insert(txin.prevout.hash);
278 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
279 continue;
d247a5d1 280 }
0cb91a8d
SS
281 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
282 assert(coins);
283
284 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
285 nTotalIn += nValueIn;
286
287 int nConf = nHeight - coins->nHeight;
288
289 dPriority += (double)nValueIn * nConf;
d247a5d1 290 }
9feb4b9e 291 nTotalIn += tx.GetShieldedValueIn();
d247a5d1 292 }
0cb91a8d 293
d247a5d1 294 if (fMissingInputs) continue;
e9e70b95 295
d6eb2599 296 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 297 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 298 dPriority = tx.ComputePriority(dPriority, nTxSize);
e9e70b95 299
805344dc 300 uint256 hash = tx.GetHash();
2a72d459 301 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
e9e70b95 302
c6cb21d1 303 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
e9e70b95 304
d247a5d1
JG
305 if (porphan)
306 {
307 porphan->dPriority = dPriority;
c6cb21d1 308 porphan->feeRate = feeRate;
d247a5d1
JG
309 }
310 else
e328fa32 311 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1 312 }
e9e70b95 313
d247a5d1 314 // Collect transactions into block
51ed9ec9
BD
315 uint64_t nBlockSize = 1000;
316 uint64_t nBlockTx = 0;
355ca565 317 int64_t interest;
d247a5d1
JG
318 int nBlockSigOps = 100;
319 bool fSortedByFee = (nBlockPrioritySize <= 0);
e9e70b95 320
d247a5d1
JG
321 TxPriorityCompare comparer(fSortedByFee);
322 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
e9e70b95 323
d247a5d1
JG
324 while (!vecPriority.empty())
325 {
326 // Take highest priority transaction off the priority queue:
327 double dPriority = vecPriority.front().get<0>();
c6cb21d1 328 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 329 const CTransaction& tx = *(vecPriority.front().get<2>());
e9e70b95 330
d247a5d1
JG
331 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
332 vecPriority.pop_back();
e9e70b95 333
d247a5d1
JG
334 // Size limits
335 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
01fda4c1 336 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
61f8caf2 337 {
51376f3c 338 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
d247a5d1 339 continue;
61f8caf2 340 }
e9e70b95 341
d247a5d1
JG
342 // Legacy limits on sigOps:
343 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
a4a40a38 344 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 345 {
51376f3c 346 //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 347 continue;
61f8caf2 348 }
d247a5d1 349 // Skip free transactions if we're past the minimum block size:
805344dc 350 const uint256& hash = tx.GetHash();
2a72d459 351 double dPriorityDelta = 0;
a372168e 352 CAmount nFeeDelta = 0;
2a72d459 353 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 354 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
61f8caf2 355 {
51376f3c 356 //fprintf(stderr,"fee rate skip\n");
d247a5d1 357 continue;
61f8caf2 358 }
2a72d459 359 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
360 // transactions:
361 if (!fSortedByFee &&
362 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
363 {
364 fSortedByFee = true;
365 comparer = TxPriorityCompare(fSortedByFee);
366 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
367 }
e9e70b95 368
d247a5d1 369 if (!view.HaveInputs(tx))
61f8caf2 370 {
51376f3c 371 //fprintf(stderr,"dont have inputs\n");
d247a5d1 372 continue;
61f8caf2 373 }
4b729ec5 374 CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
e9e70b95 375
d247a5d1 376 nTxSigOps += GetP2SHSigOpCount(tx, view);
a4a40a38 377 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 378 {
51376f3c 379 //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 380 continue;
61f8caf2 381 }
68f7d1d7
PT
382 // Note that flags: we don't want to set mempool/IsStandard()
383 // policy here, but we still have to ensure that the block we
384 // create only contains transactions that are valid in new blocks.
d247a5d1 385 CValidationState state;
6514771a 386 PrecomputedTransactionData txdata(tx);
be126699 387 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
61f8caf2 388 {
51376f3c 389 //fprintf(stderr,"context failure\n");
d247a5d1 390 continue;
61f8caf2 391 }
8cb98d91 392 UpdateCoins(tx, view, nHeight);
d247a5d1 393
31a04d28
SB
394 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
395 sapling_tree.append(outDescription.cm);
396 }
397
d247a5d1
JG
398 // Added
399 pblock->vtx.push_back(tx);
400 pblocktemplate->vTxFees.push_back(nTxFees);
401 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
402 nBlockSize += nTxSize;
403 ++nBlockTx;
404 nBlockSigOps += nTxSigOps;
405 nFees += nTxFees;
e9e70b95 406
d247a5d1
JG
407 if (fPrintPriority)
408 {
3f0813b3 409 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1 410 }
e9e70b95 411
d247a5d1
JG
412 // Add transactions that depend on this one to the priority queue
413 if (mapDependers.count(hash))
414 {
415 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
416 {
417 if (!porphan->setDependsOn.empty())
418 {
419 porphan->setDependsOn.erase(hash);
420 if (porphan->setDependsOn.empty())
421 {
c6cb21d1 422 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
423 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
424 }
425 }
426 }
427 }
428 }
e9e70b95 429
d247a5d1
JG
430 nLastBlockTx = nBlockTx;
431 nLastBlockSize = nBlockSize;
d07308d2 432 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9a0f2798 433 //pblock->nTime = blocktime + 1;
135fa24e 434 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
435
86e31e3d 436 int32_t stakeHeight = chainActive.Height() + 1;
aa3ce424 437 bool extendedStake = (Params().GetConsensus().vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight <= stakeHeight);
86e31e3d 438
7dbeae5d 439 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
135fa24e 440 if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
a4a40a38 441 {
1f722359 442 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
86e31e3d 443 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), stakeHeight);
1f722359 444
cfb55edb 445 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
446 // blocktime = pindexPrev->GetMedianTimePast() + 60;
1f722359
MT
447 if (ASSETCHAINS_LWMAPOS != 0)
448 {
449 uint32_t nBitsPOS;
450 arith_uint256 posHash;
17d0160a 451
06f41160 452 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
1f722359 453 blocktime = GetAdjustedTime();
cd230e37
MT
454
455 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
456 if (siglen > 0)
457 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
1f722359
MT
458 }
459 else
460 {
5034d1c1 461 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
1f722359
MT
462 }
463
464 if ( siglen > 0 )
a4a40a38 465 {
86e31e3d 466 CAmount txfees;
467
468 // after Sapling, stake transactions have a fee, but it is recovered in the reward
469 // this ensures that a rebroadcast goes through quickly to begin staking again
470 txfees = extendedStake ? DEFAULT_STAKE_TXFEE : 0;
471
a4a40a38 472 pblock->vtx.push_back(txStaked);
a4a40a38 473 pblocktemplate->vTxFees.push_back(txfees);
d231a6a7 474 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
a4a40a38 475 nFees += txfees;
9339a0cb 476 pblock->nTime = blocktime;
4b729ec5 477 //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
9464ac21 478 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
a4a40a38 479 }
e9e70b95 480
f3ffa3d2 481 // Create coinbase tx
072099d7 482 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
483 txNew.vin.resize(1);
484 txNew.vin[0].prevout.SetNull();
abb90a89
MT
485 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
486
d581f229 487 txNew.vout.resize(1);
f3ffa3d2 488 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
abb90a89 489 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees;
06f41160 490
491 // once we get to Sapling, enable CC CoinbaseGuard for stake transactions
86e31e3d 492 if (isStake && extendedStake)
06f41160 493 {
494 // if there is a specific destination, use it
495 CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1];
496 CStakeParams p;
497 if (ValidateStakeTransaction(stakeTx, p))
498 {
86e31e3d 499 if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0]))
500 {
501 fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
06f41160 502 return 0;
86e31e3d 503 }
504 }
505 else
506 {
507 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
508 return 0;
06f41160 509 }
06f41160 510 }
511
9bb37bf0 512 txNew.nExpiryHeight = 0;
48d800c2 513 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
abb90a89 514
e0bc68e6 515 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
516 txNew.vout[0].nValue += 5000;
5034d1c1 517
29bd53a1 518 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
a0dd01bc 519 // to transaction if so, cast for GTE operator
520 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
abb90a89
MT
521 {
522 int32_t opretlen, p2shlen, scriptlen;
29bd53a1 523 CScriptExt opretScript = CScriptExt();
abb90a89
MT
524
525 txNew.vout.resize(2);
526
29bd53a1
MT
527 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
528 // protected only by the time lock rather than 100% inaccessible
529 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
06f41160 530 if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())
531 {
86e31e3d 532 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
06f41160 533 return 0;
534 }
535
536 opretScript += scriptPubKeyIn;
abb90a89 537
29bd53a1
MT
538 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
539 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
abb90a89 540 txNew.vout[1].nValue = 0;
48d800c2 541 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
5034d1c1 542 else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
c9b1071d 543 {
c000c9ca 544 int32_t i; uint8_t *ptr;
9ed1be03 545 txNew.vout.resize(2);
546 txNew.vout[1].nValue = commission;
547 txNew.vout[1].scriptPubKey.resize(35);
9feb4b9e 548 ptr = (uint8_t *)&txNew.vout[1].scriptPubKey[0];
c000c9ca 549 ptr[0] = 33;
550 for (i=0; i<33; i++)
551 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
552 ptr[34] = OP_CHECKSIG;
146d2aa2 553 //printf("autocreate commision vout\n");
c9b1071d 554 }
48d800c2 555
4949004d 556 pblock->vtx[0] = txNew;
d247a5d1 557 pblocktemplate->vTxFees[0] = -nFees;
48d800c2 558
1fae37f6
MT
559 // if not Verus stake, setup nonce, otherwise, leave it alone
560 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
561 {
562 // Randomise nonce
563 arith_uint256 nonce = UintToArith256(GetRandHash());
48d800c2 564
1fae37f6
MT
565 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
566 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
567 nonce >>= 16;
568 pblock->nNonce = ArithToUint256(nonce);
569 }
e9e70b95 570
d247a5d1
JG
571 // Fill in header
572 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
31a04d28 573 pblock->hashFinalSaplingRoot = sapling_tree.root();
0c8fa56a
MT
574
575 // all Verus PoS chains need this data in the block at all times
576 if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )
9a0f2798 577 {
578 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
1fae37f6 579 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
9a0f2798 580 }
fdda3c50 581 pblock->nSolution.clear();
d247a5d1 582 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
4d068367 583 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
af805d53 584 {
28a62b60 585 uint32_t r;
496f1fd2 586 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
fa04bcf3 587 if ( pblock->nTime < pindexPrev->nTime+60 )
588 pblock->nTime = pindexPrev->nTime + 60;
16593898 589 if ( gpucount < 33 )
28a62b60 590 {
55566f16 591 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
28a62b60 592 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
593 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
594 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
9a146fef 595 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
55566f16 596 memcpy(&r,&randvals,sizeof(r));
597 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
28a62b60 598 }
a893e994 599 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
496f1fd2 600 {
2d79309f 601 CAmount txfees = 5000;
496f1fd2 602 pblock->vtx.push_back(txNotary);
603 pblocktemplate->vTxFees.push_back(txfees);
604 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
605 nFees += txfees;
2d79309f 606 pblocktemplate->vTxFees[0] = -nFees;
c881e52b 607 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
f31815fc 608 //fprintf(stderr,"added notaryvin\n");
0857c3d5 609 }
610 else
611 {
612 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
613 return(0);
614 }
707b061c 615 }
809f2e25 616 else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
af805d53 617 {
8fc79ac9 618 CValidationState state;
809f2e25 619 //fprintf(stderr,"check validity\n");
620 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
8fc79ac9 621 {
9feb4b9e 622 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
8fc79ac9 623 }
809f2e25 624 //fprintf(stderr,"valid\n");
af805d53 625 }
d247a5d1 626 }
2a6a442a 627 //fprintf(stderr,"done new block\n");
d247a5d1
JG
628 return pblocktemplate.release();
629}
32b915c9 630
1a31463b 631/*
e9e70b95 632 #ifdef ENABLE_WALLET
633 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
634 #else
635 boost::optional<CScript> GetMinerScriptPubKey()
636 #endif
637 {
638 CKeyID keyID;
639 CBitcoinAddress addr;
640 if (addr.SetString(GetArg("-mineraddress", ""))) {
641 addr.GetKeyID(keyID);
642 } else {
643 #ifdef ENABLE_WALLET
644 CPubKey pubkey;
645 if (!reservekey.GetReservedKey(pubkey)) {
646 return boost::optional<CScript>();
647 }
648 keyID = pubkey.GetID();
649 #else
650 return boost::optional<CScript>();
651 #endif
652 }
653
654 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
655 return scriptPubKey;
656 }
657
658 #ifdef ENABLE_WALLET
659 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
660 {
661 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
662 #else
663 CBlockTemplate* CreateNewBlockWithKey()
664 {
665 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
666 #endif
667
668 if (!scriptPubKey) {
669 return NULL;
670 }
671 return CreateNewBlock(*scriptPubKey);
672 }*/
acfa0333 673
c1de826f
JG
674//////////////////////////////////////////////////////////////////////////////
675//
676// Internal miner
677//
678
2cc0a252 679#ifdef ENABLE_MINING
c1de826f 680
d247a5d1
JG
681void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
682{
683 // Update nExtraNonce
684 static uint256 hashPrevBlock;
685 if (hashPrevBlock != pblock->hashPrevBlock)
686 {
687 nExtraNonce = 0;
688 hashPrevBlock = pblock->hashPrevBlock;
689 }
690 ++nExtraNonce;
4b729ec5 691 unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2
4949004d
PW
692 CMutableTransaction txCoinbase(pblock->vtx[0]);
693 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
694 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
e9e70b95 695
4949004d 696 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
697 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
698}
699
4a85e067 700#ifdef ENABLE_WALLET
acfa0333
WL
701//////////////////////////////////////////////////////////////////////////////
702//
703// Internal miner
704//
acfa0333 705
5034d1c1 706CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
acfa0333 707{
9feb4b9e 708 CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
d9f176ac 709 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
710 {
711 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
712 }
713 else if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 714 {
7bfc207a 715 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 716 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 717 }
718 else
719 {
720 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 721 {
f6c647ed 722 return NULL;
1b5b89ba 723 }
f6c647ed 724 scriptPubKey.resize(35);
f66f65ec 725 ptr = (uint8_t *)pubkey.begin();
9feb4b9e 726 scriptPubKey[0] = 33;
f6c647ed 727 for (i=0; i<33; i++)
9feb4b9e 728 scriptPubKey[i+1] = ptr[i];
729 scriptPubKey[34] = OP_CHECKSIG;
f6c647ed 730 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
731 }
5034d1c1 732 return CreateNewBlock(scriptPubKey, gpucount, isStake);
acfa0333
WL
733}
734
395f10cf 735void komodo_broadcast(CBlock *pblock,int32_t limit)
736{
737 int32_t n = 1;
738 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
739 {
740 LOCK(cs_vNodes);
741 BOOST_FOREACH(CNode* pnode, vNodes)
742 {
743 if ( pnode->hSocket == INVALID_SOCKET )
744 continue;
745 if ( (rand() % n) == 0 )
746 {
747 pnode->PushMessage("block", *pblock);
748 if ( n++ > limit )
749 break;
750 }
751 }
752 }
753 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
754}
945f015d 755
269d8ba0 756static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
757#else
758static bool ProcessBlockFound(CBlock* pblock)
759#endif // ENABLE_WALLET
d247a5d1 760{
81212588 761 LogPrintf("%s\n", pblock->ToString());
4b729ec5 762 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1);
e9e70b95 763
d247a5d1
JG
764 // Found a solution
765 {
194ad5b8 766 //LOCK(cs_main);
86131275 767 if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
ba8419c7 768 {
769 uint256 hash; int32_t i;
770 hash = pblock->hashPrevBlock;
92266e99 771 for (i=31; i>=0; i--)
ba8419c7 772 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 773 fprintf(stderr," <- prev (stale)\n");
86131275 774 hash = chainActive.LastTip()->GetBlockHash();
92266e99 775 for (i=31; i>=0; i--)
ba8419c7 776 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 777 fprintf(stderr," <- chainTip (stale)\n");
e9e70b95 778
2e500f50 779 return error("KomodoMiner: generated block is stale");
ba8419c7 780 }
18e72167 781 }
e9e70b95 782
8e8b6d70 783#ifdef ENABLE_WALLET
18e72167 784 // Remove key from key pool
998397aa 785 if ( IS_KOMODO_NOTARY == 0 )
945f015d 786 {
787 if (GetArg("-mineraddress", "").empty()) {
788 // Remove key from key pool
789 reservekey.KeepKey();
790 }
8e8b6d70 791 }
18e72167 792 // Track how many getdata requests this block gets
438ba9c1 793 //if ( 0 )
18e72167 794 {
d1bc3a75 795 //fprintf(stderr,"lock cs_wallet\n");
18e72167
PW
796 LOCK(wallet.cs_wallet);
797 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 798 }
8e8b6d70 799#endif
d1bc3a75 800 //fprintf(stderr,"process new block\n");
194ad5b8 801
18e72167
PW
802 // Process this block the same as if we had received it from another node
803 CValidationState state;
4b729ec5 804 if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL))
2e500f50 805 return error("KomodoMiner: ProcessNewBlock, block not accepted");
e9e70b95 806
d793f94b 807 TrackMinedBlock(pblock->GetHash());
395f10cf 808 komodo_broadcast(pblock,16);
d247a5d1
JG
809 return true;
810}
811
078f6af1 812int32_t komodo_baseid(char *origbase);
a30dd993 813int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
13691369 814arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
8ee93080 815int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
99ba67a0 816extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
8b51b9e4 817int32_t roundrobin_delay;
18443f69 818arith_uint256 HASHTarget,HASHTarget_POW;
078f6af1 819
5642c96c 820// wait for peers to connect
b45d65b4 821int32_t waitForPeers(const CChainParams &chainparams)
5642c96c 822{
823 if (chainparams.MiningRequiresPeers())
824 {
3da69a31
MT
825 bool fvNodesEmpty;
826 {
827 LOCK(cs_vNodes);
828 fvNodesEmpty = vNodes.empty();
829 }
6d84700d 830 if (fvNodesEmpty || !IsInSync())
3da69a31
MT
831 {
832 do {
64d6048f 833 if (fvNodesEmpty)
834 MilliSleep(1000 + rand() % 4000);
3da69a31
MT
835 {
836 LOCK(cs_vNodes);
837 fvNodesEmpty = vNodes.empty();
838 }
bca01f86 839 } while (fvNodesEmpty || !IsInSync());
0ba20651 840 MilliSleep(100 + rand() % 400);
3da69a31 841 }
5642c96c 842 }
843}
844
42181656 845#ifdef ENABLE_WALLET
d7e6718d
MT
846CBlockIndex *get_chainactive(int32_t height)
847{
3c40a9a6 848 if ( chainActive.LastTip() != 0 )
d7e6718d 849 {
4b729ec5 850 if ( height <= chainActive.LastTip()->GetHeight() )
3c40a9a6
MT
851 {
852 LOCK(cs_main);
d7e6718d 853 return(chainActive[height]);
3c40a9a6 854 }
4b729ec5 855 // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
d7e6718d
MT
856 }
857 //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
858 return(0);
859}
860
135fa24e 861/*
862 * A separate thread to stake, while the miner threads mine.
863 */
864void static VerusStaker(CWallet *pwallet)
865{
866 LogPrintf("Verus staker thread started\n");
867 RenameThread("verus-staker");
868
869 const CChainParams& chainparams = Params();
870
871 // Each thread has its own key
872 CReserveKey reservekey(pwallet);
873
874 // Each thread has its own counter
875 unsigned int nExtraNonce = 0;
876 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
877 solnPlaceholder.resize(Eh200_9.SolutionWidth);
878 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
879
4b729ec5 880 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
135fa24e 881 {
882 sleep(1);
883 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
884 break;
885 }
886
887 // try a nice clean peer connection to start
bf9c36f4
MT
888 CBlockIndex *pindexPrev, *pindexCur;
889 do {
890 pindexPrev = chainActive.LastTip();
891 MilliSleep(5000 + rand() % 5000);
892 waitForPeers(chainparams);
893 pindexCur = chainActive.LastTip();
894 } while (pindexPrev != pindexCur);
c132b91a 895
135fa24e 896 try {
135fa24e 897 while (true)
898 {
135fa24e 899 waitForPeers(chainparams);
4ca6678c 900 CBlockIndex* pindexPrev = chainActive.LastTip();
4b729ec5 901 printf("Staking height %d for %s\n", pindexPrev->GetHeight() + 1, ASSETCHAINS_SYMBOL);
135fa24e 902
903 // Create new block
904 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
4b729ec5 905 if ( Mining_height != pindexPrev->GetHeight()+1 )
135fa24e 906 {
4b729ec5 907 Mining_height = pindexPrev->GetHeight()+1;
135fa24e 908 Mining_start = (uint32_t)time(NULL);
909 }
910
1fae37f6
MT
911 // Check for stop or if block needs to be rebuilt
912 boost::this_thread::interruption_point();
913
135fa24e 914 // try to stake a block
1fae37f6
MT
915 CBlockTemplate *ptr = NULL;
916 if (Mining_height > VERUS_MIN_STAKEAGE)
5034d1c1 917 ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);
135fa24e 918
919 if ( ptr == 0 )
920 {
1fae37f6 921 // wait to try another staking block until after the tip moves again
37ad6886
MT
922 while ( chainActive.LastTip() == pindexPrev )
923 sleep(1);
135fa24e 924 continue;
925 }
926
927 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
928 if (!pblocktemplate.get())
929 {
930 if (GetArg("-mineraddress", "").empty()) {
1fae37f6 931 LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
135fa24e 932 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
933 } else {
934 // Should never reach here, because -mineraddress validity is checked in init.cpp
1fae37f6 935 LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
135fa24e 936 }
937 return;
938 }
939
940 CBlock *pblock = &pblocktemplate->block;
1fae37f6 941 LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
135fa24e 942 //
943 // Search
944 //
1fae37f6
MT
945 int64_t nStart = GetTime();
946
52670b72
MT
947 // take up the necessary space for alignment
948 pblock->nSolution = solnPlaceholder;
949
1fae37f6
MT
950 // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree
951 unsigned int nExtraNonce = 0;
952 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
135fa24e 953
1fae37f6
MT
954 if (vNodes.empty() && chainparams.MiningRequiresPeers())
955 {
956 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
957 {
958 fprintf(stderr,"no nodes, attempting reconnect\n");
959 continue;
960 }
961 }
962
963 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
964 {
965 fprintf(stderr,"timeout, retrying\n");
966 continue;
967 }
135fa24e 968
37ad6886 969 if ( pindexPrev != chainActive.LastTip() )
135fa24e 970 {
4b729ec5 971 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
135fa24e 972 MilliSleep(250);
973 continue;
974 }
975
1fae37f6
MT
976 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
977 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
135fa24e 978
1fae37f6 979 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
135fa24e 980
b9956efc
MT
981 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
982
983 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
984
985 ProcessBlockFound(pblock, *pwallet, reservekey);
986
1fae37f6
MT
987 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
988 LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
989 printf("Found block %d \n", Mining_height );
990 printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
b9956efc
MT
991 arith_uint256 post;
992 post.SetCompact(pblock->GetVerusPOSTarget());
d7e6718d
MT
993 pindexPrev = get_chainactive(Mining_height - 100);
994 printf(" hash: %s \ntarget: %s\n",
995 CTransaction::_GetVerusPOSHash(&(pblock->nNonce), pblock->vtx[pblock->vtx.size()-1].vin[0].prevout.hash, 0, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), pblock->vtx[pblock->vtx.size()-1].vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str());
1fae37f6
MT
996 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
997 printf("- timelocked until block %i\n", unlockTime);
998 else
999 printf("\n");
135fa24e 1000
1fae37f6
MT
1001 // Check for stop or if block needs to be rebuilt
1002 boost::this_thread::interruption_point();
135fa24e 1003
bf9c36f4 1004 sleep(3);
3da69a31 1005
1fae37f6
MT
1006 // In regression test mode, stop mining after a block is found.
1007 if (chainparams.MineBlocksOnDemand()) {
1008 throw boost::thread_interrupted();
135fa24e 1009 }
1010 }
1011 }
1012 catch (const boost::thread_interrupted&)
1013 {
135fa24e 1014 LogPrintf("VerusStaker terminated\n");
1015 throw;
1016 }
1017 catch (const std::runtime_error &e)
1018 {
135fa24e 1019 LogPrintf("VerusStaker runtime error: %s\n", e.what());
1020 return;
1021 }
135fa24e 1022}
1023
42181656 1024void static BitcoinMiner_noeq(CWallet *pwallet)
1025#else
1026void static BitcoinMiner_noeq()
1027#endif
1028{
05f6e633 1029 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
05f6e633 1030 RenameThread("verushash-miner");
42181656 1031
1032#ifdef ENABLE_WALLET
1033 // Each thread has its own key
1034 CReserveKey reservekey(pwallet);
1035#endif
1036
2910478b 1037 const CChainParams& chainparams = Params();
42181656 1038 // Each thread has its own counter
1039 unsigned int nExtraNonce = 0;
1040 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1041 solnPlaceholder.resize(Eh200_9.SolutionWidth);
42181656 1042 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1043
4b729ec5 1044 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
42181656 1045 {
1046 sleep(1);
1047 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1048 break;
1049 }
9f3e2213 1050
3da69a31
MT
1051 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1052
5642c96c 1053 // try a nice clean peer connection to start
c132b91a 1054 CBlockIndex *pindexPrev, *pindexCur;
9f3e2213 1055 do {
37ad6886 1056 pindexPrev = chainActive.LastTip();
3da69a31 1057 MilliSleep(5000 + rand() % 5000);
bf9c36f4 1058 waitForPeers(chainparams);
37ad6886 1059 pindexCur = chainActive.LastTip();
c132b91a 1060 } while (pindexPrev != pindexCur);
6176a421 1061
dbe656fe
MT
1062 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1063 // and print duplicates rarely without having to synchronize
1064 static CBlockIndex *lastChainTipPrinted;
9f3e2213 1065
42181656 1066 miningTimer.start();
1067
1068 try {
dbe656fe 1069 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1070 while (true)
1071 {
68334c8d 1072 miningTimer.stop();
1073 waitForPeers(chainparams);
dfcf8255 1074
37ad6886 1075 pindexPrev = chainActive.LastTip();
3da69a31 1076 sleep(1);
dfcf8255
MT
1077
1078 // prevent forking on startup before the diff algorithm kicks in
4b729ec5 1079 if (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip())
dfcf8255
MT
1080 {
1081 do {
37ad6886 1082 pindexPrev = chainActive.LastTip();
3da69a31 1083 MilliSleep(5000 + rand() % 5000);
37ad6886 1084 } while (pindexPrev != chainActive.LastTip());
dfcf8255 1085 }
42181656 1086
1087 // Create new block
1088 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
4b729ec5 1089 if ( Mining_height != pindexPrev->GetHeight()+1 )
42181656 1090 {
4b729ec5 1091 Mining_height = pindexPrev->GetHeight()+1;
42181656 1092 Mining_start = (uint32_t)time(NULL);
1093 }
1094
dbe656fe
MT
1095 if (lastChainTipPrinted != pindexPrev)
1096 {
1097 printf("Mining height %d\n", Mining_height);
1098 lastChainTipPrinted = pindexPrev;
1099 }
1100
1101 miningTimer.start();
42181656 1102
1103#ifdef ENABLE_WALLET
5034d1c1 1104 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
42181656 1105#else
1106 CBlockTemplate *ptr = CreateNewBlockWithKey();
1107#endif
1108 if ( ptr == 0 )
1109 {
1110 static uint32_t counter;
1111 if ( counter++ < 100 )
1112 fprintf(stderr,"created illegal block, retry\n");
1113 continue;
1114 }
dbe656fe 1115
42181656 1116 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1117 if (!pblocktemplate.get())
1118 {
1119 if (GetArg("-mineraddress", "").empty()) {
05f6e633 1120 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1121 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1122 } else {
1123 // Should never reach here, because -mineraddress validity is checked in init.cpp
05f6e633 1124 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
42181656 1125 }
1126 return;
1127 }
1128 CBlock *pblock = &pblocktemplate->block;
1129 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1130 {
1131 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1132 {
1133 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1134 {
1135 static uint32_t counter;
1136 if ( counter++ < 10 )
1137 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1138 sleep(10);
1139 continue;
1140 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1141 }
1142 }
1143 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1144 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1145 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1146 //
1147 // Search
1148 //
1149 uint32_t savebits; int64_t nStart = GetTime();
1150
1151 pblock->nSolution = solnPlaceholder;
1152 savebits = pblock->nBits;
1153 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1154 arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
1155
1156 Mining_start = 0;
ef70c5b2 1157
37ad6886 1158 if ( pindexPrev != chainActive.LastTip() )
05f6e633 1159 {
37ad6886 1160 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1161 {
37ad6886 1162 lastChainTipPrinted = chainActive.LastTip();
4b729ec5 1163 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
dbe656fe 1164 }
6176a421 1165 MilliSleep(250);
05f6e633 1166 continue;
1167 }
ef70c5b2 1168
135fa24e 1169 if ( ASSETCHAINS_STAKED != 0 )
1170 {
1171 int32_t percPoS,z;
1172 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1173 for (z=31; z>=0; z--)
1174 fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1175 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1176 }
1177
42181656 1178 while (true)
1179 {
dbe656fe
MT
1180 arith_uint256 arNonce = UintToArith256(pblock->nNonce);
1181
4dcb64c0 1182 CVerusHashWriter ss = CVerusHashWriter(SER_GETHASH, PROTOCOL_VERSION);
20ab1c91 1183 ss << *((CBlockHeader *)pblock);
4dcb64c0
MT
1184 int64_t *extraPtr = ss.xI64p();
1185 CVerusHash &vh = ss.GetState();
1186 uint256 hashResult = uint256();
1187 vh.ClearExtra();
69767347 1188 int64_t i, count = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1;
4dcb64c0
MT
1189 int64_t hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
1190
69767347
MT
1191 // for speed check NONCEMASK at a time
1192 for (i = 0; i < count; i++)
42181656 1193 {
4dcb64c0
MT
1194 *extraPtr = i;
1195 vh.ExtraHash((unsigned char *)&hashResult);
42181656 1196
4dcb64c0 1197 if ( UintToArith256(hashResult) <= hashTarget )
42181656 1198 {
4dcb64c0
MT
1199 if (pblock->nSolution.size() != 1344)
1200 {
1201 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1202 sleep(5);
1203 break;
1204 }
1205
42181656 1206 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1207
4dcb64c0
MT
1208 *((int64_t *)&(pblock->nSolution.data()[pblock->nSolution.size() - 15])) = i;
1209
ef70c5b2 1210 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1211 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1212
135fa24e 1213 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1214 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
14d104e9 1215 printf("Found block %d \n", Mining_height );
a62041d9 1216 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
ef70c5b2 1217 printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
1218 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1219 printf("- timelocked until block %i\n", unlockTime);
1220 else
1221 printf("\n");
42181656 1222#ifdef ENABLE_WALLET
1223 ProcessBlockFound(pblock, *pwallet, reservekey);
1224#else
1225 ProcessBlockFound(pblock));
1226#endif
1227 SetThreadPriority(THREAD_PRIORITY_LOWEST);
42181656 1228 break;
1229 }
dbe656fe 1230 // check periodically if we're stale
4dcb64c0 1231 if (!--hashesToGo)
42181656 1232 {
37ad6886 1233 if ( pindexPrev != chainActive.LastTip() )
ef70c5b2 1234 {
37ad6886 1235 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1236 {
37ad6886 1237 lastChainTipPrinted = chainActive.LastTip();
4b729ec5 1238 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
dbe656fe 1239 }
ef70c5b2 1240 break;
1241 }
4dcb64c0 1242 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
42181656 1243 }
1244 }
1245
69767347
MT
1246 {
1247 LOCK(cs_metrics);
1248 nHashCount += i;
1249 }
1250
42181656 1251 // Check for stop or if block needs to be rebuilt
1252 boost::this_thread::interruption_point();
1253
1254 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1255 {
1256 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1257 {
ef70c5b2 1258 fprintf(stderr,"no nodes, attempting reconnect\n");
42181656 1259 break;
1260 }
1261 }
1262
dbe656fe 1263 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
42181656 1264 {
dbe656fe 1265 fprintf(stderr,"timeout, retrying\n");
42181656 1266 break;
1267 }
1268
37ad6886 1269 if ( pindexPrev != chainActive.LastTip() )
42181656 1270 {
37ad6886 1271 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1272 {
37ad6886 1273 lastChainTipPrinted = chainActive.LastTip();
4b729ec5 1274 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
dbe656fe 1275 }
42181656 1276 break;
1277 }
1278
52cf66e1 1279#ifdef _WIN32
4dcb64c0 1280 printf("%llu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
52cf66e1 1281#else
4dcb64c0 1282 printf("%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
52cf66e1 1283#endif
4dcb64c0 1284 break;
42181656 1285 }
1286 }
1287 }
1288 catch (const boost::thread_interrupted&)
1289 {
1290 miningTimer.stop();
5034d1c1 1291 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1292 throw;
1293 }
1294 catch (const std::runtime_error &e)
1295 {
1296 miningTimer.stop();
5034d1c1 1297 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
42181656 1298 return;
1299 }
1300 miningTimer.stop();
1301}
1302
8e8b6d70 1303#ifdef ENABLE_WALLET
d247a5d1 1304void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
1305#else
1306void static BitcoinMiner()
1307#endif
d247a5d1 1308{
2e500f50 1309 LogPrintf("KomodoMiner started\n");
d247a5d1 1310 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 1311 RenameThread("komodo-miner");
bebe7282 1312 const CChainParams& chainparams = Params();
e9e70b95 1313
8e8b6d70
JG
1314#ifdef ENABLE_WALLET
1315 // Each thread has its own key
d247a5d1 1316 CReserveKey reservekey(pwallet);
8e8b6d70 1317#endif
e9e70b95 1318
8e8b6d70 1319 // Each thread has its own counter
d247a5d1 1320 unsigned int nExtraNonce = 0;
e9e70b95 1321
e9574728
JG
1322 unsigned int n = chainparams.EquihashN();
1323 unsigned int k = chainparams.EquihashK();
16593898 1324 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
99ba67a0 1325 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
755ead98 1326 {
1327 sleep(1);
4e624c04 1328 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1329 break;
755ead98 1330 }
32b0978b 1331 if ( ASSETCHAINS_SYMBOL[0] == 0 )
4b729ec5 1332 komodo_chosennotary(&notaryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
28a62b60 1333 if ( notaryid != My_notaryid )
1334 My_notaryid = notaryid;
755ead98 1335 std::string solver;
e1e65cef 1336 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
e9e70b95 1337 solver = "tromp";
e1e65cef 1338 //else solver = "default";
5f0009b2 1339 assert(solver == "tromp" || solver == "default");
c7aaab7a 1340 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 1341 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 1342 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
1343 std::mutex m_cs;
1344 bool cancelSolver = false;
1345 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
e9e70b95 1346 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1347 std::lock_guard<std::mutex> lock{m_cs};
1348 cancelSolver = true;
1349 }
1350 );
07be8f7e 1351 miningTimer.start();
e9e70b95 1352
0655fac0 1353 try {
ad84148d 1354 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 1355 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 1356 while (true)
1357 {
4b729ec5 1358 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
e725f1cb 1359 {
4b729ec5 1360 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
a96fd7b5 1361 // break;
0655fac0
PK
1362 // Busy-wait for the network to come online so we don't waste time mining
1363 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 1364 miningTimer.stop();
bba7c249
GM
1365 do {
1366 bool fvNodesEmpty;
1367 {
373668be 1368 //LOCK(cs_vNodes);
bba7c249
GM
1369 fvNodesEmpty = vNodes.empty();
1370 }
269fe243 1371 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 1372 break;
6e78d3df 1373 MilliSleep(15000);
ad84148d 1374 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
e9e70b95 1375
bba7c249 1376 } while (true);
ad84148d 1377 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 1378 miningTimer.start();
0655fac0 1379 }
0655fac0
PK
1380 //
1381 // Create new block
1382 //
1383 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
86131275 1384 CBlockIndex* pindexPrev = chainActive.LastTip();
4b729ec5 1385 if ( Mining_height != pindexPrev->GetHeight()+1 )
4940066c 1386 {
4b729ec5 1387 Mining_height = pindexPrev->GetHeight()+1;
4940066c 1388 Mining_start = (uint32_t)time(NULL);
1389 }
8e9ef91c 1390 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 1391 {
40304479 1392 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
5a7fd132 1393 //sleep(3);
2825c0b5 1394 }
135fa24e 1395
8e8b6d70 1396#ifdef ENABLE_WALLET
135fa24e 1397 // notaries always default to staking
4b729ec5 1398 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
8e8b6d70 1399#else
945f015d 1400 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 1401#endif
08d0b73c 1402 if ( ptr == 0 )
1403 {
d0f7ead0 1404 static uint32_t counter;
5bb3d0fe 1405 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 1406 fprintf(stderr,"created illegal block, retry\n");
8fc79ac9 1407 sleep(1);
d0f7ead0 1408 continue;
08d0b73c 1409 }
2a6a442a 1410 //fprintf(stderr,"get template\n");
08d0b73c 1411 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 1412 if (!pblocktemplate.get())
6c37f7fd 1413 {
8e8b6d70 1414 if (GetArg("-mineraddress", "").empty()) {
945f015d 1415 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
1416 } else {
1417 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 1418 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 1419 }
0655fac0 1420 return;
6c37f7fd 1421 }
0655fac0 1422 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 1423 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1424 {
42181656 1425 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
16c7bf6b 1426 {
8683bd8d 1427 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1428 {
1429 static uint32_t counter;
1430 if ( counter++ < 10 )
1431 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1432 sleep(10);
1433 continue;
1434 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1435 }
16c7bf6b 1436 }
0655fac0 1437 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2a6a442a 1438 //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
2e500f50 1439 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
1440 //
1441 // Search
1442 //
2ba9de01 1443 uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
d5614a76 1444 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
404391b5 1445 savebits = pblock->nBits;
d5614a76 1446 HASHTarget = arith_uint256().SetCompact(savebits);
f0100e72 1447 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 1448 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 1449 {
fda5f849 1450 j = 65;
67df454d 1451 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
fb6c7505 1452 {
4fff8a63 1453 int32_t dispflag = 0;
ef70c5b2 1454 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
4fff8a63 1455 dispflag = 1;
4b729ec5 1456 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
29e60e48 1457 if ( nonzpkeys > 0 )
1458 {
ccb71a6e 1459 for (i=0; i<33; i++)
1460 if( pubkeys[0][i] != 0 )
1461 break;
1462 if ( i == 33 )
1463 externalflag = 1;
1464 else externalflag = 0;
4d068367 1465 if ( IS_KOMODO_NOTARY != 0 )
b176c125 1466 {
345e545e 1467 for (i=1; i<66; i++)
1468 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1469 break;
6494f040 1470 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1471 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
2c7ad758 1472 for (j=gpucount=0; j<65; j++)
1473 {
4fff8a63 1474 if ( dispflag != 0 )
e4a383e3 1475 {
1476 if ( mids[j] >= 0 )
1477 fprintf(stderr,"%d ",mids[j]);
1478 else fprintf(stderr,"GPU ");
1479 }
2c7ad758 1480 if ( mids[j] == -1 )
1481 gpucount++;
1482 }
4fff8a63 1483 if ( dispflag != 0 )
4b729ec5 1484 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL));
b176c125 1485 }
29e60e48 1486 for (j=0; j<65; j++)
1487 if ( mids[j] == notaryid )
1488 break;
49b49585 1489 if ( j == 65 )
1490 KOMODO_LASTMINED = 0;
965f0f7e 1491 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 1492 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 1493 {
88287857 1494 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
4b729ec5 1495 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
fda5f849 1496 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 1497 } else Mining_start = 0;
d7d27bb3 1498 } else Mining_start = 0;
2ba9de01 1499 if ( ASSETCHAINS_STAKED != 0 )
e725f1cb 1500 {
ed3d0a05 1501 int32_t percPoS,z; bool fNegative,fOverflow;
18443f69 1502 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
f108acf9 1503 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
f2c1ac06 1504 if ( ASSETCHAINS_STAKED < 100 )
1505 {
1506 for (z=31; z>=0; z--)
1507 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
1508 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1509 }
deba7f20 1510 }
e725f1cb 1511 while (true)
1512 {
99ba67a0 1513 if ( KOMODO_INSYNC == 0 )
1514 {
e9d56b2c 1515 fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
1516 if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
a02c45db 1517 KOMODO_INSYNC = 1;
99ba67a0 1518 sleep(3);
1519 }
7213c0b1 1520 // Hash state
8c22eb46 1521 KOMODO_CHOSEN_ONE = 0;
42181656 1522
7213c0b1 1523 crypto_generichash_blake2b_state state;
e9574728 1524 EhInitialiseState(n, k, state);
7213c0b1
JG
1525 // I = the block header minus nonce and solution.
1526 CEquihashInput I{*pblock};
1527 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1528 ss << I;
7213c0b1
JG
1529 // H(I||...
1530 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
1531 // H(I||V||...
1532 crypto_generichash_blake2b_state curr_state;
1533 curr_state = state;
7a4c01c9 1534 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 1535 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 1536 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
18443f69 1537 arith_uint256 hashTarget;
6e78d3df 1538 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
18443f69 1539 hashTarget = HASHTarget_POW;
1540 else hashTarget = HASHTarget;
5be6abbf 1541 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 1542#ifdef ENABLE_WALLET
e9e70b95 1543 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1544#else
e9e70b95 1545 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1546#endif
e9e70b95 1547 (std::vector<unsigned char> soln) {
c21c6306 1548 int32_t z; arith_uint256 h; CBlock B;
51eb5273
JG
1549 // Write the solution to the hash and compute the result.
1550 LogPrint("pow", "- Checking solution against target\n");
8e165d57 1551 pblock->nSolution = soln;
e7d59bbc 1552 solutionTargetChecks.increment();
eff2c3a3 1553 B = *pblock;
1554 h = UintToArith256(B.GetHash());
eff2c3a3 1555 /*for (z=31; z>=16; z--)
02c30aac 1556 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
aea2d1aa 1557 fprintf(stderr," mined ");
1558 for (z=31; z>=16; z--)
18443f69 1559 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
aea2d1aa 1560 fprintf(stderr," hashTarget ");
1561 for (z=31; z>=16; z--)
18443f69 1562 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
eff2c3a3 1563 fprintf(stderr," POW\n");*/
265f4e96 1564 if ( h > hashTarget )
40df8d84 1565 {
6e78d3df 1566 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
afa90f17 1567 // sleep(1);
265f4e96 1568 return false;
40df8d84 1569 }
41e9c815 1570 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
d7d27bb3 1571 {
45ee62cb 1572 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
596b05ba 1573 while ( GetAdjustedTime() < B.nTime-2 )
8e9ef91c 1574 {
eb1ba5a0 1575 sleep(1);
4b729ec5 1576 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
4cc387ec 1577 {
1578 fprintf(stderr,"new block arrived\n");
1579 return(false);
1580 }
8e9ef91c 1581 }
eb1ba5a0 1582 }
8e9ef91c 1583 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 1584 {
4d068367 1585 if ( IS_KOMODO_NOTARY != 0 )
8e9ef91c 1586 {
26810a26 1587 int32_t r;
9703f8a0 1588 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
596b05ba 1589 MilliSleep((rand() % (r * 1000)) + 1000);
ef70c5b2 1590 }
e5430f52 1591 }
8e9ef91c 1592 else
d7d27bb3 1593 {
0c35569b 1594 while ( B.nTime-57 > GetAdjustedTime() )
deba7f20 1595 {
afa90f17 1596 sleep(1);
4b729ec5 1597 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
afa90f17 1598 return(false);
68d0354d 1599 }
4d068367 1600 uint256 tmp = B.GetHash();
1601 int32_t z; for (z=31; z>=0; z--)
1602 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
01e50e73 1603 fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
d7d27bb3 1604 }
8fc79ac9 1605 CValidationState state;
86131275 1606 if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
d2d3c766 1607 {
8fc79ac9 1608 h = UintToArith256(B.GetHash());
1609 for (z=31; z>=0; z--)
1610 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1611 fprintf(stderr," Invalid block mined, try again\n");
1612 return(false);
d2d3c766 1613 }
b3183e3e 1614 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
1615 // Found a solution
1616 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 1617 LogPrintf("KomodoMiner:\n");
eff2c3a3 1618 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 1619#ifdef ENABLE_WALLET
eff2c3a3 1620 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
8e8b6d70 1621#else
eff2c3a3 1622 if (ProcessBlockFound(&B)) {
8e8b6d70 1623#endif
e9e70b95 1624 // Ignore chain updates caused by us
1625 std::lock_guard<std::mutex> lock{m_cs};
1626 cancelSolver = false;
1627 }
1628 KOMODO_CHOSEN_ONE = 0;
1629 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1630 // In regression test mode, stop mining after a block is found.
1631 if (chainparams.MineBlocksOnDemand()) {
1632 // Increment here because throwing skips the call below
1633 ehSolverRuns.increment();
1634 throw boost::thread_interrupted();
1635 }
e9e70b95 1636 return true;
1637 };
1638 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
a6a0d913 1639 std::lock_guard<std::mutex> lock{m_cs};
e9e70b95 1640 return cancelSolver;
1641 };
1642
1643 // TODO: factor this out into a function with the same API for each solver.
1644 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1645 // Create solver and initialize it.
1646 equi eq(1);
1647 eq.setstate(&curr_state);
1648
1649 // Initialization done, start algo driver.
1650 eq.digit0(0);
c7aaab7a 1651 eq.xfull = eq.bfull = eq.hfull = 0;
e9e70b95 1652 eq.showbsizes(0);
1653 for (u32 r = 1; r < WK; r++) {
1654 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1655 eq.xfull = eq.bfull = eq.hfull = 0;
1656 eq.showbsizes(r);
c7aaab7a 1657 }
e9e70b95 1658 eq.digitK(0);
1659 ehSolverRuns.increment();
1660
1661 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1662 for (size_t s = 0; s < eq.nsols; s++) {
1663 LogPrint("pow", "Checking solution %d\n", s+1);
1664 std::vector<eh_index> index_vector(PROOFSIZE);
1665 for (size_t i = 0; i < PROOFSIZE; i++) {
1666 index_vector[i] = eq.sols[s][i];
1667 }
1668 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1669
1670 if (validBlock(sol_char)) {
1671 // If we find a POW solution, do not try other solutions
1672 // because they become invalid as we created a new block in blockchain.
1673 break;
1674 }
1675 }
1676 } else {
1677 try {
1678 // If we find a valid block, we rebuild
1679 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1680 ehSolverRuns.increment();
1681 if (found) {
997ddd92 1682 int32_t i; uint256 hash = pblock->GetHash();
e9e70b95 1683 for (i=0; i<32; i++)
1684 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1685 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1686 FOUND_BLOCK = 1;
1687 KOMODO_MAYBEMINED = Mining_height;
1688 break;
1689 }
1690 } catch (EhSolverCancelledException&) {
1691 LogPrint("pow", "Equihash solver cancelled\n");
1692 std::lock_guard<std::mutex> lock{m_cs};
1693 cancelSolver = false;
c7aaab7a
DH
1694 }
1695 }
e9e70b95 1696
1697 // Check for stop or if block needs to be rebuilt
1698 boost::this_thread::interruption_point();
1699 // Regtest mode doesn't require peers
1700 if ( FOUND_BLOCK != 0 )
1701 {
1702 FOUND_BLOCK = 0;
1703 fprintf(stderr,"FOUND_BLOCK!\n");
1704 //sleep(2000);
1705 }
1706 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1707 {
1708 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1709 {
1710 fprintf(stderr,"no nodes, break\n");
c7aaab7a 1711 break;
a6df7ab5 1712 }
c7aaab7a 1713 }
997ddd92 1714 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
10694486 1715 {
e9e70b95 1716 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1717 fprintf(stderr,"0xffff, break\n");
d90cef0b 1718 break;
10694486 1719 }
e9e70b95 1720 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1721 {
1722 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1723 fprintf(stderr,"timeout, break\n");
1724 break;
1725 }
86131275 1726 if ( pindexPrev != chainActive.LastTip() )
e9e70b95 1727 {
1728 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1729 fprintf(stderr,"Tip advanced, break\n");
1730 break;
1731 }
1732 // Update nNonce and nTime
1733 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1734 pblock->nBits = savebits;
18dd6a3b 1735 /*if ( NOTARY_PUBKEY33[0] == 0 )
e9e70b95 1736 {
f8f740a9 1737 int32_t percPoS;
23fc88bb 1738 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1739 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1740 {
1741 // Changing pblock->nTime can change work required on testnet:
1742 HASHTarget.SetCompact(pblock->nBits);
18443f69 1743 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
23fc88bb 1744 }
18dd6a3b 1745 }*/
48265f3c 1746 }
d247a5d1
JG
1747 }
1748 }
e9e70b95 1749 catch (const boost::thread_interrupted&)
1750 {
1751 miningTimer.stop();
1752 c.disconnect();
1753 LogPrintf("KomodoMiner terminated\n");
1754 throw;
1755 }
1756 catch (const std::runtime_error &e)
1757 {
1758 miningTimer.stop();
1759 c.disconnect();
1760 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1761 return;
1762 }
07be8f7e 1763 miningTimer.stop();
5e9b555f 1764 c.disconnect();
bba7c249 1765 }
e9e70b95 1766
8e8b6d70 1767#ifdef ENABLE_WALLET
e9e70b95 1768 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70 1769#else
e9e70b95 1770 void GenerateBitcoins(bool fGenerate, int nThreads)
8e8b6d70 1771#endif
d247a5d1 1772 {
e9e70b95 1773 static boost::thread_group* minerThreads = NULL;
1774
1775 if (nThreads < 0)
1776 nThreads = GetNumCores();
1777
1778 if (minerThreads != NULL)
1779 {
1780 minerThreads->interrupt_all();
1781 delete minerThreads;
1782 minerThreads = NULL;
1783 }
135fa24e 1784
afaeb54b 1785 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
5034d1c1 1786 if ( nThreads == 0 && ASSETCHAINS_STAKED )
3a446d9f 1787 nThreads = 1;
5034d1c1 1788
1f722359 1789 if ((nThreads == 0 && ASSETCHAINS_LWMAPOS == 0) || !fGenerate)
e9e70b95 1790 return;
135fa24e 1791
e9e70b95 1792 minerThreads = new boost::thread_group();
135fa24e 1793
1794#ifdef ENABLE_WALLET
1f722359 1795 if (ASSETCHAINS_LWMAPOS != 0)
135fa24e 1796 {
1797 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
1798 }
1799#endif
1800
e9e70b95 1801 for (int i = 0; i < nThreads; i++) {
135fa24e 1802
8e8b6d70 1803#ifdef ENABLE_WALLET
135fa24e 1804 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1805 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1806 else
1807 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
8e8b6d70 1808#else
135fa24e 1809 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1810 minerThreads->create_thread(&BitcoinMiner);
1811 else
1812 minerThreads->create_thread(&BitcoinMiner_noeq);
8e8b6d70 1813#endif
e9e70b95 1814 }
8e8b6d70 1815 }
e9e70b95 1816
2cc0a252 1817#endif // ENABLE_MINING
This page took 0.828784 seconds and 4 git commands to generate.