]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Merge mining error handling improvements
[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
2299bd95
MT
50#include "pbaas/pbaas.h"
51#include "pbaas/notarization.h"
52
09eb201b 53using namespace std;
7b4737c8 54
d247a5d1
JG
55//////////////////////////////////////////////////////////////////////////////
56//
57// BitcoinMiner
58//
59
c6cb21d1
GA
60//
61// Unconfirmed transactions in the memory pool often depend on other
62// transactions in the memory pool. When we select transactions from the
63// pool, we select by highest priority or fee rate, so we might consider
64// transactions that depend on transactions that aren't yet in the block.
65// The COrphan class keeps track of these 'temporary orphans' while
66// CreateBlock is figuring out which transactions to include.
67//
d247a5d1
JG
68class COrphan
69{
70public:
4d707d51 71 const CTransaction* ptx;
d247a5d1 72 set<uint256> setDependsOn;
c6cb21d1 73 CFeeRate feeRate;
02bec4b2 74 double dPriority;
e9e70b95 75
c6cb21d1 76 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 77 {
d247a5d1 78 }
d247a5d1
JG
79};
80
51ed9ec9
BD
81uint64_t nLastBlockTx = 0;
82uint64_t nLastBlockSize = 0;
d247a5d1 83
c6cb21d1
GA
84// We want to sort transactions by priority and fee rate, so:
85typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
86class TxPriorityCompare
87{
88 bool byFee;
e9e70b95 89
d247a5d1
JG
90public:
91 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
e9e70b95 92
d247a5d1
JG
93 bool operator()(const TxPriority& a, const TxPriority& b)
94 {
95 if (byFee)
96 {
97 if (a.get<1>() == b.get<1>())
98 return a.get<0>() < b.get<0>();
99 return a.get<1>() < b.get<1>();
100 }
101 else
102 {
103 if (a.get<0>() == b.get<0>())
104 return a.get<1>() < b.get<1>();
105 return a.get<0>() < b.get<0>();
106 }
107 }
108};
109
bebe7282 110void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 111{
112 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
5ead4b17
JG
113
114 // Updating time can change work required on testnet:
4c902704 115 if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {
5ead4b17 116 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
b86dc980 117 }
22c4272b 118}
119
5416af1d 120#include "komodo_defs.h"
121
69767347 122extern CCriticalSection cs_metrics;
6e78d3df 123extern 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 124extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
5f63373e 125extern bool VERUS_MINTBLOCKS;
42181656 126extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
127extern const char *ASSETCHAINS_ALGORITHMS[];
5296a850 128extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
7c130297 129extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
b2a98c42
MT
130extern uint160 ASSETCHAINS_CHAINID;
131extern uint160 VERUS_CHAINID;
f2d873d0 132extern std::string VERUS_CHAINNAME;
68b309c0 133extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK;
7af5cf39 134extern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;;
f8f61a6d 135extern int32_t PBAAS_PORT;
7af5cf39 136extern uint16_t ASSETCHAINS_RPCPORT;
d9f176ac 137extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
292809f7 138void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
d9f176ac 139
94a465a6 140extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 141uint32_t Mining_start,Mining_height;
28a62b60 142int32_t My_notaryid = -1;
8683bd8d 143int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 144int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
d63fdb34 145int32_t komodo_baseid(char *origbase);
3bc88f14 146int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
29bd53a1 147int64_t komodo_block_unlocktime(uint32_t nHeight);
18443f69 148uint64_t komodo_commission(const CBlock *block);
d231a6a7 149int32_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 150int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);
496f1fd2 151int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
7652ed92 152
5034d1c1 153CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
d247a5d1 154{
8626f666 155 CScript scriptPubKeyIn(_scriptPubKeyIn);
06f41160 156
157 CPubKey pk = CPubKey();
158 std::vector<std::vector<unsigned char>> vAddrs;
159 txnouttype txT;
160 if (Solver(scriptPubKeyIn, txT, vAddrs))
161 {
162 if (txT == TX_PUBKEY)
163 pk = CPubKey(vAddrs[0]);
164 }
165
9339a0cb 166 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
2a6a442a 167 //fprintf(stderr,"create new block\n");
df756d24 168 // Create new block
16593898 169 if ( gpucount < 0 )
170 gpucount = KOMODO_MAXGPUCOUNT;
08c58194 171 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 172 if(!pblocktemplate.get())
1b5b89ba 173 {
174 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 175 return NULL;
1b5b89ba 176 }
d247a5d1 177 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
12217420 178
179 // set version according to the current tip height, add solution if it is
180 // VerusHash
181 if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)
182 {
183 pblock->nSolution.resize(Eh200_9.SolutionWidth);
184 }
185 else
186 {
187 pblock->nSolution.clear();
188 }
189 pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1);
190
191 // -regtest only: allow overriding block.nVersion with
dbca89b7
GA
192 // -blockversion=N to test forking scenarios
193 if (Params().MineBlocksOnDemand())
194 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
e9e70b95 195
4949004d
PW
196 // Add dummy coinbase tx as first transaction
197 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
198 pblocktemplate->vTxFees.push_back(-1); // updated at end
199 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
e9e70b95 200
d247a5d1 201 // Largest block you're willing to create:
ad898b40 202 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
203 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
204 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
e9e70b95 205
d247a5d1
JG
206 // How much of the block should be dedicated to high-priority transactions,
207 // included regardless of the fees they pay
208 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
209 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
e9e70b95 210
d247a5d1
JG
211 // Minimum block size you want to create; block will be filled with free transactions
212 // until there are no more or the block reaches this size:
037b4f14 213 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1 214 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
e9e70b95 215
d247a5d1 216 // Collect memory pool transactions into the block
a372168e 217 CAmount nFees = 0;
df756d24
MT
218
219 // we will attempt to spend any cheats we see
220 CTransaction cheatTx;
221 boost::optional<CTransaction> cheatSpend;
222 uint256 cbHash;
223
562852ab 224 CBlockIndex* pindexPrev = 0;
d247a5d1
JG
225 {
226 LOCK2(cs_main, mempool.cs);
562852ab 227 pindexPrev = chainActive.LastTip();
4b729ec5 228 const int nHeight = pindexPrev->GetHeight() + 1;
df756d24
MT
229 const Consensus::Params &consensusParams = chainparams.GetConsensus();
230 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);
231 bool sapling = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING);
a0dd01bc 232
a1d3c6fb 233 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
a0dd01bc 234 uint32_t proposedTime = GetAdjustedTime();
235 if (proposedTime == nMedianTimePast)
236 {
237 // too fast or stuck, this addresses the too fast issue, while moving
238 // forward as quickly as possible
239 for (int i; i < 100; i++)
240 {
241 proposedTime = GetAdjustedTime();
242 if (proposedTime == nMedianTimePast)
243 MilliSleep(10);
244 }
245 }
246 pblock->nTime = GetAdjustedTime();
247
7c70438d 248 CCoinsViewCache view(pcoinsTip);
f9155fec 249 uint32_t expired; uint64_t commission;
6ff77181 250
4fc309f0 251 SaplingMerkleTree sapling_tree;
31a04d28
SB
252 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
253
d247a5d1
JG
254 // Priority order to process transactions
255 list<COrphan> vOrphan; // list memory doesn't move
256 map<uint256, vector<COrphan*> > mapDependers;
257 bool fPrintPriority = GetBoolArg("-printpriority", false);
e9e70b95 258
d247a5d1
JG
259 // This vector will be sorted into a priority queue:
260 vector<TxPriority> vecPriority;
df756d24
MT
261 vecPriority.reserve(mempool.mapTx.size() + 1);
262
263 // check if we should add cheat transaction
264 CBlockIndex *ppast;
ec8a120b 265 CTransaction cb;
83a426bc 266 int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;
df756d24
MT
267 if (cheatCatcher &&
268 sapling && chainActive.Height() > 100 &&
83a426bc 269 (ppast = chainActive[cheatHeight]) &&
df756d24 270 ppast->IsVerusPOSBlock() &&
83a426bc 271 cheatList.IsHeightOrGreaterInList(cheatHeight))
df756d24
MT
272 {
273 // get the block and see if there is a cheat candidate for the stake tx
274 CBlock b;
275 if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1))
276 {
277 CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];
278
279 if (cheatList.IsCheatInList(stakeTx, &cheatTx))
280 {
281 // make and sign the cheat transaction to spend the coinbase to our address
282 CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
283
73a4cd20 284 uint32_t voutNum;
285 // get the first vout with value
286 for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)
287 {
288 if (b.vtx[0].vout[voutNum].nValue > 0)
289 break;
290 }
291
df756d24 292 // send to the same pub key as the destination of this block reward
73a4cd20 293 if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))
df756d24
MT
294 {
295 extern CWallet *pwalletMain;
296 LOCK(pwalletMain->cs_wallet);
6c621e0e 297 TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);
ec8a120b 298 cb = b.vtx[0];
df756d24
MT
299 cbHash = cb.GetHash();
300
301 bool hasInput = false;
302 for (uint32_t i = 0; i < cb.vout.size(); i++)
303 {
304 // add the spends with the cheat
73a4cd20 305 if (cb.vout[i].nValue > 0)
df756d24
MT
306 {
307 tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);
308 hasInput = true;
309 }
310 }
311
312 if (hasInput)
313 {
314 // this is a send from a t-address to a sapling address, which we don't have an ovk for.
315 // Instead, generate a common one from the HD seed. This ensures the data is
316 // recoverable, at least for us, while keeping it logically separate from the ZIP 32
317 // Sapling key hierarchy, which the user might not be using.
318 uint256 ovk;
319 HDSeed seed;
320 if (pwalletMain->GetHDSeed(seed)) {
321 ovk = ovkForShieldingFromTaddr(seed);
322
ac2b2404 323 // send everything to Sapling address
324 tb.SendChangeTo(cheatCatcher.value(), ovk);
325
2d02c19e 326 tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);
df756d24
MT
327
328 cheatSpend = tb.Build();
df756d24
MT
329 }
330 }
331 }
332 }
333 }
334 }
335
271326fa 336 if (cheatSpend)
337 {
90cc70cc 338 cheatTx = cheatSpend.value();
271326fa 339 std::list<CTransaction> removed;
45bb4681 340 mempool.removeConflicts(cheatTx, removed);
c8700efe 341 printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n",
ec8a120b 342 (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());
45bb4681 343
344 // add to mem pool and relay
345 if (myAddtomempool(cheatTx))
346 {
347 RelayTransaction(cheatTx);
348 }
271326fa 349 }
350
4fa3b13d 351 // if we are a PBaaS chain, first make sure we don't start prematurely, and if
68b309c0
MT
352 // we should make an earned notarization, make it and set index to non-zero value
353 int32_t pbaasNotarizationTx = 0;
354 int64_t pbaasTransparentIn = 0;
eb0a6550 355 int64_t pbaasTransparentOut = 0;
8577896f 356 uint256 mmrRoot;
4fa3b13d 357 if (!IsVerusActive())
2299bd95 358 {
68b309c0
MT
359 // if we don't have a connected root PBaaS chain, we can't properly check
360 // and notarize the start block, so we have to pass and wait
361 if (nHeight != 1 || (ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK))
4fa3b13d 362 {
68b309c0
MT
363 // if we have access to our parent daemon
364 // create a notarization, if we would qualify, and add it to the mempool and block
4fa3b13d
MT
365 CMutableTransaction newNotarizationTx;
366 CTransaction prevTx, crossTx;
367 ChainMerkleMountainView mmv = chainActive.GetMMV();
8577896f 368 mmrRoot = mmv.GetRoot();
4fa3b13d
MT
369 if (CreateEarnedNotarization(newNotarizationTx, prevTx, crossTx, nHeight, mmrRoot))
370 {
68b309c0 371 // we have a valid, earned notarization transaction. we still need to verify:
eb0a6550 372 // 1. it has matching input for its outputs, since it can be returned with less than enough,
373 // if there is not enough, take it as instant-spend from the coinbase. if there is too much,
374 // increase the output on the main notarization thread.
375 // instant-spend and notarization
376 // transaction threads on a PBaaS chain can only be used for notarization, and can never convert to
68b309c0
MT
377 // available supply
378
379 // Fetch previous transactions (inputs):
380 for (const CTxIn& txin : newNotarizationTx.vin)
381 {
382 const uint256& prevHash = txin.prevout.hash;
383 const CCoins *pcoins = view.AccessCoins(prevHash); // this is certainly allowed to fail
384 pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0;
385 }
eb0a6550 386
387 for (auto txout : newNotarizationTx.vout)
388 {
389 pbaasTransparentOut += txout.nValue;
390 }
391
392 if (pbaasTransparentOut < pbaasTransparentIn)
393 {
394 // add excess to the notarization output
395 int notarizeOut = -1;
396 for (int outIdx = 0; outIdx < newNotarizationTx.vout.size(); outIdx++)
397 {
398 uint32_t ecode;
399 if (newNotarizationTx.vout[outIdx].scriptPubKey.IsPayToCryptoCondition(&ecode))
400 {
401 if (ecode == EVAL_EARNEDNOTARIZATION)
402 {
403 newNotarizationTx.vout[outIdx].nValue += pbaasTransparentIn - pbaasTransparentOut;
404 break;
405 }
406 }
407 }
408 }
409
410 if (pbaasTransparentOut > pbaasTransparentIn)
411 {
8577896f 412 // add a non-fungible input to bind the notarization to the block, specific to block height, previous MMR
413 // output will be added to coinbase with the same notarization output as well
414 newNotarizationTx.vin.push_back(CTxIn(::GetHash(CPBaaSNotarization(newNotarizationTx)), 0));
eb0a6550 415 }
416
68b309c0
MT
417 pblock->vtx.push_back(CTransaction(newNotarizationTx));
418 pblocktemplate->vTxFees.push_back(0);
419 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
420 pbaasNotarizationTx = pblock->vtx.size() - 1;
421 }
422 else if (nHeight == 1)
423 {
424 // failed to notarize at block 1
425 return NULL;
4fa3b13d
MT
426 }
427 }
428 else
429 {
430 // can't mine block 1 unless we have a connection to Verus and can notarize
431 return NULL;
432 }
2299bd95
MT
433 }
434
271326fa 435 // now add transactions from the mem pool
e328fa32 436 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 437 mi != mempool.mapTx.end(); ++mi)
d247a5d1 438 {
e328fa32 439 const CTransaction& tx = mi->GetTx();
e9e70b95 440
a1d3c6fb 441 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
e9e70b95 442 ? nMedianTimePast
443 : pblock->GetBlockTime();
9c034267 444
9bb37bf0 445 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
61f8caf2 446 {
51376f3c 447 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
14aa6cc0 448 continue;
61f8caf2 449 }
9c034267 450
161f617d 451 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
6ff77181 452 {
64b45b71 453 //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 454 continue;
14aa6cc0 455 }
df756d24 456
d247a5d1
JG
457 COrphan* porphan = NULL;
458 double dPriority = 0;
a372168e 459 CAmount nTotalIn = 0;
d247a5d1 460 bool fMissingInputs = false;
0cb91a8d 461 if (tx.IsCoinImport())
d247a5d1 462 {
0cb91a8d
SS
463 CAmount nValueIn = GetCoinImportValue(tx);
464 nTotalIn += nValueIn;
465 dPriority += (double)nValueIn * 1000; // flat multiplier
466 } else {
467 BOOST_FOREACH(const CTxIn& txin, tx.vin)
d247a5d1 468 {
0cb91a8d
SS
469 // Read prev transaction
470 if (!view.HaveCoins(txin.prevout.hash))
d247a5d1 471 {
0cb91a8d
SS
472 // This should never happen; all transactions in the memory
473 // pool should connect to either transactions in the chain
474 // or other transactions in the memory pool.
475 if (!mempool.mapTx.count(txin.prevout.hash))
476 {
477 LogPrintf("ERROR: mempool transaction missing input\n");
478 if (fDebug) assert("mempool transaction missing input" == 0);
479 fMissingInputs = true;
480 if (porphan)
481 vOrphan.pop_back();
482 break;
483 }
484
485 // Has to wait for dependencies
486 if (!porphan)
487 {
488 // Use list for automatic deletion
489 vOrphan.push_back(COrphan(&tx));
490 porphan = &vOrphan.back();
491 }
492 mapDependers[txin.prevout.hash].push_back(porphan);
493 porphan->setDependsOn.insert(txin.prevout.hash);
494 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
495 continue;
d247a5d1 496 }
0cb91a8d
SS
497 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
498 assert(coins);
499
500 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
501 nTotalIn += nValueIn;
502
503 int nConf = nHeight - coins->nHeight;
504
505 dPriority += (double)nValueIn * nConf;
d247a5d1 506 }
9feb4b9e 507 nTotalIn += tx.GetShieldedValueIn();
d247a5d1 508 }
0cb91a8d 509
d247a5d1 510 if (fMissingInputs) continue;
e9e70b95 511
d6eb2599 512 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 513 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 514 dPriority = tx.ComputePriority(dPriority, nTxSize);
e9e70b95 515
805344dc 516 uint256 hash = tx.GetHash();
2a72d459 517 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
e9e70b95 518
c6cb21d1 519 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
e9e70b95 520
d247a5d1
JG
521 if (porphan)
522 {
523 porphan->dPriority = dPriority;
c6cb21d1 524 porphan->feeRate = feeRate;
d247a5d1
JG
525 }
526 else
e328fa32 527 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1 528 }
df756d24 529
d247a5d1 530 // Collect transactions into block
51ed9ec9
BD
531 uint64_t nBlockSize = 1000;
532 uint64_t nBlockTx = 0;
355ca565 533 int64_t interest;
d247a5d1
JG
534 int nBlockSigOps = 100;
535 bool fSortedByFee = (nBlockPrioritySize <= 0);
e9e70b95 536
d247a5d1
JG
537 TxPriorityCompare comparer(fSortedByFee);
538 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
e9e70b95 539
d247a5d1
JG
540 while (!vecPriority.empty())
541 {
542 // Take highest priority transaction off the priority queue:
543 double dPriority = vecPriority.front().get<0>();
c6cb21d1 544 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 545 const CTransaction& tx = *(vecPriority.front().get<2>());
e9e70b95 546
d247a5d1
JG
547 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
548 vecPriority.pop_back();
e9e70b95 549
d247a5d1
JG
550 // Size limits
551 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
01fda4c1 552 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
61f8caf2 553 {
51376f3c 554 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
d247a5d1 555 continue;
61f8caf2 556 }
e9e70b95 557
d247a5d1
JG
558 // Legacy limits on sigOps:
559 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
a4a40a38 560 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 561 {
51376f3c 562 //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 563 continue;
61f8caf2 564 }
d247a5d1 565 // Skip free transactions if we're past the minimum block size:
805344dc 566 const uint256& hash = tx.GetHash();
2a72d459 567 double dPriorityDelta = 0;
a372168e 568 CAmount nFeeDelta = 0;
2a72d459 569 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 570 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
61f8caf2 571 {
51376f3c 572 //fprintf(stderr,"fee rate skip\n");
d247a5d1 573 continue;
61f8caf2 574 }
2a72d459 575 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
576 // transactions:
577 if (!fSortedByFee &&
578 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
579 {
580 fSortedByFee = true;
581 comparer = TxPriorityCompare(fSortedByFee);
582 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
583 }
e9e70b95 584
d247a5d1 585 if (!view.HaveInputs(tx))
61f8caf2 586 {
51376f3c 587 //fprintf(stderr,"dont have inputs\n");
d247a5d1 588 continue;
61f8caf2 589 }
4b729ec5 590 CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
e9e70b95 591
d247a5d1 592 nTxSigOps += GetP2SHSigOpCount(tx, view);
a4a40a38 593 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 594 {
51376f3c 595 //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 596 continue;
61f8caf2 597 }
68f7d1d7
PT
598 // Note that flags: we don't want to set mempool/IsStandard()
599 // policy here, but we still have to ensure that the block we
600 // create only contains transactions that are valid in new blocks.
d247a5d1 601 CValidationState state;
6514771a 602 PrecomputedTransactionData txdata(tx);
be126699 603 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
61f8caf2 604 {
51376f3c 605 //fprintf(stderr,"context failure\n");
d247a5d1 606 continue;
61f8caf2 607 }
8cb98d91 608 UpdateCoins(tx, view, nHeight);
d247a5d1 609
31a04d28
SB
610 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
611 sapling_tree.append(outDescription.cm);
612 }
613
d247a5d1
JG
614 // Added
615 pblock->vtx.push_back(tx);
616 pblocktemplate->vTxFees.push_back(nTxFees);
617 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
618 nBlockSize += nTxSize;
619 ++nBlockTx;
620 nBlockSigOps += nTxSigOps;
621 nFees += nTxFees;
e9e70b95 622
d247a5d1
JG
623 if (fPrintPriority)
624 {
3f0813b3 625 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1 626 }
e9e70b95 627
d247a5d1
JG
628 // Add transactions that depend on this one to the priority queue
629 if (mapDependers.count(hash))
630 {
631 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
632 {
633 if (!porphan->setDependsOn.empty())
634 {
635 porphan->setDependsOn.erase(hash);
636 if (porphan->setDependsOn.empty())
637 {
c6cb21d1 638 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
639 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
640 }
641 }
642 }
643 }
644 }
e9e70b95 645
d247a5d1
JG
646 nLastBlockTx = nBlockTx;
647 nLastBlockSize = nBlockSize;
d07308d2 648 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9a0f2798 649 //pblock->nTime = blocktime + 1;
135fa24e 650 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
651
86e31e3d 652 int32_t stakeHeight = chainActive.Height() + 1;
86e31e3d 653
7dbeae5d 654 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
135fa24e 655 if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
a4a40a38 656 {
1f722359 657 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
86e31e3d 658 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), stakeHeight);
1f722359 659
cfb55edb 660 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
661 // blocktime = pindexPrev->GetMedianTimePast() + 60;
1f722359
MT
662 if (ASSETCHAINS_LWMAPOS != 0)
663 {
664 uint32_t nBitsPOS;
665 arith_uint256 posHash;
17d0160a 666
06f41160 667 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
1f722359 668 blocktime = GetAdjustedTime();
cd230e37
MT
669
670 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
671 if (siglen > 0)
672 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
1f722359
MT
673 }
674 else
675 {
5034d1c1 676 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
1f722359
MT
677 }
678
679 if ( siglen > 0 )
a4a40a38 680 {
86e31e3d 681 CAmount txfees;
682
683 // after Sapling, stake transactions have a fee, but it is recovered in the reward
684 // this ensures that a rebroadcast goes through quickly to begin staking again
df756d24 685 txfees = sapling ? DEFAULT_STAKE_TXFEE : 0;
86e31e3d 686
a4a40a38 687 pblock->vtx.push_back(txStaked);
a4a40a38 688 pblocktemplate->vTxFees.push_back(txfees);
d231a6a7 689 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
a4a40a38 690 nFees += txfees;
9339a0cb 691 pblock->nTime = blocktime;
4b729ec5 692 //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
9464ac21 693 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
a4a40a38 694 }
e9e70b95 695
f3ffa3d2 696 // Create coinbase tx
df756d24 697 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
f3ffa3d2
SB
698 txNew.vin.resize(1);
699 txNew.vin[0].prevout.SetNull();
abb90a89
MT
700 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
701
d581f229 702 txNew.vout.resize(1);
f3ffa3d2 703 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
df756d24 704 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,consensusParams) + nFees;
06f41160 705
ca4a5f26 706 // once we get to Sapling, enable CC StakeGuard for stake transactions
df756d24 707 if (isStake && sapling)
06f41160 708 {
709 // if there is a specific destination, use it
710 CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1];
711 CStakeParams p;
f3b0d2ab 712 if (ValidateStakeTransaction(stakeTx, p, false))
06f41160 713 {
86e31e3d 714 if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0]))
715 {
716 fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
06f41160 717 return 0;
86e31e3d 718 }
719 }
720 else
721 {
722 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
723 return 0;
06f41160 724 }
06f41160 725 }
726
9bb37bf0 727 txNew.nExpiryHeight = 0;
48d800c2 728 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
abb90a89 729
e0bc68e6 730 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
731 txNew.vout[0].nValue += 5000;
5034d1c1 732
29bd53a1 733 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
a0dd01bc 734 // to transaction if so, cast for GTE operator
735 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
abb90a89
MT
736 {
737 int32_t opretlen, p2shlen, scriptlen;
29bd53a1 738 CScriptExt opretScript = CScriptExt();
abb90a89
MT
739
740 txNew.vout.resize(2);
741
29bd53a1
MT
742 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
743 // protected only by the time lock rather than 100% inaccessible
744 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
06f41160 745 if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())
746 {
86e31e3d 747 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
06f41160 748 return 0;
749 }
750
751 opretScript += scriptPubKeyIn;
abb90a89 752
29bd53a1
MT
753 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
754 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
abb90a89 755 txNew.vout[1].nValue = 0;
48d800c2 756 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
5034d1c1 757 else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
c9b1071d 758 {
c000c9ca 759 int32_t i; uint8_t *ptr;
9ed1be03 760 txNew.vout.resize(2);
761 txNew.vout[1].nValue = commission;
762 txNew.vout[1].scriptPubKey.resize(35);
9feb4b9e 763 ptr = (uint8_t *)&txNew.vout[1].scriptPubKey[0];
c000c9ca 764 ptr[0] = 33;
765 for (i=0; i<33; i++)
766 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
767 ptr[34] = OP_CHECKSIG;
146d2aa2 768 //printf("autocreate commision vout\n");
c9b1071d 769 }
48d800c2 770
eb0a6550 771 // add final notarization and instant spend fixups
68b309c0
MT
772 if (pbaasNotarizationTx)
773 {
774 extern CWallet *pwalletMain;
775 LOCK(pwalletMain->cs_wallet);
776
68b309c0 777 CMutableTransaction mntx(pblock->vtx[pbaasNotarizationTx]);
68b309c0 778
8577896f 779 // determine number of outputs
1e454a32 780 int numNotaryOutputs = mntx.vout.size() - (mntx.vout[mntx.vout.size() - 1].scriptPubKey.IsOpReturn() ? 1 : 0);
eb0a6550 781
782 int64_t needed = pbaasTransparentOut - pbaasTransparentIn;
1e454a32 783 if (needed > PBAAS_MINNOTARIZATIONOUTPUT * numNotaryOutputs)
68b309c0 784 {
eb0a6550 785 fprintf(stderr,"CreateNewBlock: too much output from earned notarization transaction\n");
786 return NULL;
787 }
788
eb0a6550 789 int32_t pbaasCoinbaseInstantSpendOut;
68b309c0 790
eb0a6550 791 // if we need an instant out to be a source of funds for the notarization transaction, make it here
792 if (needed > 0)
793 {
8577896f 794 // the new instant spend out will go at the end and before any opret
1e454a32 795 pbaasCoinbaseInstantSpendOut = txNew.vout.size() - (txNew.vout[txNew.vout.size() - 1].scriptPubKey.IsOpReturn() ? 1 : 0);
eb0a6550 796
1e454a32 797 auto coinbaseOutIt = txNew.vout.begin() + pbaasCoinbaseInstantSpendOut;
68b309c0
MT
798
799 CCcontract_info CC;
800 CCcontract_info *cp;
801 vector<CTxDestination> vKeys;
802
803 // make the earned notarization output
804 cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);
8577896f 805 // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey
806 CPubKey pk(ParseHex(cp->CChexstr));
68b309c0
MT
807
808 vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION))));
809
810 // output duplicate notarization as coinbase output for instant spend to notarization
8577896f 811 // the output is 0 and will be used to match, not to spend, so it does not need to be considered as
eb0a6550 812 // part of the total value of this coinbase
813 CPBaaSNotarization pbn(pblock->vtx[pbaasNotarizationTx]);
8577896f 814 txNew.vout.insert(coinbaseOutIt, MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, 0, pk, vKeys, pbn));
815 pblock->vtx[0] = txNew;
816
817 // bind to the right output of the coinbase
818 mntx.vin[mntx.vin.size() - 1].prevout.n = pbaasCoinbaseInstantSpendOut;
eb0a6550 819
820 // put notarization back in the block
821 pblock->vtx[pbaasNotarizationTx] = mntx;
68b309c0
MT
822 }
823
eb0a6550 824 CTransaction ntx(mntx);
68b309c0 825
8577896f 826 for (int i = 0, endat = (needed > 0 ? ntx.vin.size() - 1 : ntx.vin.size()); i < endat; i++)
68b309c0
MT
827 {
828 bool signSuccess;
68b309c0 829 SignatureData sigdata;
eb0a6550 830 CAmount value;
831 const CScript *pScriptPubKey;
8577896f 832
833 const CScript virtualCC;
834 CTxOut virtualCCOut;
835
836 if (needed > 0 && mmrRoot == ntx.vin[i].prevout.hash && nHeight == ntx.vin[i].prevout.n)
eb0a6550 837 {
8577896f 838 CCcontract_info CC;
839 CCcontract_info *cp;
840 vector<CTxDestination> vKeys;
841
842 // make the earned notarization output, but don't keep it
843 // on validation, we can ensure that an accurate notarization was spent as
844 cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);
845 CPubKey pk(ParseHex(cp->CChexstr));
846 vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION))));
847 CPBaaSNotarization pbn(pblock->vtx[pbaasNotarizationTx]);
848 virtualCCOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pk, vKeys, pbn);
849
850 pScriptPubKey = &virtualCCOut.scriptPubKey;
851 value = virtualCCOut.nValue;
eb0a6550 852 }
853 else
854 {
855 const CCoins *coins = view.AccessCoins(ntx.vin[i].prevout.hash);
856 pScriptPubKey = &coins->vout[ntx.vin[i].prevout.n].scriptPubKey;
857 value = coins->vout[ntx.vin[i].prevout.n].nValue;
858 }
8577896f 859
eb0a6550 860 signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId);
68b309c0
MT
861
862 if (!signSuccess)
863 {
864 fprintf(stderr,"CreateNewBlock: failure to sign earned notarization\n");
865 return NULL;
866 } else {
867 UpdateTransaction(mntx, i, sigdata);
868 }
869 }
68b309c0
MT
870 pblocktemplate->vTxSigOps[pbaasNotarizationTx] = GetLegacySigOpCount(mntx);
871 }
872
4949004d 873 pblock->vtx[0] = txNew;
d247a5d1 874 pblocktemplate->vTxFees[0] = -nFees;
48d800c2 875
1fae37f6
MT
876 // if not Verus stake, setup nonce, otherwise, leave it alone
877 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
878 {
eb0a6550 879 // Randomize nonce
1fae37f6 880 arith_uint256 nonce = UintToArith256(GetRandHash());
48d800c2 881
1fae37f6
MT
882 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
883 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
884 nonce >>= 16;
885 pblock->nNonce = ArithToUint256(nonce);
886 }
e9e70b95 887
d247a5d1
JG
888 // Fill in header
889 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
31a04d28 890 pblock->hashFinalSaplingRoot = sapling_tree.root();
0c8fa56a
MT
891
892 // all Verus PoS chains need this data in the block at all times
893 if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )
9a0f2798 894 {
895 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
1fae37f6 896 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
9a0f2798 897 }
12217420 898
d247a5d1 899 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
68b309c0 900
4d068367 901 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
af805d53 902 {
28a62b60 903 uint32_t r;
496f1fd2 904 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
fa04bcf3 905 if ( pblock->nTime < pindexPrev->nTime+60 )
906 pblock->nTime = pindexPrev->nTime + 60;
16593898 907 if ( gpucount < 33 )
28a62b60 908 {
55566f16 909 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
28a62b60 910 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
911 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
912 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
9a146fef 913 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
55566f16 914 memcpy(&r,&randvals,sizeof(r));
915 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
28a62b60 916 }
a893e994 917 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
496f1fd2 918 {
2d79309f 919 CAmount txfees = 5000;
496f1fd2 920 pblock->vtx.push_back(txNotary);
921 pblocktemplate->vTxFees.push_back(txfees);
922 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
923 nFees += txfees;
2d79309f 924 pblocktemplate->vTxFees[0] = -nFees;
c881e52b 925 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
f31815fc 926 //fprintf(stderr,"added notaryvin\n");
0857c3d5 927 }
928 else
929 {
930 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
931 return(0);
932 }
707b061c 933 }
809f2e25 934 else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
af805d53 935 {
8fc79ac9 936 CValidationState state;
809f2e25 937 //fprintf(stderr,"check validity\n");
938 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks
8fc79ac9 939 {
9feb4b9e 940 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
8fc79ac9 941 }
809f2e25 942 //fprintf(stderr,"valid\n");
af805d53 943 }
d247a5d1 944 }
2a6a442a 945 //fprintf(stderr,"done new block\n");
d247a5d1
JG
946 return pblocktemplate.release();
947}
32b915c9 948
1a31463b 949/*
e9e70b95 950 #ifdef ENABLE_WALLET
951 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
952 #else
953 boost::optional<CScript> GetMinerScriptPubKey()
954 #endif
955 {
956 CKeyID keyID;
957 CBitcoinAddress addr;
958 if (addr.SetString(GetArg("-mineraddress", ""))) {
959 addr.GetKeyID(keyID);
960 } else {
961 #ifdef ENABLE_WALLET
962 CPubKey pubkey;
963 if (!reservekey.GetReservedKey(pubkey)) {
964 return boost::optional<CScript>();
965 }
966 keyID = pubkey.GetID();
967 #else
968 return boost::optional<CScript>();
969 #endif
970 }
971
972 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
973 return scriptPubKey;
974 }
975
976 #ifdef ENABLE_WALLET
977 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
978 {
979 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
980 #else
981 CBlockTemplate* CreateNewBlockWithKey()
982 {
983 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
984 #endif
985
986 if (!scriptPubKey) {
987 return NULL;
988 }
989 return CreateNewBlock(*scriptPubKey);
990 }*/
acfa0333 991
c1de826f
JG
992//////////////////////////////////////////////////////////////////////////////
993//
994// Internal miner
995//
996
2cc0a252 997#ifdef ENABLE_MINING
c1de826f 998
d247a5d1
JG
999void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
1000{
1001 // Update nExtraNonce
1002 static uint256 hashPrevBlock;
1003 if (hashPrevBlock != pblock->hashPrevBlock)
1004 {
1005 nExtraNonce = 0;
1006 hashPrevBlock = pblock->hashPrevBlock;
1007 }
1008 ++nExtraNonce;
4b729ec5 1009 unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2
4949004d
PW
1010 CMutableTransaction txCoinbase(pblock->vtx[0]);
1011 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
1012 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
e9e70b95 1013
4949004d 1014 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
1015 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
1016}
1017
4a85e067 1018#ifdef ENABLE_WALLET
acfa0333
WL
1019//////////////////////////////////////////////////////////////////////////////
1020//
1021// Internal miner
1022//
acfa0333 1023
5034d1c1 1024CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
acfa0333 1025{
9feb4b9e 1026 CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
d9f176ac 1027 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
1028 {
1029 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
1030 }
1031 else if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 1032 {
7bfc207a 1033 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 1034 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 1035 }
1036 else
1037 {
f1f6dfbb 1038 if (!isStake)
1b5b89ba 1039 {
f1f6dfbb 1040 if (!reservekey.GetReservedKey(pubkey))
1041 {
1042 return NULL;
1043 }
1044 scriptPubKey.resize(35);
1045 ptr = (uint8_t *)pubkey.begin();
1046 scriptPubKey[0] = 33;
1047 for (i=0; i<33; i++)
1048 scriptPubKey[i+1] = ptr[i];
1049 scriptPubKey[34] = OP_CHECKSIG;
1050 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
1b5b89ba 1051 }
f6c647ed 1052 }
5034d1c1 1053 return CreateNewBlock(scriptPubKey, gpucount, isStake);
acfa0333
WL
1054}
1055
395f10cf 1056void komodo_broadcast(CBlock *pblock,int32_t limit)
1057{
1058 int32_t n = 1;
1059 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
1060 {
1061 LOCK(cs_vNodes);
1062 BOOST_FOREACH(CNode* pnode, vNodes)
1063 {
1064 if ( pnode->hSocket == INVALID_SOCKET )
1065 continue;
1066 if ( (rand() % n) == 0 )
1067 {
1068 pnode->PushMessage("block", *pblock);
1069 if ( n++ > limit )
1070 break;
1071 }
1072 }
1073 }
1074 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
1075}
945f015d 1076
269d8ba0 1077static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
1078#else
1079static bool ProcessBlockFound(CBlock* pblock)
1080#endif // ENABLE_WALLET
d247a5d1 1081{
81212588 1082 LogPrintf("%s\n", pblock->ToString());
4b729ec5 1083 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1);
e9e70b95 1084
d247a5d1
JG
1085 // Found a solution
1086 {
86131275 1087 if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
ba8419c7 1088 {
1089 uint256 hash; int32_t i;
1090 hash = pblock->hashPrevBlock;
92266e99 1091 for (i=31; i>=0; i--)
ba8419c7 1092 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 1093 fprintf(stderr," <- prev (stale)\n");
86131275 1094 hash = chainActive.LastTip()->GetBlockHash();
92266e99 1095 for (i=31; i>=0; i--)
ba8419c7 1096 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 1097 fprintf(stderr," <- chainTip (stale)\n");
e9e70b95 1098
ffde1589 1099 return error("VerusMiner: generated block is stale");
ba8419c7 1100 }
18e72167 1101 }
e9e70b95 1102
8e8b6d70 1103#ifdef ENABLE_WALLET
18e72167 1104 // Remove key from key pool
998397aa 1105 if ( IS_KOMODO_NOTARY == 0 )
945f015d 1106 {
1107 if (GetArg("-mineraddress", "").empty()) {
1108 // Remove key from key pool
1109 reservekey.KeepKey();
1110 }
8e8b6d70 1111 }
18e72167 1112 // Track how many getdata requests this block gets
438ba9c1 1113 //if ( 0 )
18e72167 1114 {
d1bc3a75 1115 //fprintf(stderr,"lock cs_wallet\n");
18e72167
PW
1116 LOCK(wallet.cs_wallet);
1117 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 1118 }
8e8b6d70 1119#endif
d1bc3a75 1120 //fprintf(stderr,"process new block\n");
194ad5b8 1121
18e72167
PW
1122 // Process this block the same as if we had received it from another node
1123 CValidationState state;
4b729ec5 1124 if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL))
ffde1589 1125 return error("VerusMiner: ProcessNewBlock, block not accepted");
e9e70b95 1126
d793f94b 1127 TrackMinedBlock(pblock->GetHash());
395f10cf 1128 komodo_broadcast(pblock,16);
d247a5d1
JG
1129 return true;
1130}
1131
078f6af1 1132int32_t komodo_baseid(char *origbase);
a30dd993 1133int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
13691369 1134arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
8ee93080 1135int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
99ba67a0 1136extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
8b51b9e4 1137int32_t roundrobin_delay;
18443f69 1138arith_uint256 HASHTarget,HASHTarget_POW;
3363d1c0 1139int32_t komodo_longestchain();
078f6af1 1140
5642c96c 1141// wait for peers to connect
12217420 1142void waitForPeers(const CChainParams &chainparams)
5642c96c 1143{
1144 if (chainparams.MiningRequiresPeers())
1145 {
3da69a31
MT
1146 bool fvNodesEmpty;
1147 {
00a7120e 1148 boost::this_thread::interruption_point();
3da69a31
MT
1149 LOCK(cs_vNodes);
1150 fvNodesEmpty = vNodes.empty();
1151 }
3363d1c0 1152 int longestchain = komodo_longestchain();
1153 int lastlongest = 0;
1154 if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight()))
3da69a31 1155 {
af2e212d 1156 int loops = 0, blockDiff = 0, newDiff = 0;
1157
3da69a31 1158 do {
64d6048f 1159 if (fvNodesEmpty)
3da69a31 1160 {
69fa3d0e 1161 MilliSleep(1000 + rand() % 4000);
00a7120e 1162 boost::this_thread::interruption_point();
3da69a31
MT
1163 LOCK(cs_vNodes);
1164 fvNodesEmpty = vNodes.empty();
af2e212d 1165 loops = 0;
1166 blockDiff = 0;
3363d1c0 1167 lastlongest = 0;
af2e212d 1168 }
3363d1c0 1169 else if ((newDiff = IsNotInSync()) > 0)
af2e212d 1170 {
1171 if (blockDiff != newDiff)
1172 {
1173 blockDiff = newDiff;
1174 }
1175 else
1176 {
3363d1c0 1177 if (++loops <= 5)
af2e212d 1178 {
1179 MilliSleep(1000);
1180 }
1181 else break;
1182 }
3363d1c0 1183 lastlongest = 0;
1184 }
1185 else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight())
1186 {
1187 // the only thing may be that we are seeing a long chain that we'll never get
1188 // don't wait forever
1189 if (lastlongest == 0)
1190 {
1191 MilliSleep(3000);
1192 lastlongest = longestchain;
1193 }
3da69a31 1194 }
af2e212d 1195 } while (fvNodesEmpty || IsNotInSync());
0ba20651 1196 MilliSleep(100 + rand() % 400);
3da69a31 1197 }
5642c96c 1198 }
1199}
1200
42181656 1201#ifdef ENABLE_WALLET
d7e6718d
MT
1202CBlockIndex *get_chainactive(int32_t height)
1203{
3c40a9a6 1204 if ( chainActive.LastTip() != 0 )
d7e6718d 1205 {
4b729ec5 1206 if ( height <= chainActive.LastTip()->GetHeight() )
3c40a9a6
MT
1207 {
1208 LOCK(cs_main);
d7e6718d 1209 return(chainActive[height]);
3c40a9a6 1210 }
4b729ec5 1211 // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
d7e6718d
MT
1212 }
1213 //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
1214 return(0);
1215}
1216
135fa24e 1217/*
1218 * A separate thread to stake, while the miner threads mine.
1219 */
1220void static VerusStaker(CWallet *pwallet)
1221{
1222 LogPrintf("Verus staker thread started\n");
1223 RenameThread("verus-staker");
1224
1225 const CChainParams& chainparams = Params();
2d02c19e 1226 auto consensusParams = chainparams.GetConsensus();
135fa24e 1227
1228 // Each thread has its own key
1229 CReserveKey reservekey(pwallet);
1230
1231 // Each thread has its own counter
1232 unsigned int nExtraNonce = 0;
12217420 1233
135fa24e 1234 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1235
4b729ec5 1236 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
135fa24e 1237 {
1238 sleep(1);
1239 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1240 break;
1241 }
1242
1243 // try a nice clean peer connection to start
bf9c36f4
MT
1244 CBlockIndex *pindexPrev, *pindexCur;
1245 do {
1246 pindexPrev = chainActive.LastTip();
1247 MilliSleep(5000 + rand() % 5000);
1248 waitForPeers(chainparams);
1249 pindexCur = chainActive.LastTip();
1250 } while (pindexPrev != pindexCur);
c132b91a 1251
135fa24e 1252 try {
0fc0dc56 1253 static int32_t lastStakingHeight = 0;
1254
135fa24e 1255 while (true)
1256 {
135fa24e 1257 waitForPeers(chainparams);
4ca6678c 1258 CBlockIndex* pindexPrev = chainActive.LastTip();
135fa24e 1259
1260 // Create new block
1261 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
0fc0dc56 1262
4b729ec5 1263 if ( Mining_height != pindexPrev->GetHeight()+1 )
135fa24e 1264 {
4b729ec5 1265 Mining_height = pindexPrev->GetHeight()+1;
135fa24e 1266 Mining_start = (uint32_t)time(NULL);
1267 }
1268
0fc0dc56 1269 if ( Mining_height != lastStakingHeight )
1270 {
1271 printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL);
1272 lastStakingHeight = Mining_height;
1273 }
1274
1fae37f6
MT
1275 // Check for stop or if block needs to be rebuilt
1276 boost::this_thread::interruption_point();
1277
135fa24e 1278 // try to stake a block
1fae37f6
MT
1279 CBlockTemplate *ptr = NULL;
1280 if (Mining_height > VERUS_MIN_STAKEAGE)
5034d1c1 1281 ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true);
135fa24e 1282
1283 if ( ptr == 0 )
1284 {
1fae37f6 1285 // wait to try another staking block until after the tip moves again
37ad6886 1286 while ( chainActive.LastTip() == pindexPrev )
bab13dd2 1287 MilliSleep(250);
135fa24e 1288 continue;
1289 }
1290
1291 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1292 if (!pblocktemplate.get())
1293 {
1294 if (GetArg("-mineraddress", "").empty()) {
1fae37f6 1295 LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
135fa24e 1296 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1297 } else {
1298 // Should never reach here, because -mineraddress validity is checked in init.cpp
1fae37f6 1299 LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
135fa24e 1300 }
1301 return;
1302 }
1303
1304 CBlock *pblock = &pblocktemplate->block;
1fae37f6 1305 LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
135fa24e 1306 //
1307 // Search
1308 //
1fae37f6
MT
1309 int64_t nStart = GetTime();
1310
1311 // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree
1312 unsigned int nExtraNonce = 0;
1313 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
135fa24e 1314
b2a98c42
MT
1315 // update PBaaS header
1316 if (CConstVerusSolutionVector::activationHeight.ActiveVersion(Mining_height) == CActivationHeight::SOLUTION_VERUSV3)
1317 {
b2a98c42
MT
1318 uint256 mmvRoot;
1319 {
1320 LOCK(cs_main);
f8f61a6d 1321 // set the PBaaS header
1322 ChainMerkleMountainView mmv = chainActive.GetMMV();
b2a98c42 1323 mmvRoot = mmv.GetRoot();
b2a98c42 1324 }
f8f61a6d 1325 pblock->AddUpdatePBaaSHeader(mmvRoot);
b2a98c42
MT
1326 }
1327
1fae37f6
MT
1328 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1329 {
1330 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1331 {
1332 fprintf(stderr,"no nodes, attempting reconnect\n");
1333 continue;
1334 }
1335 }
1336
1337 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1338 {
1339 fprintf(stderr,"timeout, retrying\n");
1340 continue;
1341 }
135fa24e 1342
37ad6886 1343 if ( pindexPrev != chainActive.LastTip() )
135fa24e 1344 {
4b729ec5 1345 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
135fa24e 1346 MilliSleep(250);
1347 continue;
1348 }
1349
1fae37f6
MT
1350 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1351 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
135fa24e 1352
1fae37f6 1353 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
135fa24e 1354
df756d24 1355 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
b9956efc 1356
df756d24 1357 UpdateTime(pblock, consensusParams, pindexPrev);
b9956efc
MT
1358
1359 ProcessBlockFound(pblock, *pwallet, reservekey);
1360
1fae37f6
MT
1361 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1362 LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
1363 printf("Found block %d \n", Mining_height );
1364 printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
b9956efc
MT
1365 arith_uint256 post;
1366 post.SetCompact(pblock->GetVerusPOSTarget());
d7e6718d 1367 pindexPrev = get_chainactive(Mining_height - 100);
d0cd5074 1368 CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];
1369 printf("POS hash: %s \ntarget: %s\n",
1370 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
1371 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1372 printf("- timelocked until block %i\n", unlockTime);
1373 else
1374 printf("\n");
135fa24e 1375
1fae37f6
MT
1376 // Check for stop or if block needs to be rebuilt
1377 boost::this_thread::interruption_point();
135fa24e 1378
bf9c36f4 1379 sleep(3);
3da69a31 1380
1fae37f6
MT
1381 // In regression test mode, stop mining after a block is found.
1382 if (chainparams.MineBlocksOnDemand()) {
1383 throw boost::thread_interrupted();
135fa24e 1384 }
1385 }
1386 }
1387 catch (const boost::thread_interrupted&)
1388 {
135fa24e 1389 LogPrintf("VerusStaker terminated\n");
1390 throw;
1391 }
1392 catch (const std::runtime_error &e)
1393 {
135fa24e 1394 LogPrintf("VerusStaker runtime error: %s\n", e.what());
1395 return;
1396 }
135fa24e 1397}
1398
fa7fdbc6 1399typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
1400bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
1401bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
1402
42181656 1403void static BitcoinMiner_noeq(CWallet *pwallet)
1404#else
1405void static BitcoinMiner_noeq()
1406#endif
1407{
05f6e633 1408 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
05f6e633 1409 RenameThread("verushash-miner");
42181656 1410
1411#ifdef ENABLE_WALLET
1412 // Each thread has its own key
1413 CReserveKey reservekey(pwallet);
1414#endif
1415
2910478b 1416 const CChainParams& chainparams = Params();
42181656 1417 // Each thread has its own counter
1418 unsigned int nExtraNonce = 0;
12217420 1419
42181656 1420 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1421
4b729ec5 1422 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
42181656 1423 {
1424 sleep(1);
1425 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1426 break;
1427 }
9f3e2213 1428
3da69a31
MT
1429 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1430
5642c96c 1431 // try a nice clean peer connection to start
c132b91a 1432 CBlockIndex *pindexPrev, *pindexCur;
9f3e2213 1433 do {
37ad6886 1434 pindexPrev = chainActive.LastTip();
3da69a31 1435 MilliSleep(5000 + rand() % 5000);
bf9c36f4 1436 waitForPeers(chainparams);
37ad6886 1437 pindexCur = chainActive.LastTip();
c132b91a 1438 } while (pindexPrev != pindexCur);
6176a421 1439
a9f18272 1440 // make sure that we have checked for PBaaS availability
1441 ConnectedChains.CheckVerusPBaaSAvailable();
1442
dbe656fe
MT
1443 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1444 // and print duplicates rarely without having to synchronize
1445 static CBlockIndex *lastChainTipPrinted;
90198f71 1446 static int32_t lastMiningHeight = 0;
9f3e2213 1447
42181656 1448 miningTimer.start();
1449
1450 try {
dbe656fe 1451 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
08d46b7f 1452
08d46b7f 1453 // v2 hash writer
1454 CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION);
1455
42181656 1456 while (true)
1457 {
68334c8d 1458 miningTimer.stop();
1459 waitForPeers(chainparams);
dfcf8255 1460
37ad6886 1461 pindexPrev = chainActive.LastTip();
dfcf8255 1462
f8f61a6d 1463 // prevent forking on startup before the diff algorithm kicks in,
1464 // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from
1465 // their parent
57055854 1466 if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip()))
dfcf8255
MT
1467 {
1468 do {
37ad6886 1469 pindexPrev = chainActive.LastTip();
2830db29 1470 MilliSleep(2000 + rand() % 2000);
37ad6886 1471 } while (pindexPrev != chainActive.LastTip());
dfcf8255 1472 }
42181656 1473
1474 // Create new block
1475 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
4b729ec5 1476 if ( Mining_height != pindexPrev->GetHeight()+1 )
42181656 1477 {
4b729ec5 1478 Mining_height = pindexPrev->GetHeight()+1;
90198f71 1479 if (lastMiningHeight != Mining_height)
1480 {
1481 lastMiningHeight = Mining_height;
dc74c06d 1482 printf("Mining %s at height %d\n", ASSETCHAINS_SYMBOL, Mining_height);
90198f71 1483 }
42181656 1484 Mining_start = (uint32_t)time(NULL);
1485 }
1486
dbe656fe 1487 miningTimer.start();
42181656 1488
1489#ifdef ENABLE_WALLET
5034d1c1 1490 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
42181656 1491#else
1492 CBlockTemplate *ptr = CreateNewBlockWithKey();
1493#endif
1494 if ( ptr == 0 )
1495 {
1496 static uint32_t counter;
bab13dd2 1497 if ( (counter++ < 10) || (counter % 40 == 0) )
1498 fprintf(stderr,"Unable to create valid block... will continue to try\n");
2830db29 1499 MilliSleep(2000);
42181656 1500 continue;
1501 }
dbe656fe 1502
42181656 1503 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1504 if (!pblocktemplate.get())
1505 {
1506 if (GetArg("-mineraddress", "").empty()) {
05f6e633 1507 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1508 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1509 } else {
1510 // Should never reach here, because -mineraddress validity is checked in init.cpp
05f6e633 1511 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
42181656 1512 }
1513 return;
1514 }
1515 CBlock *pblock = &pblocktemplate->block;
f8f61a6d 1516
1517 uint32_t savebits;
1518 bool mergeMining = false;
1519 savebits = pblock->nBits;
1520
1521 bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2;
1522 bool verusSolutionV3 = CConstVerusSolutionVector::Version(pblock->nSolution) == CActivationHeight::SOLUTION_VERUSV3;
1523
42181656 1524 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1525 {
1526 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1527 {
1528 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1529 {
1530 static uint32_t counter;
1531 if ( counter++ < 10 )
1532 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1533 sleep(10);
1534 continue;
1535 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1536 }
1537 }
b2a98c42
MT
1538
1539 // this builds the Merkle tree
42181656 1540 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
b2a98c42
MT
1541
1542 // update PBaaS header
f8f61a6d 1543 if (verusSolutionV3)
b2a98c42 1544 {
b2a98c42
MT
1545 uint256 mmvRoot;
1546 {
1547 LOCK(cs_main);
f8f61a6d 1548 ChainMerkleMountainView mmv = chainActive.GetMMV();
b2a98c42 1549 mmvRoot = mmv.GetRoot();
f8f61a6d 1550 }
1551 pblock->AddUpdatePBaaSHeader(mmvRoot);
1552
2fd1f0fb 1553 if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable())
f8f61a6d 1554 {
b2a98c42 1555
2fd1f0fb 1556 UniValue params(UniValue::VARR);
1557 UniValue error(UniValue::VARR);
1558 params.push_back(EncodeHexBlk(*pblock));
1559 params.push_back(ASSETCHAINS_SYMBOL);
1560 params.push_back(ASSETCHAINS_RPCHOST);
1561 params.push_back(ASSETCHAINS_RPCPORT);
1562 params.push_back(ASSETCHAINS_RPCCREDENTIALS);
1563 try
b2a98c42 1564 {
be17c611 1565 ConnectedChains.lastSubmissionFailed = false;
2fd1f0fb 1566 params = RPCCallRoot("addmergedblock", params);
1567 params = find_value(params, "result");
1568 error = find_value(params, "error");
1569 } catch (std::exception e)
1570 {
1571 printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
1572 params = UniValue(e.what());
b2a98c42 1573 }
2fd1f0fb 1574 if (mergeMining = (params.isNull() && error.isNull()))
f8f61a6d 1575 {
a1d91f89 1576 printf("Merge mining %s with %s as the hashing chain\n", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str());
1577 LogPrintf("Merge mining with %s as the hashing chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
f8f61a6d 1578 }
b2a98c42
MT
1579 }
1580 }
1581
42181656 1582 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1583 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1584 //
1585 // Search
1586 //
f8f61a6d 1587 int64_t nStart = GetTime();
42181656 1588
f8f61a6d 1589 arith_uint256 hashTarget = arith_uint256().SetCompact(savebits);
fa7fdbc6 1590 uint256 uintTarget = ArithToUint256(hashTarget);
f8f61a6d 1591 arith_uint256 ourTarget;
1592 ourTarget.SetCompact(pblock->nBits);
1593
42181656 1594 Mining_start = 0;
ef70c5b2 1595
37ad6886 1596 if ( pindexPrev != chainActive.LastTip() )
05f6e633 1597 {
37ad6886 1598 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1599 {
37ad6886 1600 lastChainTipPrinted = chainActive.LastTip();
4b729ec5 1601 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
dbe656fe 1602 }
f8f61a6d 1603 MilliSleep(100);
05f6e633 1604 continue;
1605 }
ef70c5b2 1606
135fa24e 1607 if ( ASSETCHAINS_STAKED != 0 )
1608 {
1609 int32_t percPoS,z;
1610 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1611 for (z=31; z>=0; z--)
1612 fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1613 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1614 }
1615
2830db29 1616 uint64_t count;
1617 uint64_t hashesToGo = 0;
1618 uint64_t totalDone = 0;
1619
fa7fdbc6 1620 if (!verusHashV2)
458bfcab 1621 {
fa7fdbc6 1622 // must not be in sync
1623 printf("Mining on incorrect block version.\n");
1624 sleep(2);
1625 continue;
458bfcab 1626 }
1627
2830db29 1628 int64_t subsidy = (int64_t)(pblock->vtx[0].GetValueOut());
fa7fdbc6 1629 count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
db027133 1630 CVerusHashV2 *vh2 = &ss2.GetState();
3b500530 1631 u128 *hashKey;
1632 verusclhasher &vclh = vh2->vclh;
fa7fdbc6 1633 minefunction mine_verus;
1634 mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;
f21fad6a 1635
42181656 1636 while (true)
1637 {
4dcb64c0 1638 uint256 hashResult = uint256();
458bfcab 1639
e5fb645e 1640 unsigned char *curBuf;
1641
f8f61a6d 1642 if (mergeMining)
42181656 1643 {
c89d86ee 1644 // loop for a few minutes before refreshing the block
e771a884 1645 while (true)
12217420 1646 {
a1d91f89 1647 if ( pindexPrev != chainActive.LastTip() )
1648 {
1649 if (lastChainTipPrinted != chainActive.LastTip())
1650 {
1651 lastChainTipPrinted = chainActive.LastTip();
1652 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
1653 arith_uint256 target;
1654 target.SetCompact(lastChainTipPrinted->nBits);
1655 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());
1656 printf("Found block %d \n", Mining_height );
1657 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1658 printf(" hash: %s\ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());
1659 }
1660 break;
1661 }
1662
e771a884 1663 // if PBaaS is no longer available, we can't count on merge mining
1664 if (!ConnectedChains.IsVerusPBaaSAvailable())
1665 {
1666 break;
1667 }
f8f61a6d 1668
1669 if (vNodes.empty() && chainparams.MiningRequiresPeers())
458bfcab 1670 {
f8f61a6d 1671 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
fa7fdbc6 1672 {
f8f61a6d 1673 fprintf(stderr,"no nodes, attempting reconnect\n");
1674 break;
fa7fdbc6 1675 }
f8f61a6d 1676 }
1677
a82942e4 1678 // update every few minutes, regardless
1679 int64_t elapsed = GetTime() - nStart;
f8f61a6d 1680
be17c611 1681 if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 120 || ConnectedChains.lastSubmissionFailed)
458bfcab 1682 {
be17c611 1683
f8f61a6d 1684 break;
458bfcab 1685 }
a1d91f89 1686
dc74c06d 1687 boost::this_thread::interruption_point();
a1d91f89 1688 MilliSleep(500);
458bfcab 1689 }
ffde1589 1690 break;
f8f61a6d 1691 }
1692 else
1693 {
1694 // check NONCEMASK at a time
1695 for (uint64_t i = 0; i < count; i++)
42181656 1696 {
2fd1f0fb 1697 // this is the actual mining loop, which enables us to drop out and queue a header anytime we earn a block that is good enough for a
f8f61a6d 1698 // merge mined block, but not our own
f8f61a6d 1699 bool blockFound;
1700 arith_uint256 arithHash;
2830db29 1701 totalDone = 0;
f8f61a6d 1702 do
1703 {
2fd1f0fb 1704 // pickup/remove any new/deleted headers
1705 if (ConnectedChains.dirty)
1706 {
1707 if (!(savebits = ConnectedChains.CombineBlocks(*pblock)))
1708 {
1709 savebits = pblock->nBits;
1710 }
1711 hashTarget.SetCompact(savebits);
1712 uintTarget = ArithToUint256(hashTarget);
1713 }
1714
f8f61a6d 1715 // hashesToGo gets updated with actual number run for metrics
1716 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
2830db29 1717 uint64_t start = i * hashesToGo + totalDone;
f8f61a6d 1718 hashesToGo -= totalDone;
1719
1720 if (verusSolutionV3)
1721 {
1722 // mine on canonical header for merge mining
1723 CPBaaSPreHeader savedHeader(*pblock);
1724 pblock->ClearNonCanonicalData();
1725 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
1726 savedHeader.SetBlockData(*pblock);
1727 }
1728 else
1729 {
1730 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
1731 }
1732
1733 arithHash = UintToArith256(hashResult);
249e20e4 1734 totalDone += hashesToGo + 1;
f8f61a6d 1735 if (blockFound && IsVerusActive())
1736 {
1737 ConnectedChains.QueueNewBlockHeader(*pblock);
1738 if (arithHash > ourTarget)
1739 {
1740 // all blocks qualified with this hash will be submitted
1741 // until we redo the block, we might as well not try again with anything over this hash
1742 hashTarget = arithHash;
1743 uintTarget = ArithToUint256(hashTarget);
1744 }
1745 }
2fd1f0fb 1746 } while (blockFound && arithHash > ourTarget);
c98efb5a 1747
f8f61a6d 1748 if (!blockFound || arithHash > ourTarget)
4dcb64c0 1749 {
f8f61a6d 1750 // Check for stop or if block needs to be rebuilt
1751 boost::this_thread::interruption_point();
ce40cf2e 1752 if ( pindexPrev != chainActive.LastTip() )
f8f61a6d 1753 {
1754 if (lastChainTipPrinted != chainActive.LastTip())
1755 {
1756 lastChainTipPrinted = chainActive.LastTip();
1757 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1758 }
1759 break;
1760 }
a1d91f89 1761 else if ((i + 1) < count)
f8f61a6d 1762 {
a1d91f89 1763 // if we'll not drop through, update hashcount
f8f61a6d 1764 {
1765 LOCK(cs_metrics);
2830db29 1766 nHashCount += totalDone;
1767 totalDone = 0;
f8f61a6d 1768 }
f8f61a6d 1769 }
4dcb64c0 1770 }
f8f61a6d 1771 else
1772 {
1773 // Check for stop or if block needs to be rebuilt
1774 boost::this_thread::interruption_point();
4dcb64c0 1775
f8f61a6d 1776 if (pblock->nSolution.size() != 1344)
1777 {
1778 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1779 break;
1780 }
42181656 1781
f8f61a6d 1782 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1783
1784 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
ef70c5b2 1785
3363d1c0 1786#ifdef VERUSHASHDEBUG
f8f61a6d 1787 std::string validateStr = hashResult.GetHex();
1788 std::string hashStr = pblock->GetHash().GetHex();
1789 uint256 *bhalf1 = (uint256 *)vh2->CurBuffer();
1790 uint256 *bhalf2 = bhalf1 + 1;
3363d1c0 1791#else
f8f61a6d 1792 std::string hashStr = hashResult.GetHex();
3363d1c0 1793#endif
3af22e67 1794
f8f61a6d 1795 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1796 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex());
1797 printf("Found block %d \n", Mining_height );
1798 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
3363d1c0 1799#ifdef VERUSHASHDEBUG
f8f61a6d 1800 printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
1801 printf("intermediate %lx\n", intermediate);
1802 printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
1803 bhalf1 = (uint256 *)verusclhasher_key.get();
1804 bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5);
1805 printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
3363d1c0 1806#else
f8f61a6d 1807 printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
3363d1c0 1808#endif
f8f61a6d 1809 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1810 printf(" - timelocked until block %i\n", unlockTime);
1811 else
1812 printf("\n");
42181656 1813#ifdef ENABLE_WALLET
f8f61a6d 1814 ProcessBlockFound(pblock, *pwallet, reservekey);
42181656 1815#else
f8f61a6d 1816 ProcessBlockFound(pblock);
42181656 1817#endif
f8f61a6d 1818 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1819 break;
1820 }
42181656 1821 }
42181656 1822
f8f61a6d 1823 {
1824 LOCK(cs_metrics);
2830db29 1825 nHashCount += totalDone;
f8f61a6d 1826 }
69767347 1827 }
f8f61a6d 1828
69767347 1829
42181656 1830 // Check for stop or if block needs to be rebuilt
1831 boost::this_thread::interruption_point();
1832
1833 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1834 {
1835 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1836 {
ef70c5b2 1837 fprintf(stderr,"no nodes, attempting reconnect\n");
42181656 1838 break;
1839 }
1840 }
1841
dbe656fe 1842 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
42181656 1843 {
dbe656fe 1844 fprintf(stderr,"timeout, retrying\n");
42181656 1845 break;
1846 }
1847
37ad6886 1848 if ( pindexPrev != chainActive.LastTip() )
42181656 1849 {
37ad6886 1850 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1851 {
37ad6886 1852 lastChainTipPrinted = chainActive.LastTip();
90198f71 1853 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
dbe656fe 1854 }
42181656 1855 break;
1856 }
1857
2830db29 1858 // totalDone now has the number of hashes actually done since starting on one nonce mask worth
ce40cf2e 1859 uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3;
2830db29 1860 if (!(totalDone < hashesPerNonceMask))
ce40cf2e 1861 {
52cf66e1 1862#ifdef _WIN32
ce40cf2e 1863 printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
52cf66e1 1864#else
ce40cf2e 1865 printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
52cf66e1 1866#endif
ce40cf2e 1867 }
4dcb64c0 1868 break;
8682e17a 1869
42181656 1870 }
1871 }
1872 }
1873 catch (const boost::thread_interrupted&)
1874 {
1875 miningTimer.stop();
5034d1c1 1876 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1877 throw;
1878 }
1879 catch (const std::runtime_error &e)
1880 {
1881 miningTimer.stop();
5034d1c1 1882 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
42181656 1883 return;
1884 }
1885 miningTimer.stop();
1886}
1887
8e8b6d70 1888#ifdef ENABLE_WALLET
d247a5d1 1889void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
1890#else
1891void static BitcoinMiner()
1892#endif
d247a5d1 1893{
2e500f50 1894 LogPrintf("KomodoMiner started\n");
d247a5d1 1895 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 1896 RenameThread("komodo-miner");
bebe7282 1897 const CChainParams& chainparams = Params();
e9e70b95 1898
8e8b6d70
JG
1899#ifdef ENABLE_WALLET
1900 // Each thread has its own key
d247a5d1 1901 CReserveKey reservekey(pwallet);
8e8b6d70 1902#endif
e9e70b95 1903
8e8b6d70 1904 // Each thread has its own counter
d247a5d1 1905 unsigned int nExtraNonce = 0;
e9e70b95 1906
e9574728
JG
1907 unsigned int n = chainparams.EquihashN();
1908 unsigned int k = chainparams.EquihashK();
16593898 1909 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
99ba67a0 1910 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
755ead98 1911 {
1912 sleep(1);
4e624c04 1913 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1914 break;
755ead98 1915 }
32b0978b 1916 if ( ASSETCHAINS_SYMBOL[0] == 0 )
4b729ec5 1917 komodo_chosennotary(&notaryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
28a62b60 1918 if ( notaryid != My_notaryid )
1919 My_notaryid = notaryid;
755ead98 1920 std::string solver;
e1e65cef 1921 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
e9e70b95 1922 solver = "tromp";
e1e65cef 1923 //else solver = "default";
5f0009b2 1924 assert(solver == "tromp" || solver == "default");
c7aaab7a 1925 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 1926 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 1927 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
1928 std::mutex m_cs;
1929 bool cancelSolver = false;
1930 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
e9e70b95 1931 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1932 std::lock_guard<std::mutex> lock{m_cs};
1933 cancelSolver = true;
1934 }
1935 );
07be8f7e 1936 miningTimer.start();
e9e70b95 1937
0655fac0 1938 try {
ad84148d 1939 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 1940 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 1941 while (true)
1942 {
4b729ec5 1943 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
e725f1cb 1944 {
4b729ec5 1945 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
a96fd7b5 1946 // break;
0655fac0
PK
1947 // Busy-wait for the network to come online so we don't waste time mining
1948 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 1949 miningTimer.stop();
bba7c249
GM
1950 do {
1951 bool fvNodesEmpty;
1952 {
373668be 1953 //LOCK(cs_vNodes);
bba7c249
GM
1954 fvNodesEmpty = vNodes.empty();
1955 }
269fe243 1956 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 1957 break;
6e78d3df 1958 MilliSleep(15000);
ad84148d 1959 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
e9e70b95 1960
bba7c249 1961 } while (true);
ad84148d 1962 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 1963 miningTimer.start();
0655fac0 1964 }
0655fac0
PK
1965 //
1966 // Create new block
1967 //
1968 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
86131275 1969 CBlockIndex* pindexPrev = chainActive.LastTip();
4b729ec5 1970 if ( Mining_height != pindexPrev->GetHeight()+1 )
4940066c 1971 {
4b729ec5 1972 Mining_height = pindexPrev->GetHeight()+1;
4940066c 1973 Mining_start = (uint32_t)time(NULL);
1974 }
8e9ef91c 1975 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 1976 {
40304479 1977 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
5a7fd132 1978 //sleep(3);
2825c0b5 1979 }
135fa24e 1980
8e8b6d70 1981#ifdef ENABLE_WALLET
135fa24e 1982 // notaries always default to staking
4b729ec5 1983 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
8e8b6d70 1984#else
945f015d 1985 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 1986#endif
08d0b73c 1987 if ( ptr == 0 )
1988 {
d0f7ead0 1989 static uint32_t counter;
5bb3d0fe 1990 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 1991 fprintf(stderr,"created illegal block, retry\n");
8fc79ac9 1992 sleep(1);
d0f7ead0 1993 continue;
08d0b73c 1994 }
2a6a442a 1995 //fprintf(stderr,"get template\n");
08d0b73c 1996 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 1997 if (!pblocktemplate.get())
6c37f7fd 1998 {
8e8b6d70 1999 if (GetArg("-mineraddress", "").empty()) {
945f015d 2000 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
2001 } else {
2002 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 2003 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 2004 }
0655fac0 2005 return;
6c37f7fd 2006 }
0655fac0 2007 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 2008 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2009 {
42181656 2010 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
16c7bf6b 2011 {
8683bd8d 2012 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
2013 {
2014 static uint32_t counter;
2015 if ( counter++ < 10 )
2016 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
2017 sleep(10);
2018 continue;
2019 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
2020 }
16c7bf6b 2021 }
0655fac0 2022 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2a6a442a 2023 //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
2e500f50 2024 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
2025 //
2026 // Search
2027 //
2ba9de01 2028 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 2029 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
404391b5 2030 savebits = pblock->nBits;
d5614a76 2031 HASHTarget = arith_uint256().SetCompact(savebits);
f0100e72 2032 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 2033 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 2034 {
fda5f849 2035 j = 65;
67df454d 2036 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
fb6c7505 2037 {
4fff8a63 2038 int32_t dispflag = 0;
ef70c5b2 2039 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
4fff8a63 2040 dispflag = 1;
4b729ec5 2041 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
29e60e48 2042 if ( nonzpkeys > 0 )
2043 {
ccb71a6e 2044 for (i=0; i<33; i++)
2045 if( pubkeys[0][i] != 0 )
2046 break;
2047 if ( i == 33 )
2048 externalflag = 1;
2049 else externalflag = 0;
4d068367 2050 if ( IS_KOMODO_NOTARY != 0 )
b176c125 2051 {
345e545e 2052 for (i=1; i<66; i++)
2053 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
2054 break;
6494f040 2055 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
2056 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
2c7ad758 2057 for (j=gpucount=0; j<65; j++)
2058 {
4fff8a63 2059 if ( dispflag != 0 )
e4a383e3 2060 {
2061 if ( mids[j] >= 0 )
2062 fprintf(stderr,"%d ",mids[j]);
2063 else fprintf(stderr,"GPU ");
2064 }
2c7ad758 2065 if ( mids[j] == -1 )
2066 gpucount++;
2067 }
4fff8a63 2068 if ( dispflag != 0 )
4b729ec5 2069 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 2070 }
29e60e48 2071 for (j=0; j<65; j++)
2072 if ( mids[j] == notaryid )
2073 break;
49b49585 2074 if ( j == 65 )
2075 KOMODO_LASTMINED = 0;
965f0f7e 2076 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 2077 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 2078 {
88287857 2079 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
4b729ec5 2080 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
fda5f849 2081 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 2082 } else Mining_start = 0;
d7d27bb3 2083 } else Mining_start = 0;
2ba9de01 2084 if ( ASSETCHAINS_STAKED != 0 )
e725f1cb 2085 {
ed3d0a05 2086 int32_t percPoS,z; bool fNegative,fOverflow;
18443f69 2087 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
f108acf9 2088 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
f2c1ac06 2089 if ( ASSETCHAINS_STAKED < 100 )
2090 {
2091 for (z=31; z>=0; z--)
2092 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
2093 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
2094 }
deba7f20 2095 }
e725f1cb 2096 while (true)
2097 {
99ba67a0 2098 if ( KOMODO_INSYNC == 0 )
2099 {
e9d56b2c 2100 fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
2101 if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
a02c45db 2102 KOMODO_INSYNC = 1;
99ba67a0 2103 sleep(3);
2104 }
7213c0b1 2105 // Hash state
8c22eb46 2106 KOMODO_CHOSEN_ONE = 0;
42181656 2107
7213c0b1 2108 crypto_generichash_blake2b_state state;
e9574728 2109 EhInitialiseState(n, k, state);
7213c0b1
JG
2110 // I = the block header minus nonce and solution.
2111 CEquihashInput I{*pblock};
2112 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2113 ss << I;
7213c0b1
JG
2114 // H(I||...
2115 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
2116 // H(I||V||...
2117 crypto_generichash_blake2b_state curr_state;
2118 curr_state = state;
7a4c01c9 2119 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 2120 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 2121 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
18443f69 2122 arith_uint256 hashTarget;
6e78d3df 2123 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
18443f69 2124 hashTarget = HASHTarget_POW;
2125 else hashTarget = HASHTarget;
5be6abbf 2126 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 2127#ifdef ENABLE_WALLET
e9e70b95 2128 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 2129#else
e9e70b95 2130 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 2131#endif
e9e70b95 2132 (std::vector<unsigned char> soln) {
c21c6306 2133 int32_t z; arith_uint256 h; CBlock B;
51eb5273
JG
2134 // Write the solution to the hash and compute the result.
2135 LogPrint("pow", "- Checking solution against target\n");
8e165d57 2136 pblock->nSolution = soln;
e7d59bbc 2137 solutionTargetChecks.increment();
eff2c3a3 2138 B = *pblock;
2139 h = UintToArith256(B.GetHash());
eff2c3a3 2140 /*for (z=31; z>=16; z--)
02c30aac 2141 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
aea2d1aa 2142 fprintf(stderr," mined ");
2143 for (z=31; z>=16; z--)
18443f69 2144 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
aea2d1aa 2145 fprintf(stderr," hashTarget ");
2146 for (z=31; z>=16; z--)
18443f69 2147 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
eff2c3a3 2148 fprintf(stderr," POW\n");*/
265f4e96 2149 if ( h > hashTarget )
40df8d84 2150 {
6e78d3df 2151 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
afa90f17 2152 // sleep(1);
265f4e96 2153 return false;
40df8d84 2154 }
41e9c815 2155 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
d7d27bb3 2156 {
45ee62cb 2157 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
596b05ba 2158 while ( GetAdjustedTime() < B.nTime-2 )
8e9ef91c 2159 {
eb1ba5a0 2160 sleep(1);
4b729ec5 2161 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
4cc387ec 2162 {
2163 fprintf(stderr,"new block arrived\n");
2164 return(false);
2165 }
8e9ef91c 2166 }
eb1ba5a0 2167 }
8e9ef91c 2168 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 2169 {
4d068367 2170 if ( IS_KOMODO_NOTARY != 0 )
8e9ef91c 2171 {
26810a26 2172 int32_t r;
9703f8a0 2173 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
596b05ba 2174 MilliSleep((rand() % (r * 1000)) + 1000);
ef70c5b2 2175 }
e5430f52 2176 }
8e9ef91c 2177 else
d7d27bb3 2178 {
0c35569b 2179 while ( B.nTime-57 > GetAdjustedTime() )
deba7f20 2180 {
afa90f17 2181 sleep(1);
4b729ec5 2182 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
afa90f17 2183 return(false);
68d0354d 2184 }
4d068367 2185 uint256 tmp = B.GetHash();
2186 int32_t z; for (z=31; z>=0; z--)
2187 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
01e50e73 2188 fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
d7d27bb3 2189 }
8fc79ac9 2190 CValidationState state;
86131275 2191 if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
d2d3c766 2192 {
8fc79ac9 2193 h = UintToArith256(B.GetHash());
2194 for (z=31; z>=0; z--)
2195 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
2196 fprintf(stderr," Invalid block mined, try again\n");
2197 return(false);
d2d3c766 2198 }
b3183e3e 2199 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
2200 // Found a solution
2201 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 2202 LogPrintf("KomodoMiner:\n");
eff2c3a3 2203 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 2204#ifdef ENABLE_WALLET
eff2c3a3 2205 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
8e8b6d70 2206#else
eff2c3a3 2207 if (ProcessBlockFound(&B)) {
8e8b6d70 2208#endif
e9e70b95 2209 // Ignore chain updates caused by us
2210 std::lock_guard<std::mutex> lock{m_cs};
2211 cancelSolver = false;
2212 }
2213 KOMODO_CHOSEN_ONE = 0;
2214 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2215 // In regression test mode, stop mining after a block is found.
2216 if (chainparams.MineBlocksOnDemand()) {
2217 // Increment here because throwing skips the call below
2218 ehSolverRuns.increment();
2219 throw boost::thread_interrupted();
2220 }
e9e70b95 2221 return true;
2222 };
2223 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
a6a0d913 2224 std::lock_guard<std::mutex> lock{m_cs};
e9e70b95 2225 return cancelSolver;
2226 };
2227
2228 // TODO: factor this out into a function with the same API for each solver.
2229 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
2230 // Create solver and initialize it.
2231 equi eq(1);
2232 eq.setstate(&curr_state);
2233
2234 // Initialization done, start algo driver.
2235 eq.digit0(0);
c7aaab7a 2236 eq.xfull = eq.bfull = eq.hfull = 0;
e9e70b95 2237 eq.showbsizes(0);
2238 for (u32 r = 1; r < WK; r++) {
2239 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
2240 eq.xfull = eq.bfull = eq.hfull = 0;
2241 eq.showbsizes(r);
c7aaab7a 2242 }
e9e70b95 2243 eq.digitK(0);
2244 ehSolverRuns.increment();
2245
2246 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
2247 for (size_t s = 0; s < eq.nsols; s++) {
2248 LogPrint("pow", "Checking solution %d\n", s+1);
2249 std::vector<eh_index> index_vector(PROOFSIZE);
2250 for (size_t i = 0; i < PROOFSIZE; i++) {
2251 index_vector[i] = eq.sols[s][i];
2252 }
2253 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
2254
2255 if (validBlock(sol_char)) {
2256 // If we find a POW solution, do not try other solutions
2257 // because they become invalid as we created a new block in blockchain.
2258 break;
2259 }
2260 }
2261 } else {
2262 try {
2263 // If we find a valid block, we rebuild
2264 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
2265 ehSolverRuns.increment();
2266 if (found) {
997ddd92 2267 int32_t i; uint256 hash = pblock->GetHash();
e9e70b95 2268 for (i=0; i<32; i++)
2269 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
2270 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
2271 FOUND_BLOCK = 1;
2272 KOMODO_MAYBEMINED = Mining_height;
2273 break;
2274 }
2275 } catch (EhSolverCancelledException&) {
2276 LogPrint("pow", "Equihash solver cancelled\n");
2277 std::lock_guard<std::mutex> lock{m_cs};
2278 cancelSolver = false;
c7aaab7a
DH
2279 }
2280 }
e9e70b95 2281
2282 // Check for stop or if block needs to be rebuilt
2283 boost::this_thread::interruption_point();
2284 // Regtest mode doesn't require peers
2285 if ( FOUND_BLOCK != 0 )
2286 {
2287 FOUND_BLOCK = 0;
2288 fprintf(stderr,"FOUND_BLOCK!\n");
2289 //sleep(2000);
2290 }
2291 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2292 {
2293 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
2294 {
2295 fprintf(stderr,"no nodes, break\n");
c7aaab7a 2296 break;
a6df7ab5 2297 }
c7aaab7a 2298 }
997ddd92 2299 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
10694486 2300 {
e9e70b95 2301 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2302 fprintf(stderr,"0xffff, break\n");
d90cef0b 2303 break;
10694486 2304 }
e9e70b95 2305 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2306 {
2307 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2308 fprintf(stderr,"timeout, break\n");
2309 break;
2310 }
86131275 2311 if ( pindexPrev != chainActive.LastTip() )
e9e70b95 2312 {
2313 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2314 fprintf(stderr,"Tip advanced, break\n");
2315 break;
2316 }
2317 // Update nNonce and nTime
2318 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
2319 pblock->nBits = savebits;
18dd6a3b 2320 /*if ( NOTARY_PUBKEY33[0] == 0 )
e9e70b95 2321 {
f8f740a9 2322 int32_t percPoS;
df756d24
MT
2323 UpdateTime(pblock, consensusParams, pindexPrev);
2324 if (consensusParams.fPowAllowMinDifficultyBlocks)
23fc88bb 2325 {
2326 // Changing pblock->nTime can change work required on testnet:
2327 HASHTarget.SetCompact(pblock->nBits);
18443f69 2328 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
23fc88bb 2329 }
18dd6a3b 2330 }*/
48265f3c 2331 }
d247a5d1
JG
2332 }
2333 }
e9e70b95 2334 catch (const boost::thread_interrupted&)
2335 {
2336 miningTimer.stop();
2337 c.disconnect();
2338 LogPrintf("KomodoMiner terminated\n");
2339 throw;
2340 }
2341 catch (const std::runtime_error &e)
2342 {
2343 miningTimer.stop();
2344 c.disconnect();
2345 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
2346 return;
2347 }
07be8f7e 2348 miningTimer.stop();
5e9b555f 2349 c.disconnect();
bba7c249 2350 }
e9e70b95 2351
8e8b6d70 2352#ifdef ENABLE_WALLET
e9e70b95 2353 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70 2354#else
e9e70b95 2355 void GenerateBitcoins(bool fGenerate, int nThreads)
8e8b6d70 2356#endif
d247a5d1 2357 {
f8f61a6d 2358 if (!AreParamsInitialized())
2359 {
2360 return;
2361 }
2362
10214558 2363 // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
2364 // initialization, and this is the first time we can get it. store the Sapling address here
2365 extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
2366 extern std::string VERUS_CHEATCATCHER;
2367 libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);
2368 if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))
2369 {
99c94fc3 2370 try
2371 {
2372 cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
2373 }
2374 catch (...)
2375 {
2376 }
10214558 2377 }
bd6639fd 2378
b20c38cc 2379 VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);
bd6639fd 2380
89cd7b59 2381 if (fGenerate == true || VERUS_MINTBLOCKS)
10214558 2382 {
89cd7b59
MT
2383 mapArgs["-gen"] = "1";
2384
2385 if (VERUS_CHEATCATCHER.size() > 0)
99c94fc3 2386 {
89cd7b59
MT
2387 if (cheatCatcher == boost::none)
2388 {
2389 LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n");
2390 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
2391 }
2392 else
2393 {
2394 LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
2395 fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
2396 }
99c94fc3 2397 }
2398 }
10214558 2399
e9e70b95 2400 static boost::thread_group* minerThreads = NULL;
28424e9f 2401
e9e70b95 2402 if (nThreads < 0)
2403 nThreads = GetNumCores();
2404
2405 if (minerThreads != NULL)
2406 {
2407 minerThreads->interrupt_all();
2408 delete minerThreads;
2409 minerThreads = NULL;
2410 }
135fa24e 2411
afaeb54b 2412 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
5034d1c1 2413 if ( nThreads == 0 && ASSETCHAINS_STAKED )
3a446d9f 2414 nThreads = 1;
5034d1c1 2415
28424e9f 2416 if (!fGenerate)
e9e70b95 2417 return;
135fa24e 2418
e9e70b95 2419 minerThreads = new boost::thread_group();
135fa24e 2420
85c51d62 2421 // add the PBaaS thread when mining or staking
2422 minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub));
2423
135fa24e 2424#ifdef ENABLE_WALLET
b20c38cc 2425 if (VERUS_MINTBLOCKS && pwallet != NULL)
135fa24e 2426 {
2427 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
2428 }
2429#endif
2430
e9e70b95 2431 for (int i = 0; i < nThreads; i++) {
135fa24e 2432
8e8b6d70 2433#ifdef ENABLE_WALLET
135fa24e 2434 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2435 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
2436 else
2437 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
8e8b6d70 2438#else
135fa24e 2439 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2440 minerThreads->create_thread(&BitcoinMiner);
2441 else
2442 minerThreads->create_thread(&BitcoinMiner_noeq);
8e8b6d70 2443#endif
e9e70b95 2444 }
8e8b6d70 2445 }
e9e70b95 2446
2cc0a252 2447#endif // ENABLE_MINING
This page took 0.928362 seconds and 4 git commands to generate.