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