]> Git Repo - VerusCoin.git/blame - src/miner.cpp
improve merge mining display
[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
dbe656fe
MT
1440 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1441 // and print duplicates rarely without having to synchronize
1442 static CBlockIndex *lastChainTipPrinted;
90198f71 1443 static int32_t lastMiningHeight = 0;
9f3e2213 1444
42181656 1445 miningTimer.start();
1446
1447 try {
dbe656fe 1448 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
08d46b7f 1449
08d46b7f 1450 // v2 hash writer
1451 CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION);
1452
42181656 1453 while (true)
1454 {
68334c8d 1455 miningTimer.stop();
1456 waitForPeers(chainparams);
dfcf8255 1457
37ad6886 1458 pindexPrev = chainActive.LastTip();
dfcf8255 1459
f8f61a6d 1460 // prevent forking on startup before the diff algorithm kicks in,
1461 // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from
1462 // their parent
57055854 1463 if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip()))
dfcf8255
MT
1464 {
1465 do {
37ad6886 1466 pindexPrev = chainActive.LastTip();
2830db29 1467 MilliSleep(2000 + rand() % 2000);
37ad6886 1468 } while (pindexPrev != chainActive.LastTip());
dfcf8255 1469 }
42181656 1470
1471 // Create new block
1472 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
4b729ec5 1473 if ( Mining_height != pindexPrev->GetHeight()+1 )
42181656 1474 {
4b729ec5 1475 Mining_height = pindexPrev->GetHeight()+1;
90198f71 1476 if (lastMiningHeight != Mining_height)
1477 {
1478 lastMiningHeight = Mining_height;
1479 printf("Mining height %d\n", Mining_height);
1480 }
42181656 1481 Mining_start = (uint32_t)time(NULL);
1482 }
1483
dbe656fe 1484 miningTimer.start();
42181656 1485
1486#ifdef ENABLE_WALLET
5034d1c1 1487 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
42181656 1488#else
1489 CBlockTemplate *ptr = CreateNewBlockWithKey();
1490#endif
1491 if ( ptr == 0 )
1492 {
1493 static uint32_t counter;
bab13dd2 1494 if ( (counter++ < 10) || (counter % 40 == 0) )
1495 fprintf(stderr,"Unable to create valid block... will continue to try\n");
2830db29 1496 MilliSleep(2000);
42181656 1497 continue;
1498 }
dbe656fe 1499
42181656 1500 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1501 if (!pblocktemplate.get())
1502 {
1503 if (GetArg("-mineraddress", "").empty()) {
05f6e633 1504 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1505 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1506 } else {
1507 // Should never reach here, because -mineraddress validity is checked in init.cpp
05f6e633 1508 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
42181656 1509 }
1510 return;
1511 }
1512 CBlock *pblock = &pblocktemplate->block;
f8f61a6d 1513
1514 uint32_t savebits;
1515 bool mergeMining = false;
1516 savebits = pblock->nBits;
1517
1518 bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2;
1519 bool verusSolutionV3 = CConstVerusSolutionVector::Version(pblock->nSolution) == CActivationHeight::SOLUTION_VERUSV3;
1520
42181656 1521 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1522 {
1523 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1524 {
1525 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1526 {
1527 static uint32_t counter;
1528 if ( counter++ < 10 )
1529 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1530 sleep(10);
1531 continue;
1532 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1533 }
1534 }
b2a98c42
MT
1535
1536 // this builds the Merkle tree
42181656 1537 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
b2a98c42
MT
1538
1539 // update PBaaS header
f8f61a6d 1540 if (verusSolutionV3)
b2a98c42 1541 {
b2a98c42
MT
1542 uint256 mmvRoot;
1543 {
1544 LOCK(cs_main);
f8f61a6d 1545 ChainMerkleMountainView mmv = chainActive.GetMMV();
b2a98c42 1546 mmvRoot = mmv.GetRoot();
f8f61a6d 1547 }
1548 pblock->AddUpdatePBaaSHeader(mmvRoot);
1549
1550 if (IsVerusActive())
1551 {
1552 // combine all merge mined headers into this header
1553 // and get the easiest target of all chains in savebits
1554 if (!(savebits = ConnectedChains.CombineBlocks(*pblock)))
1555 {
1556 savebits = pblock->nBits;
1557 }
b2a98c42 1558
f8f61a6d 1559 LOCK(cs_main);
1560 // TODO: REMOVE OR COMMENT TESTS
b2a98c42 1561 // tests to validate a few transactions and all past blocks
f8f61a6d 1562 ChainMerkleMountainView mmv = chainActive.GetMMV();
1563 mmvRoot = mmv.GetRoot();
b2a98c42
MT
1564 for (uint32_t i = 1; i <= pindexPrev->GetHeight(); i += 10)
1565 {
1566 CBlockIndex *pindex = chainActive[i - 1];
1567 mmv.resize(i);
1568 uint256 testRoot = mmv.GetRoot();
1569 uint32_t testHeight = ((unsigned char *)&testRoot)[0] < i ? (i - ((unsigned char *)&testRoot)[0]) - 1 : i - 1;
1570 CMerkleBranch branchMerkle, branchBlock;
1571 chainActive.GetBlockProof(mmv, branchBlock, testHeight);
1572 chainActive.GetMerkleProof(mmv, branchMerkle, testHeight);
1573 uint256 merkleAnswer = branchMerkle.SafeCheck(chainActive[testHeight]->hashMerkleRoot);
1574 uint256 blockAnswer = branchBlock.SafeCheck(chainActive[testHeight]->GetBlockHash());
1575 if (merkleAnswer != testRoot)
1576 {
1577 printf("Failed merkle proof at testheight: %u\nexpected: %s\ncalculated: %s\n", testHeight, testRoot.GetHex().c_str(), merkleAnswer.GetHex().c_str());
1578 printf("Bits for left (0) and right (1): \n");
1579 std::vector<unsigned char> proofBits = ChainMerkleMountainView::GetProofBits(testHeight, i);
1580 printf("right\n");
1581 for (auto bit : proofBits)
1582 {
1583 printf("%s\n", bit ? "left" : "right");
1584 }
1585 }
1586 if (blockAnswer != testRoot)
1587 {
1588 printf("Failed block proof at testheight: %u\nexpected: %s\ncalculated: %s\n", testHeight, testRoot.GetHex().c_str(), blockAnswer.GetHex().c_str());
1589 printf("Bits for left (0) and right (1): \n");
1590 std::vector<unsigned char> proofBits = ChainMerkleMountainView::GetProofBits(testHeight, i);
1591 printf("left\n");
1592 for (auto bit : proofBits)
1593 {
1594 printf("%s\n", bit ? "left" : "right");
1595 }
1596 }
1597 const CMMRPowerNode *ppower = mmv.GetRootNode();
1598 if (!ppower || ppower->Work() != pindex->chainPower.chainWork)
1599 {
1600 printf("Work did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainWork).GetHex().c_str(), ArithToUint256(ppower->Work()).GetHex().c_str());
1601 }
1602 if (!ppower || ppower->Stake() != pindex->chainPower.chainStake)
1603 {
1604 printf("Stake did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainStake).GetHex().c_str(), ArithToUint256(ppower->Stake()).GetHex().c_str());
1605 }
1606 }
f8f61a6d 1607 // END TESTS
1608 }
1609 else
1610 {
1611 // submit the block for merge mining if Verus is present
1612 // otherwise, mine solo
1613 if (ConnectedChains.IsVerusPBaaSAvailable())
1614 {
1615
1616 UniValue params(UniValue::VARR);
7af5cf39 1617 UniValue error(UniValue::VARR);
f8f61a6d 1618 params.push_back(EncodeHexBlk(*pblock));
1619 params.push_back(ASSETCHAINS_SYMBOL);
7af5cf39 1620 params.push_back(ASSETCHAINS_RPCHOST);
1621 params.push_back(ASSETCHAINS_RPCPORT);
1622 params.push_back(ASSETCHAINS_RPCCREDENTIALS);
9a891caf 1623 try
1624 {
7af5cf39 1625 params = RPCCallRoot("addmergedblock", params);
1626 params = find_value(params, "result");
1627 error = find_value(params, "error");
9a891caf 1628 } catch (std::exception e)
1629 {
1630 printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
1631 params = UniValue(e.what());
1632 }
7af5cf39 1633 if (mergeMining = (params.isNull() && error.isNull()))
f8f61a6d 1634 {
a82942e4 1635 printf("Merge mining with %s as the actual mining chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
1636 LogPrintf("Merge mining with %s\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
f8f61a6d 1637 }
1638 }
b2a98c42
MT
1639 }
1640 }
1641
42181656 1642 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1643 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1644 //
1645 // Search
1646 //
f8f61a6d 1647 int64_t nStart = GetTime();
42181656 1648
f8f61a6d 1649 arith_uint256 hashTarget = arith_uint256().SetCompact(savebits);
fa7fdbc6 1650 uint256 uintTarget = ArithToUint256(hashTarget);
f8f61a6d 1651
1652 arith_uint256 ourTarget;
1653 ourTarget.SetCompact(pblock->nBits);
1654
42181656 1655 Mining_start = 0;
ef70c5b2 1656
37ad6886 1657 if ( pindexPrev != chainActive.LastTip() )
05f6e633 1658 {
37ad6886 1659 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1660 {
37ad6886 1661 lastChainTipPrinted = chainActive.LastTip();
4b729ec5 1662 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
dbe656fe 1663 }
f8f61a6d 1664 MilliSleep(100);
05f6e633 1665 continue;
1666 }
ef70c5b2 1667
135fa24e 1668 if ( ASSETCHAINS_STAKED != 0 )
1669 {
1670 int32_t percPoS,z;
1671 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1672 for (z=31; z>=0; z--)
1673 fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1674 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1675 }
1676
2830db29 1677 uint64_t count;
1678 uint64_t hashesToGo = 0;
1679 uint64_t totalDone = 0;
1680
fa7fdbc6 1681 if (!verusHashV2)
458bfcab 1682 {
fa7fdbc6 1683 // must not be in sync
1684 printf("Mining on incorrect block version.\n");
1685 sleep(2);
1686 continue;
458bfcab 1687 }
1688
2830db29 1689 int64_t subsidy = (int64_t)(pblock->vtx[0].GetValueOut());
fa7fdbc6 1690 count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
db027133 1691 CVerusHashV2 *vh2 = &ss2.GetState();
3b500530 1692 u128 *hashKey;
1693 verusclhasher &vclh = vh2->vclh;
fa7fdbc6 1694 minefunction mine_verus;
1695 mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;
f21fad6a 1696
42181656 1697 while (true)
1698 {
4dcb64c0 1699 uint256 hashResult = uint256();
458bfcab 1700
e5fb645e 1701 unsigned char *curBuf;
1702
f8f61a6d 1703 if (mergeMining)
42181656 1704 {
c89d86ee 1705 // loop for a few minutes before refreshing the block
e771a884 1706 while (true)
12217420 1707 {
e771a884 1708 // if PBaaS is no longer available, we can't count on merge mining
1709 if (!ConnectedChains.IsVerusPBaaSAvailable())
1710 {
1711 break;
1712 }
fa7fdbc6 1713 boost::this_thread::interruption_point();
a82942e4 1714 MilliSleep(1000);
f8f61a6d 1715
1716 if (vNodes.empty() && chainparams.MiningRequiresPeers())
458bfcab 1717 {
f8f61a6d 1718 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
fa7fdbc6 1719 {
f8f61a6d 1720 fprintf(stderr,"no nodes, attempting reconnect\n");
1721 break;
fa7fdbc6 1722 }
f8f61a6d 1723 }
1724
a82942e4 1725 // update every few minutes, regardless
1726 int64_t elapsed = GetTime() - nStart;
befe9235 1727 // this is accelerated for debugging, last check should be increased to at least 2 minutes
1728 if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60)
f8f61a6d 1729 {
fa7fdbc6 1730 break;
458bfcab 1731 }
f8f61a6d 1732
1733 if ( pindexPrev != chainActive.LastTip() )
458bfcab 1734 {
301cda74 1735 if (lastChainTipPrinted != chainActive.LastTip())
1736 {
1737 lastChainTipPrinted = chainActive.LastTip();
1738 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
1739 arith_uint256 target;
1740 target.SetCompact(lastChainTipPrinted->nBits);
1741 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex());
1742 printf("Found block %d \n", Mining_height );
1743 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
1744 }
f8f61a6d 1745 break;
458bfcab 1746 }
1747 }
ffde1589 1748 break;
f8f61a6d 1749 }
1750 else
1751 {
1752 // check NONCEMASK at a time
1753 for (uint64_t i = 0; i < count; i++)
42181656 1754 {
f8f61a6d 1755 // this is the merge mining loop, which enables us to drop out and queue a header anytime we earn a block that is good enough for a
1756 // merge mined block, but not our own
f8f61a6d 1757 bool blockFound;
1758 arith_uint256 arithHash;
2830db29 1759 totalDone = 0;
f8f61a6d 1760 do
1761 {
1762 // hashesToGo gets updated with actual number run for metrics
1763 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
2830db29 1764 uint64_t start = i * hashesToGo + totalDone;
f8f61a6d 1765 hashesToGo -= totalDone;
1766
1767 if (verusSolutionV3)
1768 {
1769 // mine on canonical header for merge mining
1770 CPBaaSPreHeader savedHeader(*pblock);
1771 pblock->ClearNonCanonicalData();
1772 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
1773 savedHeader.SetBlockData(*pblock);
1774 }
1775 else
1776 {
1777 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
1778 }
1779
1780 arithHash = UintToArith256(hashResult);
1781 totalDone += hashesToGo;
1782 if (blockFound && IsVerusActive())
1783 {
1784 ConnectedChains.QueueNewBlockHeader(*pblock);
1785 if (arithHash > ourTarget)
1786 {
1787 // all blocks qualified with this hash will be submitted
1788 // until we redo the block, we might as well not try again with anything over this hash
1789 hashTarget = arithHash;
1790 uintTarget = ArithToUint256(hashTarget);
1791 }
1792 }
f8f61a6d 1793 } while (blockFound && arithHash > ourTarget);
c98efb5a 1794
f8f61a6d 1795 if (!blockFound || arithHash > ourTarget)
4dcb64c0 1796 {
f8f61a6d 1797 // Check for stop or if block needs to be rebuilt
1798 boost::this_thread::interruption_point();
ce40cf2e 1799 if ( pindexPrev != chainActive.LastTip() )
f8f61a6d 1800 {
1801 if (lastChainTipPrinted != chainActive.LastTip())
1802 {
1803 lastChainTipPrinted = chainActive.LastTip();
1804 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
1805 }
1806 break;
1807 }
1808 else
1809 {
1810 {
1811 LOCK(cs_metrics);
2830db29 1812 nHashCount += totalDone;
1813 totalDone = 0;
f8f61a6d 1814 }
2830db29 1815 if (!ConnectedChains.dirty)
ce40cf2e 1816 {
1817 continue;
1818 }
f8f61a6d 1819 }
4dcb64c0 1820 }
f8f61a6d 1821 else
1822 {
1823 // Check for stop or if block needs to be rebuilt
1824 boost::this_thread::interruption_point();
4dcb64c0 1825
f8f61a6d 1826 if (pblock->nSolution.size() != 1344)
1827 {
1828 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
1829 break;
1830 }
42181656 1831
f8f61a6d 1832 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1833
1834 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
ef70c5b2 1835
3363d1c0 1836#ifdef VERUSHASHDEBUG
f8f61a6d 1837 std::string validateStr = hashResult.GetHex();
1838 std::string hashStr = pblock->GetHash().GetHex();
1839 uint256 *bhalf1 = (uint256 *)vh2->CurBuffer();
1840 uint256 *bhalf2 = bhalf1 + 1;
3363d1c0 1841#else
f8f61a6d 1842 std::string hashStr = hashResult.GetHex();
3363d1c0 1843#endif
3af22e67 1844
f8f61a6d 1845 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
1846 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex());
1847 printf("Found block %d \n", Mining_height );
1848 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
3363d1c0 1849#ifdef VERUSHASHDEBUG
f8f61a6d 1850 printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
1851 printf("intermediate %lx\n", intermediate);
1852 printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
1853 bhalf1 = (uint256 *)verusclhasher_key.get();
1854 bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5);
1855 printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
3363d1c0 1856#else
f8f61a6d 1857 printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
3363d1c0 1858#endif
f8f61a6d 1859 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1860 printf(" - timelocked until block %i\n", unlockTime);
1861 else
1862 printf("\n");
42181656 1863#ifdef ENABLE_WALLET
f8f61a6d 1864 ProcessBlockFound(pblock, *pwallet, reservekey);
42181656 1865#else
f8f61a6d 1866 ProcessBlockFound(pblock);
42181656 1867#endif
f8f61a6d 1868 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1869 break;
1870 }
42181656 1871 }
42181656 1872
f8f61a6d 1873 {
1874 LOCK(cs_metrics);
2830db29 1875 nHashCount += totalDone;
f8f61a6d 1876 }
69767347 1877 }
f8f61a6d 1878
69767347 1879
42181656 1880 // Check for stop or if block needs to be rebuilt
1881 boost::this_thread::interruption_point();
1882
1883 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1884 {
1885 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1886 {
ef70c5b2 1887 fprintf(stderr,"no nodes, attempting reconnect\n");
42181656 1888 break;
1889 }
1890 }
1891
dbe656fe 1892 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
42181656 1893 {
dbe656fe 1894 fprintf(stderr,"timeout, retrying\n");
42181656 1895 break;
1896 }
1897
37ad6886 1898 if ( pindexPrev != chainActive.LastTip() )
42181656 1899 {
37ad6886 1900 if (lastChainTipPrinted != chainActive.LastTip())
dbe656fe 1901 {
37ad6886 1902 lastChainTipPrinted = chainActive.LastTip();
90198f71 1903 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
dbe656fe 1904 }
42181656 1905 break;
1906 }
1907
2830db29 1908 // totalDone now has the number of hashes actually done since starting on one nonce mask worth
ce40cf2e 1909 uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3;
2830db29 1910 if (!(totalDone < hashesPerNonceMask))
ce40cf2e 1911 {
52cf66e1 1912#ifdef _WIN32
ce40cf2e 1913 printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
52cf66e1 1914#else
ce40cf2e 1915 printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
52cf66e1 1916#endif
ce40cf2e 1917 }
4dcb64c0 1918 break;
8682e17a 1919
42181656 1920 }
1921 }
1922 }
1923 catch (const boost::thread_interrupted&)
1924 {
1925 miningTimer.stop();
5034d1c1 1926 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1927 throw;
1928 }
1929 catch (const std::runtime_error &e)
1930 {
1931 miningTimer.stop();
5034d1c1 1932 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
42181656 1933 return;
1934 }
1935 miningTimer.stop();
1936}
1937
8e8b6d70 1938#ifdef ENABLE_WALLET
d247a5d1 1939void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
1940#else
1941void static BitcoinMiner()
1942#endif
d247a5d1 1943{
2e500f50 1944 LogPrintf("KomodoMiner started\n");
d247a5d1 1945 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 1946 RenameThread("komodo-miner");
bebe7282 1947 const CChainParams& chainparams = Params();
e9e70b95 1948
8e8b6d70
JG
1949#ifdef ENABLE_WALLET
1950 // Each thread has its own key
d247a5d1 1951 CReserveKey reservekey(pwallet);
8e8b6d70 1952#endif
e9e70b95 1953
8e8b6d70 1954 // Each thread has its own counter
d247a5d1 1955 unsigned int nExtraNonce = 0;
e9e70b95 1956
e9574728
JG
1957 unsigned int n = chainparams.EquihashN();
1958 unsigned int k = chainparams.EquihashK();
16593898 1959 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
99ba67a0 1960 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
755ead98 1961 {
1962 sleep(1);
4e624c04 1963 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1964 break;
755ead98 1965 }
32b0978b 1966 if ( ASSETCHAINS_SYMBOL[0] == 0 )
4b729ec5 1967 komodo_chosennotary(&notaryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
28a62b60 1968 if ( notaryid != My_notaryid )
1969 My_notaryid = notaryid;
755ead98 1970 std::string solver;
e1e65cef 1971 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
e9e70b95 1972 solver = "tromp";
e1e65cef 1973 //else solver = "default";
5f0009b2 1974 assert(solver == "tromp" || solver == "default");
c7aaab7a 1975 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 1976 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 1977 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
1978 std::mutex m_cs;
1979 bool cancelSolver = false;
1980 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
e9e70b95 1981 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1982 std::lock_guard<std::mutex> lock{m_cs};
1983 cancelSolver = true;
1984 }
1985 );
07be8f7e 1986 miningTimer.start();
e9e70b95 1987
0655fac0 1988 try {
ad84148d 1989 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 1990 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 1991 while (true)
1992 {
4b729ec5 1993 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
e725f1cb 1994 {
4b729ec5 1995 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
a96fd7b5 1996 // break;
0655fac0
PK
1997 // Busy-wait for the network to come online so we don't waste time mining
1998 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 1999 miningTimer.stop();
bba7c249
GM
2000 do {
2001 bool fvNodesEmpty;
2002 {
373668be 2003 //LOCK(cs_vNodes);
bba7c249
GM
2004 fvNodesEmpty = vNodes.empty();
2005 }
269fe243 2006 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 2007 break;
6e78d3df 2008 MilliSleep(15000);
ad84148d 2009 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
e9e70b95 2010
bba7c249 2011 } while (true);
ad84148d 2012 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 2013 miningTimer.start();
0655fac0 2014 }
0655fac0
PK
2015 //
2016 // Create new block
2017 //
2018 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
86131275 2019 CBlockIndex* pindexPrev = chainActive.LastTip();
4b729ec5 2020 if ( Mining_height != pindexPrev->GetHeight()+1 )
4940066c 2021 {
4b729ec5 2022 Mining_height = pindexPrev->GetHeight()+1;
4940066c 2023 Mining_start = (uint32_t)time(NULL);
2024 }
8e9ef91c 2025 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 2026 {
40304479 2027 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
5a7fd132 2028 //sleep(3);
2825c0b5 2029 }
135fa24e 2030
8e8b6d70 2031#ifdef ENABLE_WALLET
135fa24e 2032 // notaries always default to staking
4b729ec5 2033 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
8e8b6d70 2034#else
945f015d 2035 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 2036#endif
08d0b73c 2037 if ( ptr == 0 )
2038 {
d0f7ead0 2039 static uint32_t counter;
5bb3d0fe 2040 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 2041 fprintf(stderr,"created illegal block, retry\n");
8fc79ac9 2042 sleep(1);
d0f7ead0 2043 continue;
08d0b73c 2044 }
2a6a442a 2045 //fprintf(stderr,"get template\n");
08d0b73c 2046 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 2047 if (!pblocktemplate.get())
6c37f7fd 2048 {
8e8b6d70 2049 if (GetArg("-mineraddress", "").empty()) {
945f015d 2050 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
2051 } else {
2052 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 2053 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 2054 }
0655fac0 2055 return;
6c37f7fd 2056 }
0655fac0 2057 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 2058 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2059 {
42181656 2060 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
16c7bf6b 2061 {
8683bd8d 2062 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
2063 {
2064 static uint32_t counter;
2065 if ( counter++ < 10 )
2066 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
2067 sleep(10);
2068 continue;
2069 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
2070 }
16c7bf6b 2071 }
0655fac0 2072 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2a6a442a 2073 //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
2e500f50 2074 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
2075 //
2076 // Search
2077 //
2ba9de01 2078 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 2079 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
404391b5 2080 savebits = pblock->nBits;
d5614a76 2081 HASHTarget = arith_uint256().SetCompact(savebits);
f0100e72 2082 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 2083 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 2084 {
fda5f849 2085 j = 65;
67df454d 2086 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
fb6c7505 2087 {
4fff8a63 2088 int32_t dispflag = 0;
ef70c5b2 2089 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
4fff8a63 2090 dispflag = 1;
4b729ec5 2091 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
29e60e48 2092 if ( nonzpkeys > 0 )
2093 {
ccb71a6e 2094 for (i=0; i<33; i++)
2095 if( pubkeys[0][i] != 0 )
2096 break;
2097 if ( i == 33 )
2098 externalflag = 1;
2099 else externalflag = 0;
4d068367 2100 if ( IS_KOMODO_NOTARY != 0 )
b176c125 2101 {
345e545e 2102 for (i=1; i<66; i++)
2103 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
2104 break;
6494f040 2105 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
2106 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
2c7ad758 2107 for (j=gpucount=0; j<65; j++)
2108 {
4fff8a63 2109 if ( dispflag != 0 )
e4a383e3 2110 {
2111 if ( mids[j] >= 0 )
2112 fprintf(stderr,"%d ",mids[j]);
2113 else fprintf(stderr,"GPU ");
2114 }
2c7ad758 2115 if ( mids[j] == -1 )
2116 gpucount++;
2117 }
4fff8a63 2118 if ( dispflag != 0 )
4b729ec5 2119 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 2120 }
29e60e48 2121 for (j=0; j<65; j++)
2122 if ( mids[j] == notaryid )
2123 break;
49b49585 2124 if ( j == 65 )
2125 KOMODO_LASTMINED = 0;
965f0f7e 2126 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 2127 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 2128 {
88287857 2129 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
4b729ec5 2130 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
fda5f849 2131 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 2132 } else Mining_start = 0;
d7d27bb3 2133 } else Mining_start = 0;
2ba9de01 2134 if ( ASSETCHAINS_STAKED != 0 )
e725f1cb 2135 {
ed3d0a05 2136 int32_t percPoS,z; bool fNegative,fOverflow;
18443f69 2137 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
f108acf9 2138 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
f2c1ac06 2139 if ( ASSETCHAINS_STAKED < 100 )
2140 {
2141 for (z=31; z>=0; z--)
2142 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
2143 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
2144 }
deba7f20 2145 }
e725f1cb 2146 while (true)
2147 {
99ba67a0 2148 if ( KOMODO_INSYNC == 0 )
2149 {
e9d56b2c 2150 fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
2151 if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
a02c45db 2152 KOMODO_INSYNC = 1;
99ba67a0 2153 sleep(3);
2154 }
7213c0b1 2155 // Hash state
8c22eb46 2156 KOMODO_CHOSEN_ONE = 0;
42181656 2157
7213c0b1 2158 crypto_generichash_blake2b_state state;
e9574728 2159 EhInitialiseState(n, k, state);
7213c0b1
JG
2160 // I = the block header minus nonce and solution.
2161 CEquihashInput I{*pblock};
2162 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2163 ss << I;
7213c0b1
JG
2164 // H(I||...
2165 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
2166 // H(I||V||...
2167 crypto_generichash_blake2b_state curr_state;
2168 curr_state = state;
7a4c01c9 2169 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 2170 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 2171 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
18443f69 2172 arith_uint256 hashTarget;
6e78d3df 2173 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
18443f69 2174 hashTarget = HASHTarget_POW;
2175 else hashTarget = HASHTarget;
5be6abbf 2176 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 2177#ifdef ENABLE_WALLET
e9e70b95 2178 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 2179#else
e9e70b95 2180 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 2181#endif
e9e70b95 2182 (std::vector<unsigned char> soln) {
c21c6306 2183 int32_t z; arith_uint256 h; CBlock B;
51eb5273
JG
2184 // Write the solution to the hash and compute the result.
2185 LogPrint("pow", "- Checking solution against target\n");
8e165d57 2186 pblock->nSolution = soln;
e7d59bbc 2187 solutionTargetChecks.increment();
eff2c3a3 2188 B = *pblock;
2189 h = UintToArith256(B.GetHash());
eff2c3a3 2190 /*for (z=31; z>=16; z--)
02c30aac 2191 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
aea2d1aa 2192 fprintf(stderr," mined ");
2193 for (z=31; z>=16; z--)
18443f69 2194 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
aea2d1aa 2195 fprintf(stderr," hashTarget ");
2196 for (z=31; z>=16; z--)
18443f69 2197 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
eff2c3a3 2198 fprintf(stderr," POW\n");*/
265f4e96 2199 if ( h > hashTarget )
40df8d84 2200 {
6e78d3df 2201 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
afa90f17 2202 // sleep(1);
265f4e96 2203 return false;
40df8d84 2204 }
41e9c815 2205 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
d7d27bb3 2206 {
45ee62cb 2207 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
596b05ba 2208 while ( GetAdjustedTime() < B.nTime-2 )
8e9ef91c 2209 {
eb1ba5a0 2210 sleep(1);
4b729ec5 2211 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
4cc387ec 2212 {
2213 fprintf(stderr,"new block arrived\n");
2214 return(false);
2215 }
8e9ef91c 2216 }
eb1ba5a0 2217 }
8e9ef91c 2218 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 2219 {
4d068367 2220 if ( IS_KOMODO_NOTARY != 0 )
8e9ef91c 2221 {
26810a26 2222 int32_t r;
9703f8a0 2223 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
596b05ba 2224 MilliSleep((rand() % (r * 1000)) + 1000);
ef70c5b2 2225 }
e5430f52 2226 }
8e9ef91c 2227 else
d7d27bb3 2228 {
0c35569b 2229 while ( B.nTime-57 > GetAdjustedTime() )
deba7f20 2230 {
afa90f17 2231 sleep(1);
4b729ec5 2232 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
afa90f17 2233 return(false);
68d0354d 2234 }
4d068367 2235 uint256 tmp = B.GetHash();
2236 int32_t z; for (z=31; z>=0; z--)
2237 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
01e50e73 2238 fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
d7d27bb3 2239 }
8fc79ac9 2240 CValidationState state;
86131275 2241 if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false))
d2d3c766 2242 {
8fc79ac9 2243 h = UintToArith256(B.GetHash());
2244 for (z=31; z>=0; z--)
2245 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
2246 fprintf(stderr," Invalid block mined, try again\n");
2247 return(false);
d2d3c766 2248 }
b3183e3e 2249 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
2250 // Found a solution
2251 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 2252 LogPrintf("KomodoMiner:\n");
eff2c3a3 2253 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 2254#ifdef ENABLE_WALLET
eff2c3a3 2255 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
8e8b6d70 2256#else
eff2c3a3 2257 if (ProcessBlockFound(&B)) {
8e8b6d70 2258#endif
e9e70b95 2259 // Ignore chain updates caused by us
2260 std::lock_guard<std::mutex> lock{m_cs};
2261 cancelSolver = false;
2262 }
2263 KOMODO_CHOSEN_ONE = 0;
2264 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2265 // In regression test mode, stop mining after a block is found.
2266 if (chainparams.MineBlocksOnDemand()) {
2267 // Increment here because throwing skips the call below
2268 ehSolverRuns.increment();
2269 throw boost::thread_interrupted();
2270 }
e9e70b95 2271 return true;
2272 };
2273 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
a6a0d913 2274 std::lock_guard<std::mutex> lock{m_cs};
e9e70b95 2275 return cancelSolver;
2276 };
2277
2278 // TODO: factor this out into a function with the same API for each solver.
2279 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
2280 // Create solver and initialize it.
2281 equi eq(1);
2282 eq.setstate(&curr_state);
2283
2284 // Initialization done, start algo driver.
2285 eq.digit0(0);
c7aaab7a 2286 eq.xfull = eq.bfull = eq.hfull = 0;
e9e70b95 2287 eq.showbsizes(0);
2288 for (u32 r = 1; r < WK; r++) {
2289 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
2290 eq.xfull = eq.bfull = eq.hfull = 0;
2291 eq.showbsizes(r);
c7aaab7a 2292 }
e9e70b95 2293 eq.digitK(0);
2294 ehSolverRuns.increment();
2295
2296 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
2297 for (size_t s = 0; s < eq.nsols; s++) {
2298 LogPrint("pow", "Checking solution %d\n", s+1);
2299 std::vector<eh_index> index_vector(PROOFSIZE);
2300 for (size_t i = 0; i < PROOFSIZE; i++) {
2301 index_vector[i] = eq.sols[s][i];
2302 }
2303 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
2304
2305 if (validBlock(sol_char)) {
2306 // If we find a POW solution, do not try other solutions
2307 // because they become invalid as we created a new block in blockchain.
2308 break;
2309 }
2310 }
2311 } else {
2312 try {
2313 // If we find a valid block, we rebuild
2314 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
2315 ehSolverRuns.increment();
2316 if (found) {
997ddd92 2317 int32_t i; uint256 hash = pblock->GetHash();
e9e70b95 2318 for (i=0; i<32; i++)
2319 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
2320 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
2321 FOUND_BLOCK = 1;
2322 KOMODO_MAYBEMINED = Mining_height;
2323 break;
2324 }
2325 } catch (EhSolverCancelledException&) {
2326 LogPrint("pow", "Equihash solver cancelled\n");
2327 std::lock_guard<std::mutex> lock{m_cs};
2328 cancelSolver = false;
c7aaab7a
DH
2329 }
2330 }
e9e70b95 2331
2332 // Check for stop or if block needs to be rebuilt
2333 boost::this_thread::interruption_point();
2334 // Regtest mode doesn't require peers
2335 if ( FOUND_BLOCK != 0 )
2336 {
2337 FOUND_BLOCK = 0;
2338 fprintf(stderr,"FOUND_BLOCK!\n");
2339 //sleep(2000);
2340 }
2341 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2342 {
2343 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
2344 {
2345 fprintf(stderr,"no nodes, break\n");
c7aaab7a 2346 break;
a6df7ab5 2347 }
c7aaab7a 2348 }
997ddd92 2349 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
10694486 2350 {
e9e70b95 2351 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2352 fprintf(stderr,"0xffff, break\n");
d90cef0b 2353 break;
10694486 2354 }
e9e70b95 2355 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2356 {
2357 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2358 fprintf(stderr,"timeout, break\n");
2359 break;
2360 }
86131275 2361 if ( pindexPrev != chainActive.LastTip() )
e9e70b95 2362 {
2363 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
2364 fprintf(stderr,"Tip advanced, break\n");
2365 break;
2366 }
2367 // Update nNonce and nTime
2368 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
2369 pblock->nBits = savebits;
18dd6a3b 2370 /*if ( NOTARY_PUBKEY33[0] == 0 )
e9e70b95 2371 {
f8f740a9 2372 int32_t percPoS;
df756d24
MT
2373 UpdateTime(pblock, consensusParams, pindexPrev);
2374 if (consensusParams.fPowAllowMinDifficultyBlocks)
23fc88bb 2375 {
2376 // Changing pblock->nTime can change work required on testnet:
2377 HASHTarget.SetCompact(pblock->nBits);
18443f69 2378 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
23fc88bb 2379 }
18dd6a3b 2380 }*/
48265f3c 2381 }
d247a5d1
JG
2382 }
2383 }
e9e70b95 2384 catch (const boost::thread_interrupted&)
2385 {
2386 miningTimer.stop();
2387 c.disconnect();
2388 LogPrintf("KomodoMiner terminated\n");
2389 throw;
2390 }
2391 catch (const std::runtime_error &e)
2392 {
2393 miningTimer.stop();
2394 c.disconnect();
2395 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
2396 return;
2397 }
07be8f7e 2398 miningTimer.stop();
5e9b555f 2399 c.disconnect();
bba7c249 2400 }
e9e70b95 2401
8e8b6d70 2402#ifdef ENABLE_WALLET
e9e70b95 2403 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70 2404#else
e9e70b95 2405 void GenerateBitcoins(bool fGenerate, int nThreads)
8e8b6d70 2406#endif
d247a5d1 2407 {
f8f61a6d 2408 if (!AreParamsInitialized())
2409 {
2410 return;
2411 }
2412
10214558 2413 // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
2414 // initialization, and this is the first time we can get it. store the Sapling address here
2415 extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
2416 extern std::string VERUS_CHEATCATCHER;
2417 libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);
2418 if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))
2419 {
99c94fc3 2420 try
2421 {
2422 cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
2423 }
2424 catch (...)
2425 {
2426 }
10214558 2427 }
bd6639fd 2428
b20c38cc 2429 VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);
bd6639fd 2430
89cd7b59 2431 if (fGenerate == true || VERUS_MINTBLOCKS)
10214558 2432 {
89cd7b59
MT
2433 mapArgs["-gen"] = "1";
2434
2435 if (VERUS_CHEATCATCHER.size() > 0)
99c94fc3 2436 {
89cd7b59
MT
2437 if (cheatCatcher == boost::none)
2438 {
2439 LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n");
2440 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
2441 }
2442 else
2443 {
2444 LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
2445 fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
2446 }
99c94fc3 2447 }
2448 }
10214558 2449
e9e70b95 2450 static boost::thread_group* minerThreads = NULL;
28424e9f 2451
e9e70b95 2452 if (nThreads < 0)
2453 nThreads = GetNumCores();
2454
2455 if (minerThreads != NULL)
2456 {
2457 minerThreads->interrupt_all();
2458 delete minerThreads;
2459 minerThreads = NULL;
2460 }
135fa24e 2461
afaeb54b 2462 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
5034d1c1 2463 if ( nThreads == 0 && ASSETCHAINS_STAKED )
3a446d9f 2464 nThreads = 1;
5034d1c1 2465
28424e9f 2466 if (!fGenerate)
e9e70b95 2467 return;
135fa24e 2468
e9e70b95 2469 minerThreads = new boost::thread_group();
135fa24e 2470
85c51d62 2471 // add the PBaaS thread when mining or staking
2472 minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub));
2473
135fa24e 2474#ifdef ENABLE_WALLET
b20c38cc 2475 if (VERUS_MINTBLOCKS && pwallet != NULL)
135fa24e 2476 {
2477 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
2478 }
2479#endif
2480
e9e70b95 2481 for (int i = 0; i < nThreads; i++) {
135fa24e 2482
8e8b6d70 2483#ifdef ENABLE_WALLET
135fa24e 2484 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2485 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
2486 else
2487 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
8e8b6d70 2488#else
135fa24e 2489 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
2490 minerThreads->create_thread(&BitcoinMiner);
2491 else
2492 minerThreads->create_thread(&BitcoinMiner_noeq);
8e8b6d70 2493#endif
e9e70b95 2494 }
8e8b6d70 2495 }
e9e70b95 2496
2cc0a252 2497#endif // ENABLE_MINING
This page took 0.943545 seconds and 4 git commands to generate.