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