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