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