]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Do not resurrect staking transactions and lose stake age when no block won
[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"
8e8b6d70 12#include "base58.h"
bebe7282 13#include "chainparams.h"
691161d4 14#include "consensus/consensus.h"
be126699 15#include "consensus/upgrades.h"
da29ecbc 16#include "consensus/validation.h"
8e8b6d70
JG
17#ifdef ENABLE_MINING
18#include "crypto/equihash.h"
42181656 19#include "crypto/verus_hash.h"
8e8b6d70 20#endif
85aab2a0 21#include "hash.h"
42181656 22
d247a5d1 23#include "main.h"
a6df7ab5 24#include "metrics.h"
51ed9ec9 25#include "net.h"
df852d2b 26#include "pow.h"
bebe7282 27#include "primitives/transaction.h"
8e165d57 28#include "random.h"
22c4272b 29#include "timedata.h"
8e8b6d70 30#include "ui_interface.h"
ad49c256
WL
31#include "util.h"
32#include "utilmoneystr.h"
df840de5 33#ifdef ENABLE_WALLET
50c72f23 34#include "wallet/wallet.h"
df840de5 35#endif
09eb201b 36
fdda3c50
JG
37#include "sodium.h"
38
ad49c256 39#include <boost/thread.hpp>
a3c26c2e 40#include <boost/tuple/tuple.hpp>
8e8b6d70
JG
41#ifdef ENABLE_MINING
42#include <functional>
43#endif
5a360a5c 44#include <mutex>
ad49c256 45
09eb201b 46using namespace std;
7b4737c8 47
d247a5d1
JG
48//////////////////////////////////////////////////////////////////////////////
49//
50// BitcoinMiner
51//
52
c6cb21d1
GA
53//
54// Unconfirmed transactions in the memory pool often depend on other
55// transactions in the memory pool. When we select transactions from the
56// pool, we select by highest priority or fee rate, so we might consider
57// transactions that depend on transactions that aren't yet in the block.
58// The COrphan class keeps track of these 'temporary orphans' while
59// CreateBlock is figuring out which transactions to include.
60//
d247a5d1
JG
61class COrphan
62{
63public:
4d707d51 64 const CTransaction* ptx;
d247a5d1 65 set<uint256> setDependsOn;
c6cb21d1 66 CFeeRate feeRate;
02bec4b2 67 double dPriority;
e9e70b95 68
c6cb21d1 69 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 70 {
d247a5d1 71 }
d247a5d1
JG
72};
73
51ed9ec9
BD
74uint64_t nLastBlockTx = 0;
75uint64_t nLastBlockSize = 0;
d247a5d1 76
c6cb21d1
GA
77// We want to sort transactions by priority and fee rate, so:
78typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
79class TxPriorityCompare
80{
81 bool byFee;
e9e70b95 82
d247a5d1
JG
83public:
84 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
e9e70b95 85
d247a5d1
JG
86 bool operator()(const TxPriority& a, const TxPriority& b)
87 {
88 if (byFee)
89 {
90 if (a.get<1>() == b.get<1>())
91 return a.get<0>() < b.get<0>();
92 return a.get<1>() < b.get<1>();
93 }
94 else
95 {
96 if (a.get<0>() == b.get<0>())
97 return a.get<1>() < b.get<1>();
98 return a.get<0>() < b.get<0>();
99 }
100 }
101};
102
bebe7282 103void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 104{
4972b74b 105 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
22c4272b 106}
107
5416af1d 108#include "komodo_defs.h"
109
16c7bf6b 110extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
48d800c2 111extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
42181656 112extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
113extern const char *ASSETCHAINS_ALGORITHMS[];
1fae37f6 114extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
7c130297 115extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
f24b36ca 116extern std::string NOTARY_PUBKEY;
94a465a6 117extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 118uint32_t Mining_start,Mining_height;
8683bd8d 119int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 120int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
265660f7 121//uint64_t komodo_paxtotal();
d63fdb34 122int32_t komodo_baseid(char *origbase);
001bc04a 123//int32_t komodo_is_issuer();
124//int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
265660f7 125//int32_t komodo_isrealtime(int32_t *kmdheightp);
3bc88f14 126int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
29bd53a1 127int64_t komodo_block_unlocktime(uint32_t nHeight);
18443f69 128uint64_t komodo_commission(const CBlock *block);
135fa24e 129int32_t komodo_staked(CPubKey &pubkey, CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
1f722359 130int32_t verus_staked(CPubKey &pubkey, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig);
496f1fd2 131int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
7652ed92 132
135fa24e 133CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn, bool isStake)
d247a5d1 134{
9339a0cb 135 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
d247a5d1 136 // Create new block
08c58194 137 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 138 if(!pblocktemplate.get())
1b5b89ba 139 {
140 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 141 return NULL;
1b5b89ba 142 }
d247a5d1 143 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
265660f7 144 /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
a5e36fdd 145 {
48a3cd18 146 isrealtime = komodo_isrealtime(&kmdheight);
3da07d2e 147 deposits = komodo_paxtotal();
5ba0ce9d 148 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
ec7ad5f6 149 {
79562bf3 150 deposits = komodo_paxtotal();
16c7bf6b 151 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
79562bf3 152 {
bbaa688c 153 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
79562bf3 154 }
2bec17cb 155 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
4a21ccd2 156 {
eb928486 157 fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
79562bf3 158 break;
4a21ccd2 159 }
6fd0ae11 160 sleep(10);
ec7ad5f6 161 }
f24b36ca 162 KOMODO_ON_DEMAND = 0;
16cd9f2d 163 if ( 0 && deposits != 0 )
79562bf3 164 printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
265660f7 165 }*/
dbca89b7
GA
166 // -regtest only: allow overriding block.nVersion with
167 // -blockversion=N to test forking scenarios
168 if (Params().MineBlocksOnDemand())
169 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
e9e70b95 170
4949004d
PW
171 // Add dummy coinbase tx as first transaction
172 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
173 pblocktemplate->vTxFees.push_back(-1); // updated at end
174 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
e9e70b95 175
d247a5d1 176 // Largest block you're willing to create:
ad898b40 177 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
178 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
179 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
e9e70b95 180
d247a5d1
JG
181 // How much of the block should be dedicated to high-priority transactions,
182 // included regardless of the fees they pay
183 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
184 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
e9e70b95 185
d247a5d1
JG
186 // Minimum block size you want to create; block will be filled with free transactions
187 // until there are no more or the block reaches this size:
037b4f14 188 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1 189 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
e9e70b95 190
d247a5d1 191 // Collect memory pool transactions into the block
a372168e 192 CAmount nFees = 0;
e9e70b95 193
d247a5d1
JG
194 {
195 LOCK2(cs_main, mempool.cs);
48265f3c 196 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 197 const int nHeight = pindexPrev->nHeight + 1;
be126699 198 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
a0dd01bc 199
a1d3c6fb 200 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
a0dd01bc 201 uint32_t proposedTime = GetAdjustedTime();
202 if (proposedTime == nMedianTimePast)
203 {
204 // too fast or stuck, this addresses the too fast issue, while moving
205 // forward as quickly as possible
206 for (int i; i < 100; i++)
207 {
208 proposedTime = GetAdjustedTime();
209 if (proposedTime == nMedianTimePast)
210 MilliSleep(10);
211 }
212 }
213 pblock->nTime = GetAdjustedTime();
214
7c70438d 215 CCoinsViewCache view(pcoinsTip);
f9155fec 216 uint32_t expired; uint64_t commission;
6ff77181 217
d247a5d1
JG
218 // Priority order to process transactions
219 list<COrphan> vOrphan; // list memory doesn't move
220 map<uint256, vector<COrphan*> > mapDependers;
221 bool fPrintPriority = GetBoolArg("-printpriority", false);
e9e70b95 222
d247a5d1
JG
223 // This vector will be sorted into a priority queue:
224 vector<TxPriority> vecPriority;
225 vecPriority.reserve(mempool.mapTx.size());
e328fa32 226 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 227 mi != mempool.mapTx.end(); ++mi)
d247a5d1 228 {
e328fa32 229 const CTransaction& tx = mi->GetTx();
e9e70b95 230
a1d3c6fb 231 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
e9e70b95 232 ? nMedianTimePast
233 : pblock->GetBlockTime();
234
9bb37bf0 235 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
61f8caf2 236 {
51376f3c 237 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
14aa6cc0 238 continue;
61f8caf2 239 }
161f617d 240 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
6ff77181 241 {
64b45b71 242 //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 243 continue;
14aa6cc0 244 }
d247a5d1
JG
245 COrphan* porphan = NULL;
246 double dPriority = 0;
a372168e 247 CAmount nTotalIn = 0;
d247a5d1
JG
248 bool fMissingInputs = false;
249 BOOST_FOREACH(const CTxIn& txin, tx.vin)
250 {
251 // Read prev transaction
252 if (!view.HaveCoins(txin.prevout.hash))
253 {
254 // This should never happen; all transactions in the memory
255 // pool should connect to either transactions in the chain
256 // or other transactions in the memory pool.
257 if (!mempool.mapTx.count(txin.prevout.hash))
258 {
881a85a2 259 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
260 if (fDebug) assert("mempool transaction missing input" == 0);
261 fMissingInputs = true;
262 if (porphan)
263 vOrphan.pop_back();
264 break;
265 }
e9e70b95 266
d247a5d1
JG
267 // Has to wait for dependencies
268 if (!porphan)
269 {
270 // Use list for automatic deletion
271 vOrphan.push_back(COrphan(&tx));
272 porphan = &vOrphan.back();
273 }
274 mapDependers[txin.prevout.hash].push_back(porphan);
275 porphan->setDependsOn.insert(txin.prevout.hash);
e328fa32 276 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
277 continue;
278 }
629d75fa
PW
279 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
280 assert(coins);
e9e70b95 281
a372168e 282 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1 283 nTotalIn += nValueIn;
e9e70b95 284
b867e409 285 int nConf = nHeight - coins->nHeight;
e9e70b95 286
d247a5d1
JG
287 dPriority += (double)nValueIn * nConf;
288 }
2b2bc69e 289 nTotalIn += tx.GetJoinSplitValueIn();
e9e70b95 290
d247a5d1 291 if (fMissingInputs) continue;
e9e70b95 292
d6eb2599 293 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 294 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 295 dPriority = tx.ComputePriority(dPriority, nTxSize);
e9e70b95 296
805344dc 297 uint256 hash = tx.GetHash();
2a72d459 298 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
e9e70b95 299
c6cb21d1 300 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
e9e70b95 301
d247a5d1
JG
302 if (porphan)
303 {
304 porphan->dPriority = dPriority;
c6cb21d1 305 porphan->feeRate = feeRate;
d247a5d1
JG
306 }
307 else
e328fa32 308 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1 309 }
e9e70b95 310
d247a5d1 311 // Collect transactions into block
51ed9ec9
BD
312 uint64_t nBlockSize = 1000;
313 uint64_t nBlockTx = 0;
355ca565 314 int64_t interest;
d247a5d1
JG
315 int nBlockSigOps = 100;
316 bool fSortedByFee = (nBlockPrioritySize <= 0);
e9e70b95 317
d247a5d1
JG
318 TxPriorityCompare comparer(fSortedByFee);
319 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
e9e70b95 320
d247a5d1
JG
321 while (!vecPriority.empty())
322 {
323 // Take highest priority transaction off the priority queue:
324 double dPriority = vecPriority.front().get<0>();
c6cb21d1 325 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 326 const CTransaction& tx = *(vecPriority.front().get<2>());
e9e70b95 327
d247a5d1
JG
328 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
329 vecPriority.pop_back();
e9e70b95 330
d247a5d1
JG
331 // Size limits
332 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
01fda4c1 333 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
61f8caf2 334 {
51376f3c 335 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
d247a5d1 336 continue;
61f8caf2 337 }
e9e70b95 338
d247a5d1
JG
339 // Legacy limits on sigOps:
340 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
a4a40a38 341 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 342 {
51376f3c 343 //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 344 continue;
61f8caf2 345 }
d247a5d1 346 // Skip free transactions if we're past the minimum block size:
805344dc 347 const uint256& hash = tx.GetHash();
2a72d459 348 double dPriorityDelta = 0;
a372168e 349 CAmount nFeeDelta = 0;
2a72d459 350 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 351 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
61f8caf2 352 {
51376f3c 353 //fprintf(stderr,"fee rate skip\n");
d247a5d1 354 continue;
61f8caf2 355 }
2a72d459 356 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
357 // transactions:
358 if (!fSortedByFee &&
359 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
360 {
361 fSortedByFee = true;
362 comparer = TxPriorityCompare(fSortedByFee);
363 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
364 }
e9e70b95 365
d247a5d1 366 if (!view.HaveInputs(tx))
61f8caf2 367 {
51376f3c 368 //fprintf(stderr,"dont have inputs\n");
d247a5d1 369 continue;
61f8caf2 370 }
1141b678 371 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
e9e70b95 372
d247a5d1 373 nTxSigOps += GetP2SHSigOpCount(tx, view);
a4a40a38 374 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
61f8caf2 375 {
51376f3c 376 //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 377 continue;
61f8caf2 378 }
68f7d1d7
PT
379 // Note that flags: we don't want to set mempool/IsStandard()
380 // policy here, but we still have to ensure that the block we
381 // create only contains transactions that are valid in new blocks.
d247a5d1 382 CValidationState state;
6514771a 383 PrecomputedTransactionData txdata(tx);
be126699 384 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
61f8caf2 385 {
51376f3c 386 //fprintf(stderr,"context failure\n");
d247a5d1 387 continue;
61f8caf2 388 }
8cb98d91 389 UpdateCoins(tx, view, nHeight);
e9e70b95 390
d247a5d1
JG
391 // Added
392 pblock->vtx.push_back(tx);
393 pblocktemplate->vTxFees.push_back(nTxFees);
394 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
395 nBlockSize += nTxSize;
396 ++nBlockTx;
397 nBlockSigOps += nTxSigOps;
398 nFees += nTxFees;
e9e70b95 399
d247a5d1
JG
400 if (fPrintPriority)
401 {
3f0813b3 402 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1 403 }
e9e70b95 404
d247a5d1
JG
405 // Add transactions that depend on this one to the priority queue
406 if (mapDependers.count(hash))
407 {
408 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
409 {
410 if (!porphan->setDependsOn.empty())
411 {
412 porphan->setDependsOn.erase(hash);
413 if (porphan->setDependsOn.empty())
414 {
c6cb21d1 415 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
416 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
417 }
418 }
419 }
420 }
421 }
e9e70b95 422
d247a5d1
JG
423 nLastBlockTx = nBlockTx;
424 nLastBlockSize = nBlockSize;
d07308d2 425 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9a0f2798 426 //pblock->nTime = blocktime + 1;
135fa24e 427 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
428
7dbeae5d 429 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
135fa24e 430 if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake )
a4a40a38 431 {
135fa24e 432 CPubKey key;
433
434 if ( NOTARY_PUBKEY33[0] != 0 )
435 {
436 key = CPubKey(ParseHex(NOTARY_PUBKEY));
437 }
438 else
439 {
440 vector<vector<unsigned char>> vSolutions;
441 txnouttype whichType;
442
443 if (Solver(scriptPubKeyIn, whichType, vSolutions) && !vSolutions.empty())
444 {
445 key = CPubKey(vSolutions[0]);
446 }
447 else
448 {
449 fprintf(stderr,"CreateNewBlock() invalid scriptPubKeyIn\n");
450 return(0);
451 }
452 }
453
1f722359 454 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
d231a6a7 455 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
1f722359 456
cfb55edb 457 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
458 // blocktime = pindexPrev->GetMedianTimePast() + 60;
1f722359
MT
459 if (ASSETCHAINS_LWMAPOS != 0)
460 {
461 uint32_t nBitsPOS;
462 arith_uint256 posHash;
463 siglen = verus_staked(key, txStaked, nBitsPOS, posHash, utxosig);
464 blocktime = GetAdjustedTime();
1fae37f6 465 pblock->SetVerusPOSTarget(nBitsPOS);
cd230e37
MT
466
467 // change the scriptPubKeyIn to the same output script exactly as the staking transaction
468 if (siglen > 0)
469 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
1f722359
MT
470 }
471 else
472 {
473 siglen = komodo_staked(key, txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
474 }
475
476 if ( siglen > 0 )
a4a40a38 477 {
66b4e563 478 CAmount txfees = 0;
de230f5e 479 if ( GetAdjustedTime() < blocktime-13 )
ba1587fd 480 return(0);
a4a40a38 481 pblock->vtx.push_back(txStaked);
a4a40a38 482 pblocktemplate->vTxFees.push_back(txfees);
d231a6a7 483 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
a4a40a38 484 nFees += txfees;
9339a0cb 485 pblock->nTime = blocktime;
de230f5e 486 //printf("PoS ht.%d t%u\n",(int32_t)chainActive.Tip()->nHeight+1,blocktime);
9464ac21 487 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
a4a40a38 488 }
e9e70b95 489
f3ffa3d2 490 // Create coinbase tx
072099d7 491 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
492 txNew.vin.resize(1);
493 txNew.vin[0].prevout.SetNull();
abb90a89
MT
494 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
495
d581f229 496 txNew.vout.resize(1);
f3ffa3d2 497 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
abb90a89 498 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees;
9bb37bf0 499 txNew.nExpiryHeight = 0;
48d800c2 500 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
abb90a89 501
29bd53a1 502 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
a0dd01bc 503 // to transaction if so, cast for GTE operator
504 if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE)
abb90a89
MT
505 {
506 int32_t opretlen, p2shlen, scriptlen;
29bd53a1 507 CScriptExt opretScript = CScriptExt();
abb90a89
MT
508
509 txNew.vout.resize(2);
510
29bd53a1
MT
511 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
512 // protected only by the time lock rather than 100% inaccessible
513 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
514 if (!scriptPubKeyIn.IsPayToScriptHash())
515 opretScript += scriptPubKeyIn;
abb90a89 516
29bd53a1
MT
517 txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
518 txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
abb90a89 519 txNew.vout[1].nValue = 0;
48d800c2 520 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
521 else if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
c9b1071d 522 {
c000c9ca 523 int32_t i; uint8_t *ptr;
9ed1be03 524 txNew.vout.resize(2);
525 txNew.vout[1].nValue = commission;
526 txNew.vout[1].scriptPubKey.resize(35);
527 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
c000c9ca 528 ptr[0] = 33;
529 for (i=0; i<33; i++)
530 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
531 ptr[34] = OP_CHECKSIG;
146d2aa2 532 //printf("autocreate commision vout\n");
c9b1071d 533 }
48d800c2 534
4949004d 535 pblock->vtx[0] = txNew;
d247a5d1 536 pblocktemplate->vTxFees[0] = -nFees;
48d800c2 537
1fae37f6
MT
538 // if not Verus stake, setup nonce, otherwise, leave it alone
539 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
540 {
541 // Randomise nonce
542 arith_uint256 nonce = UintToArith256(GetRandHash());
48d800c2 543
1fae37f6
MT
544 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
545 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
546 nonce >>= 16;
547 pblock->nNonce = ArithToUint256(nonce);
548 }
e9e70b95 549
d247a5d1
JG
550 // Fill in header
551 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 552 pblock->hashReserved = uint256();
3da69a31 553
9a0f2798 554 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
555 {
556 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
1fae37f6 557 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
9a0f2798 558 }
fdda3c50 559 pblock->nSolution.clear();
d247a5d1 560 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
496f1fd2 561 if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
af805d53 562 {
496f1fd2 563 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
f31815fc 564 if ( pblock->nTime < pindexPrev->nTime+65 )
c670f024 565 pblock->nTime = pindexPrev->nTime + 65;
a893e994 566 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
496f1fd2 567 {
568 CAmount txfees = 0;
569 pblock->vtx.push_back(txNotary);
570 pblocktemplate->vTxFees.push_back(txfees);
571 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
572 nFees += txfees;
f31815fc 573 //fprintf(stderr,"added notaryvin\n");
0857c3d5 574 }
575 else
576 {
577 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
578 return(0);
579 }
707b061c 580 }
8fc79ac9 581 else
af805d53 582 {
8fc79ac9 583 CValidationState state;
584 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
585 {
586 //static uint32_t counter;
587 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
588 // fprintf(stderr,"warning: miner testblockvalidity failed\n");
589 return(0);
590 }
af805d53 591 }
d247a5d1 592 }
d247a5d1
JG
593 return pblocktemplate.release();
594}
32b915c9 595
1a31463b 596/*
e9e70b95 597 #ifdef ENABLE_WALLET
598 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
599 #else
600 boost::optional<CScript> GetMinerScriptPubKey()
601 #endif
602 {
603 CKeyID keyID;
604 CBitcoinAddress addr;
605 if (addr.SetString(GetArg("-mineraddress", ""))) {
606 addr.GetKeyID(keyID);
607 } else {
608 #ifdef ENABLE_WALLET
609 CPubKey pubkey;
610 if (!reservekey.GetReservedKey(pubkey)) {
611 return boost::optional<CScript>();
612 }
613 keyID = pubkey.GetID();
614 #else
615 return boost::optional<CScript>();
616 #endif
617 }
618
619 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
620 return scriptPubKey;
621 }
622
623 #ifdef ENABLE_WALLET
624 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
625 {
626 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
627 #else
628 CBlockTemplate* CreateNewBlockWithKey()
629 {
630 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
631 #endif
632
633 if (!scriptPubKey) {
634 return NULL;
635 }
636 return CreateNewBlock(*scriptPubKey);
637 }*/
acfa0333 638
c1de826f
JG
639//////////////////////////////////////////////////////////////////////////////
640//
641// Internal miner
642//
643
2cc0a252 644#ifdef ENABLE_MINING
c1de826f 645
d247a5d1
JG
646void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
647{
648 // Update nExtraNonce
649 static uint256 hashPrevBlock;
650 if (hashPrevBlock != pblock->hashPrevBlock)
651 {
652 nExtraNonce = 0;
653 hashPrevBlock = pblock->hashPrevBlock;
654 }
655 ++nExtraNonce;
656 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
657 CMutableTransaction txCoinbase(pblock->vtx[0]);
658 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
659 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
e9e70b95 660
4949004d 661 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
662 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
663}
664
4a85e067 665#ifdef ENABLE_WALLET
acfa0333
WL
666//////////////////////////////////////////////////////////////////////////////
667//
668// Internal miner
669//
acfa0333 670
135fa24e 671CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, bool isStake)
acfa0333 672{
f6c647ed 673 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 674 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 675 {
7bfc207a 676 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 677 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 678 }
679 else
680 {
681 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 682 {
f6c647ed 683 return NULL;
1b5b89ba 684 }
f6c647ed 685 scriptPubKey.resize(35);
f66f65ec 686 ptr = (uint8_t *)pubkey.begin();
f6c647ed 687 script = (uint8_t *)scriptPubKey.data();
688 script[0] = 33;
689 for (i=0; i<33; i++)
690 script[i+1] = ptr[i];
691 script[34] = OP_CHECKSIG;
692 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
693 }
135fa24e 694 return CreateNewBlock(scriptPubKey, isStake);
acfa0333
WL
695}
696
395f10cf 697void komodo_broadcast(CBlock *pblock,int32_t limit)
698{
699 int32_t n = 1;
700 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
701 {
702 LOCK(cs_vNodes);
703 BOOST_FOREACH(CNode* pnode, vNodes)
704 {
705 if ( pnode->hSocket == INVALID_SOCKET )
706 continue;
707 if ( (rand() % n) == 0 )
708 {
709 pnode->PushMessage("block", *pblock);
710 if ( n++ > limit )
711 break;
712 }
713 }
714 }
715 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
716}
945f015d 717
269d8ba0 718static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
719#else
720static bool ProcessBlockFound(CBlock* pblock)
721#endif // ENABLE_WALLET
d247a5d1 722{
81212588 723 LogPrintf("%s\n", pblock->ToString());
35915149 724 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
e9e70b95 725
d247a5d1
JG
726 // Found a solution
727 {
728 LOCK(cs_main);
4c6d41b8 729 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
ba8419c7 730 {
731 uint256 hash; int32_t i;
732 hash = pblock->hashPrevBlock;
92266e99 733 for (i=31; i>=0; i--)
ba8419c7 734 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 735 fprintf(stderr," <- prev (stale)\n");
ba8419c7 736 hash = chainActive.Tip()->GetBlockHash();
92266e99 737 for (i=31; i>=0; i--)
ba8419c7 738 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 739 fprintf(stderr," <- chainTip (stale)\n");
e9e70b95 740
2e500f50 741 return error("KomodoMiner: generated block is stale");
ba8419c7 742 }
18e72167 743 }
e9e70b95 744
8e8b6d70 745#ifdef ENABLE_WALLET
18e72167 746 // Remove key from key pool
998397aa 747 if ( IS_KOMODO_NOTARY == 0 )
945f015d 748 {
749 if (GetArg("-mineraddress", "").empty()) {
750 // Remove key from key pool
751 reservekey.KeepKey();
752 }
8e8b6d70 753 }
18e72167 754 // Track how many getdata requests this block gets
438ba9c1 755 //if ( 0 )
18e72167
PW
756 {
757 LOCK(wallet.cs_wallet);
758 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 759 }
8e8b6d70 760#endif
e9e70b95 761
18e72167
PW
762 // Process this block the same as if we had received it from another node
763 CValidationState state;
7bb789bb 764 if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 765 return error("KomodoMiner: ProcessNewBlock, block not accepted");
e9e70b95 766
d793f94b 767 TrackMinedBlock(pblock->GetHash());
395f10cf 768 komodo_broadcast(pblock,16);
d247a5d1
JG
769 return true;
770}
771
078f6af1 772int32_t komodo_baseid(char *origbase);
a30dd993 773int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
13691369 774arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
8ee93080 775int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 776extern int32_t KOMODO_LASTMINED;
8b51b9e4 777int32_t roundrobin_delay;
18443f69 778arith_uint256 HASHTarget,HASHTarget_POW;
078f6af1 779
5642c96c 780// wait for peers to connect
b45d65b4 781int32_t waitForPeers(const CChainParams &chainparams)
5642c96c 782{
783 if (chainparams.MiningRequiresPeers())
784 {
3da69a31
MT
785 bool fvNodesEmpty;
786 {
787 LOCK(cs_vNodes);
788 fvNodesEmpty = vNodes.empty();
789 }
790 if (fvNodesEmpty)
791 {
792 do {
793 MilliSleep(5000 + rand() % 5000);
794 {
795 LOCK(cs_vNodes);
796 fvNodesEmpty = vNodes.empty();
797 }
798 } while (fvNodesEmpty);
799 MilliSleep(5000 + rand() % 5000);
800 }
5642c96c 801 }
802}
803
42181656 804#ifdef ENABLE_WALLET
135fa24e 805/*
806 * A separate thread to stake, while the miner threads mine.
807 */
808void static VerusStaker(CWallet *pwallet)
809{
810 LogPrintf("Verus staker thread started\n");
811 RenameThread("verus-staker");
812
813 const CChainParams& chainparams = Params();
814
815 // Each thread has its own key
816 CReserveKey reservekey(pwallet);
817
818 // Each thread has its own counter
819 unsigned int nExtraNonce = 0;
820 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
821 solnPlaceholder.resize(Eh200_9.SolutionWidth);
822 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
823
824 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
825 {
826 sleep(1);
827 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
828 break;
829 }
830
3da69a31
MT
831 SetThreadPriority(THREAD_PRIORITY_LOWEST);
832
135fa24e 833 // try a nice clean peer connection to start
834 waitForPeers(chainparams);
3da69a31
MT
835 // try a nice clean peer connection to start
836 waitForPeers(chainparams);
c132b91a 837 CBlockIndex* pindexPrev, *pindexCur;
135fa24e 838 do {
c132b91a
MT
839 {
840 LOCK(cs_main);
841 pindexPrev = chainActive.Tip();
842 }
3da69a31 843 MilliSleep(5000 + rand() % 5000);
c132b91a
MT
844 {
845 LOCK(cs_main);
846 pindexCur = chainActive.Tip();
847 }
848 } while (pindexPrev != pindexCur);
135fa24e 849
850 sleep(5);
c132b91a
MT
851
852 {
853 printf("Staking height %d for %s\n", chainActive.Tip()->nHeight + 1, ASSETCHAINS_SYMBOL);
854 }
1fae37f6 855 //fprintf(stderr,"Staking height %d for %s\n", chainActive.Tip()->nHeight + 1, ASSETCHAINS_SYMBOL);
135fa24e 856
857 miningTimer.start();
858
859 try {
135fa24e 860 while (true)
861 {
862 miningTimer.stop();
863 waitForPeers(chainparams);
864 miningTimer.start();
865
866 // Create new block
867 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
868 CBlockIndex* pindexPrev = chainActive.Tip();
869 if ( Mining_height != pindexPrev->nHeight+1 )
870 {
871 Mining_height = pindexPrev->nHeight+1;
872 Mining_start = (uint32_t)time(NULL);
873 }
874
1fae37f6
MT
875 // Check for stop or if block needs to be rebuilt
876 boost::this_thread::interruption_point();
877
135fa24e 878 // try to stake a block
1fae37f6
MT
879 CBlockTemplate *ptr = NULL;
880 if (Mining_height > VERUS_MIN_STAKEAGE)
881 ptr = CreateNewBlockWithKey(reservekey, true);
135fa24e 882
883 if ( ptr == 0 )
884 {
1fae37f6
MT
885 // wait to try another staking block until after the tip moves again
886 while ( chainActive.Tip() == pindexPrev )
887 sleep(5);
135fa24e 888 continue;
889 }
890
891 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
892 if (!pblocktemplate.get())
893 {
894 if (GetArg("-mineraddress", "").empty()) {
1fae37f6 895 LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
135fa24e 896 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
897 } else {
898 // Should never reach here, because -mineraddress validity is checked in init.cpp
1fae37f6 899 LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
135fa24e 900 }
901 return;
902 }
903
904 CBlock *pblock = &pblocktemplate->block;
1fae37f6 905 LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
135fa24e 906 //
907 // Search
908 //
1fae37f6
MT
909 int64_t nStart = GetTime();
910
52670b72
MT
911 // take up the necessary space for alignment
912 pblock->nSolution = solnPlaceholder;
913
1fae37f6
MT
914 // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree
915 unsigned int nExtraNonce = 0;
916 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
135fa24e 917
1fae37f6
MT
918 if (vNodes.empty() && chainparams.MiningRequiresPeers())
919 {
920 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
921 {
922 fprintf(stderr,"no nodes, attempting reconnect\n");
923 continue;
924 }
925 }
926
927 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
928 {
929 fprintf(stderr,"timeout, retrying\n");
930 continue;
931 }
135fa24e 932
933 if ( pindexPrev != chainActive.Tip() )
934 {
935 printf("Block %d added to chain\n", chainActive.Tip()->nHeight);
936 MilliSleep(250);
937 continue;
938 }
939
1fae37f6 940 SetThreadPriority(THREAD_PRIORITY_NORMAL);
135fa24e 941
1fae37f6
MT
942 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
943 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
135fa24e 944
1fae37f6 945 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
135fa24e 946
b9956efc
MT
947 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
948
949 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
950
951 ProcessBlockFound(pblock, *pwallet, reservekey);
952
1fae37f6
MT
953 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
954 LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
955 printf("Found block %d \n", Mining_height );
956 printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
b9956efc
MT
957 arith_uint256 post;
958 post.SetCompact(pblock->GetVerusPOSTarget());
959 printf(" hash: %s \ntarget: %s\n", pblock->vtx[pblock->vtx.size()-1].GetVerusPOSHash(0, Mining_height, pindexPrev->GetBlockHash()).GetHex().c_str(), ArithToUint256(post).GetHex().c_str());
1fae37f6
MT
960 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
961 printf("- timelocked until block %i\n", unlockTime);
962 else
963 printf("\n");
135fa24e 964
1fae37f6
MT
965 // Check for stop or if block needs to be rebuilt
966 boost::this_thread::interruption_point();
967 SetThreadPriority(THREAD_PRIORITY_LOWEST);
135fa24e 968
3da69a31
MT
969 sleep(5);
970
1fae37f6
MT
971 // In regression test mode, stop mining after a block is found.
972 if (chainparams.MineBlocksOnDemand()) {
973 throw boost::thread_interrupted();
135fa24e 974 }
975 }
976 }
977 catch (const boost::thread_interrupted&)
978 {
979 miningTimer.stop();
980 LogPrintf("VerusStaker terminated\n");
981 throw;
982 }
983 catch (const std::runtime_error &e)
984 {
985 miningTimer.stop();
986 LogPrintf("VerusStaker runtime error: %s\n", e.what());
987 return;
988 }
989 miningTimer.stop();
990}
991
42181656 992void static BitcoinMiner_noeq(CWallet *pwallet)
993#else
994void static BitcoinMiner_noeq()
995#endif
996{
05f6e633 997 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
05f6e633 998 RenameThread("verushash-miner");
42181656 999
1000#ifdef ENABLE_WALLET
1001 // Each thread has its own key
1002 CReserveKey reservekey(pwallet);
1003#endif
1004
2910478b 1005 const CChainParams& chainparams = Params();
42181656 1006 // Each thread has its own counter
1007 unsigned int nExtraNonce = 0;
1008 std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>();
1009 solnPlaceholder.resize(Eh200_9.SolutionWidth);
42181656 1010 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
1011
1012 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
1013 {
1014 sleep(1);
1015 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1016 break;
1017 }
9f3e2213 1018
3da69a31
MT
1019 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1020
5642c96c 1021 // try a nice clean peer connection to start
1022 waitForPeers(chainparams);
c132b91a 1023 CBlockIndex *pindexPrev, *pindexCur;
9f3e2213 1024 do {
dbe656fe 1025 pindexPrev = chainActive.Tip();
3da69a31 1026 MilliSleep(5000 + rand() % 5000);
dbe656fe 1027 pindexCur = chainActive.Tip();
c132b91a 1028 } while (pindexPrev != pindexCur);
6176a421 1029
dbe656fe
MT
1030 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
1031 // and print duplicates rarely without having to synchronize
1032 static CBlockIndex *lastChainTipPrinted;
9f3e2213 1033
42181656 1034 miningTimer.start();
1035
1036 try {
dbe656fe 1037 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1038 while (true)
1039 {
68334c8d 1040 miningTimer.stop();
1041 waitForPeers(chainparams);
dfcf8255 1042
3da69a31
MT
1043 pindexPrev = chainActive.Tip();
1044 sleep(1);
dfcf8255
MT
1045
1046 // prevent forking on startup before the diff algorithm kicks in
3da69a31 1047 if (pindexPrev->nHeight < 50 || pindexPrev != chainActive.Tip())
dfcf8255
MT
1048 {
1049 do {
dfcf8255 1050 pindexPrev = chainActive.Tip();
3da69a31
MT
1051 MilliSleep(5000 + rand() % 5000);
1052 } while (pindexPrev != chainActive.Tip());
dfcf8255 1053 }
42181656 1054
1055 // Create new block
1056 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
42181656 1057 if ( Mining_height != pindexPrev->nHeight+1 )
1058 {
1059 Mining_height = pindexPrev->nHeight+1;
1060 Mining_start = (uint32_t)time(NULL);
1061 }
1062
dbe656fe
MT
1063 if (lastChainTipPrinted != pindexPrev)
1064 {
1065 printf("Mining height %d\n", Mining_height);
1066 lastChainTipPrinted = pindexPrev;
1067 }
1068
1069 miningTimer.start();
42181656 1070
1071#ifdef ENABLE_WALLET
1072 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
1073#else
1074 CBlockTemplate *ptr = CreateNewBlockWithKey();
1075#endif
1076 if ( ptr == 0 )
1077 {
1078 static uint32_t counter;
1079 if ( counter++ < 100 )
1080 fprintf(stderr,"created illegal block, retry\n");
1081 continue;
1082 }
dbe656fe 1083
42181656 1084 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
1085 if (!pblocktemplate.get())
1086 {
1087 if (GetArg("-mineraddress", "").empty()) {
05f6e633 1088 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
1089 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1090 } else {
1091 // Should never reach here, because -mineraddress validity is checked in init.cpp
05f6e633 1092 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
42181656 1093 }
1094 return;
1095 }
1096 CBlock *pblock = &pblocktemplate->block;
1097 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1098 {
1099 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
1100 {
1101 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1102 {
1103 static uint32_t counter;
1104 if ( counter++ < 10 )
1105 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1106 sleep(10);
1107 continue;
1108 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1109 }
1110 }
1111 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
1112 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
1113 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
1114 //
1115 // Search
1116 //
1117 uint32_t savebits; int64_t nStart = GetTime();
1118
1119 pblock->nSolution = solnPlaceholder;
1120 savebits = pblock->nBits;
1121 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
1122 arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]);
1123
1124 Mining_start = 0;
ef70c5b2 1125
ef70c5b2 1126 if ( pindexPrev != chainActive.Tip() )
05f6e633 1127 {
dbe656fe
MT
1128 if (lastChainTipPrinted != chainActive.Tip())
1129 {
1130 lastChainTipPrinted = chainActive.Tip();
1131 printf("Block %d added to chain\n", lastChainTipPrinted->nHeight);
1132 }
6176a421 1133 MilliSleep(250);
05f6e633 1134 continue;
1135 }
ef70c5b2 1136
135fa24e 1137 if ( ASSETCHAINS_STAKED != 0 )
1138 {
1139 int32_t percPoS,z;
1140 hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED);
1141 for (z=31; z>=0; z--)
1142 fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]);
1143 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
1144 }
1145
42181656 1146 while (true)
1147 {
dbe656fe
MT
1148 arith_uint256 arNonce = UintToArith256(pblock->nNonce);
1149
1150 // for speed check 16 mega hash at a time
1151 for (int i = 0; i < 0x1000000; i++)
42181656 1152 {
1153 solutionTargetChecks.increment();
1154
dbe656fe
MT
1155 // Update nNonce
1156 *((unsigned char *)&(pblock->nNonce)) = i & 0xff;
1157 *(((unsigned char *)&(pblock->nNonce))+1) = (i >> 8) & 0xff;
1158 *(((unsigned char *)&(pblock->nNonce))+2) = (i >> 16) & 0xff;
42181656 1159
1160 if ( UintToArith256(pblock->GetHash()) <= hashTarget )
1161 {
1162 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1163
ef70c5b2 1164 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
1165 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
1166
135fa24e 1167 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
42181656 1168 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
14d104e9 1169 printf("Found block %d \n", Mining_height );
a62041d9 1170 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
ef70c5b2 1171 printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str());
1172 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
1173 printf("- timelocked until block %i\n", unlockTime);
1174 else
1175 printf("\n");
1176
42181656 1177#ifdef ENABLE_WALLET
1178 ProcessBlockFound(pblock, *pwallet, reservekey);
1179#else
1180 ProcessBlockFound(pblock));
1181#endif
1182 SetThreadPriority(THREAD_PRIORITY_LOWEST);
42181656 1183 break;
1184 }
dbe656fe
MT
1185 // check periodically if we're stale
1186 if (!(i % ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]))
42181656 1187 {
dbe656fe 1188 if ( pindexPrev != chainActive.Tip() )
ef70c5b2 1189 {
dbe656fe
MT
1190 if (lastChainTipPrinted != chainActive.Tip())
1191 {
1192 lastChainTipPrinted = chainActive.Tip();
1193 printf("Block %d added to chain\n", lastChainTipPrinted->nHeight);
1194 }
ef70c5b2 1195 break;
1196 }
42181656 1197 }
1198 }
1199
1200 // Check for stop or if block needs to be rebuilt
1201 boost::this_thread::interruption_point();
1202
1203 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1204 {
1205 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
1206 {
ef70c5b2 1207 fprintf(stderr,"no nodes, attempting reconnect\n");
42181656 1208 break;
1209 }
1210 }
1211
dbe656fe 1212 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
42181656 1213 {
dbe656fe 1214 fprintf(stderr,"timeout, retrying\n");
42181656 1215 break;
1216 }
1217
dbe656fe 1218 if ( pindexPrev != chainActive.Tip() )
42181656 1219 {
dbe656fe
MT
1220 if (lastChainTipPrinted != chainActive.Tip())
1221 {
1222 lastChainTipPrinted = chainActive.Tip();
1223 printf("Block %d added to chain\n", lastChainTipPrinted->nHeight);
1224 }
42181656 1225 break;
1226 }
1227
dbe656fe 1228 if ((UintToArith256(pblock->nNonce) & mask) == mask)
42181656 1229 {
dbe656fe 1230 printf("%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576);
42181656 1231 break;
1232 }
1233
1234 pblock->nBits = savebits;
1235 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1236 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1237 {
1238 // Changing pblock->nTime can change work required on testnet:
1239 hashTarget.SetCompact(pblock->nBits);
1240 }
1241 }
1242 }
1243 }
1244 catch (const boost::thread_interrupted&)
1245 {
1246 miningTimer.stop();
1247 LogPrintf("KomodoMiner terminated\n");
1248 throw;
1249 }
1250 catch (const std::runtime_error &e)
1251 {
1252 miningTimer.stop();
1253 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1254 return;
1255 }
1256 miningTimer.stop();
1257}
1258
8e8b6d70 1259#ifdef ENABLE_WALLET
d247a5d1 1260void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
1261#else
1262void static BitcoinMiner()
1263#endif
d247a5d1 1264{
2e500f50 1265 LogPrintf("KomodoMiner started\n");
d247a5d1 1266 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 1267 RenameThread("komodo-miner");
bebe7282 1268 const CChainParams& chainparams = Params();
e9e70b95 1269
8e8b6d70
JG
1270#ifdef ENABLE_WALLET
1271 // Each thread has its own key
d247a5d1 1272 CReserveKey reservekey(pwallet);
8e8b6d70 1273#endif
e9e70b95 1274
8e8b6d70 1275 // Each thread has its own counter
d247a5d1 1276 unsigned int nExtraNonce = 0;
e9e70b95 1277
e9574728
JG
1278 unsigned int n = chainparams.EquihashN();
1279 unsigned int k = chainparams.EquihashK();
8683bd8d 1280 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
b7ba6413 1281 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 1282 {
1283 sleep(1);
4e624c04 1284 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
1285 break;
755ead98 1286 }
8683bd8d 1287 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
e9e70b95 1288
755ead98 1289 std::string solver;
e1e65cef 1290 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
e9e70b95 1291 solver = "tromp";
e1e65cef 1292 //else solver = "default";
5f0009b2 1293 assert(solver == "tromp" || solver == "default");
c7aaab7a 1294 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 1295 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 1296 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
1297 std::mutex m_cs;
1298 bool cancelSolver = false;
1299 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
e9e70b95 1300 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
1301 std::lock_guard<std::mutex> lock{m_cs};
1302 cancelSolver = true;
1303 }
1304 );
07be8f7e 1305 miningTimer.start();
e9e70b95 1306
0655fac0 1307 try {
ad84148d 1308 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 1309 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 1310 while (true)
1311 {
2c70b583 1312 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 1313 {
a96fd7b5 1314 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
1315 // break;
0655fac0
PK
1316 // Busy-wait for the network to come online so we don't waste time mining
1317 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 1318 miningTimer.stop();
bba7c249
GM
1319 do {
1320 bool fvNodesEmpty;
1321 {
373668be 1322 //LOCK(cs_vNodes);
bba7c249
GM
1323 fvNodesEmpty = vNodes.empty();
1324 }
269fe243 1325 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 1326 break;
f8e367eb 1327 MilliSleep(5000);
ad84148d 1328 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
e9e70b95 1329
bba7c249 1330 } while (true);
ad84148d 1331 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 1332 miningTimer.start();
0655fac0 1333 }
f70ced6a 1334 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
e9e70b95 1335 {
1336 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
1337 sleep(3);
1338 }*/
0655fac0
PK
1339 //
1340 // Create new block
1341 //
1342 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 1343 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 1344 if ( Mining_height != pindexPrev->nHeight+1 )
1345 {
1346 Mining_height = pindexPrev->nHeight+1;
1347 Mining_start = (uint32_t)time(NULL);
1348 }
8e9ef91c 1349 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 1350 {
40304479 1351 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2825c0b5 1352 sleep(3);
1353 }
135fa24e 1354
8e8b6d70 1355#ifdef ENABLE_WALLET
135fa24e 1356 // notaries always default to staking
1357 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, (ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0));
8e8b6d70 1358#else
945f015d 1359 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 1360#endif
08d0b73c 1361 if ( ptr == 0 )
1362 {
d0f7ead0 1363 static uint32_t counter;
5bb3d0fe 1364 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 1365 fprintf(stderr,"created illegal block, retry\n");
8fc79ac9 1366 sleep(1);
d0f7ead0 1367 continue;
08d0b73c 1368 }
1369 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 1370 if (!pblocktemplate.get())
6c37f7fd 1371 {
8e8b6d70 1372 if (GetArg("-mineraddress", "").empty()) {
945f015d 1373 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
1374 } else {
1375 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 1376 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 1377 }
0655fac0 1378 return;
6c37f7fd 1379 }
0655fac0 1380 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 1381 if ( ASSETCHAINS_SYMBOL[0] != 0 )
1382 {
42181656 1383 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
16c7bf6b 1384 {
8683bd8d 1385 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
1386 {
1387 static uint32_t counter;
1388 if ( counter++ < 10 )
1389 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1390 sleep(10);
1391 continue;
1392 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
1393 }
16c7bf6b 1394 }
0655fac0 1395 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 1396 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
1397 //
1398 // Search
1399 //
a30dd993 1400 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
404391b5 1401 savebits = pblock->nBits;
88287857 1402 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
f0100e72 1403 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 1404 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 1405 {
fda5f849 1406 j = 65;
5a471ba9 1407 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 1408 {
4fff8a63 1409 int32_t dispflag = 0;
ef70c5b2 1410 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &&notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
4fff8a63 1411 dispflag = 1;
a30dd993 1412 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
29e60e48 1413 if ( nonzpkeys > 0 )
1414 {
ccb71a6e 1415 for (i=0; i<33; i++)
1416 if( pubkeys[0][i] != 0 )
1417 break;
1418 if ( i == 33 )
1419 externalflag = 1;
1420 else externalflag = 0;
e4a383e3 1421 if ( NOTARY_PUBKEY33[0] != 0 )
b176c125 1422 {
345e545e 1423 for (i=1; i<66; i++)
1424 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
1425 break;
6494f040 1426 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
1427 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
2c7ad758 1428 for (j=gpucount=0; j<65; j++)
1429 {
4fff8a63 1430 if ( dispflag != 0 )
e4a383e3 1431 {
1432 if ( mids[j] >= 0 )
1433 fprintf(stderr,"%d ",mids[j]);
1434 else fprintf(stderr,"GPU ");
1435 }
2c7ad758 1436 if ( mids[j] == -1 )
1437 gpucount++;
1438 }
b000fa04 1439 if ( gpucount > j/2 )
f0100e72 1440 {
dd98c02d 1441 double delta;
d2d3c766 1442 if ( notaryid < 0 )
1443 i = (rand() % 64);
1444 else i = ((Mining_height + notaryid) % 64);
b000fa04 1445 delta = sqrt((double)gpucount - j/2) / 2.;
dd98c02d 1446 roundrobin_delay += ((delta * i) / 64) - delta;
67478d4a 1447 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
f0100e72 1448 }
4fff8a63 1449 if ( dispflag != 0 )
2c7ba74d 1450 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
b176c125 1451 }
29e60e48 1452 for (j=0; j<65; j++)
1453 if ( mids[j] == notaryid )
1454 break;
49b49585 1455 if ( j == 65 )
1456 KOMODO_LASTMINED = 0;
965f0f7e 1457 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 1458 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 1459 {
88287857 1460 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
fda5f849 1461 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
1462 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 1463 } else Mining_start = 0;
d7d27bb3 1464 } else Mining_start = 0;
deba7f20 1465 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
e725f1cb 1466 {
deba7f20 1467 int32_t percPoS,z;
d9935f2b 1468 /*if ( Mining_height <= 100 )
16cd9f2d 1469 {
c966741f 1470 sleep(60);
1471 continue;
16c7bf6b 1472 }*/
18443f69 1473 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
deba7f20 1474 for (z=31; z>=0; z--)
8fbee929 1475 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
b509fdae 1476 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
deba7f20 1477 }
e725f1cb 1478 while (true)
1479 {
16c7bf6b 1480 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
e9e70b95 1481 {
1482 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
1483 sleep(10);
1484 break;
1485 }*/
7213c0b1 1486 // Hash state
8c22eb46 1487 KOMODO_CHOSEN_ONE = 0;
42181656 1488
7213c0b1 1489 crypto_generichash_blake2b_state state;
e9574728 1490 EhInitialiseState(n, k, state);
7213c0b1
JG
1491 // I = the block header minus nonce and solution.
1492 CEquihashInput I{*pblock};
1493 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1494 ss << I;
7213c0b1
JG
1495 // H(I||...
1496 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
1497 // H(I||V||...
1498 crypto_generichash_blake2b_state curr_state;
1499 curr_state = state;
7a4c01c9 1500 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 1501 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 1502 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
18443f69 1503 arith_uint256 hashTarget;
1f722359 1504 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED <= 100 )
18443f69 1505 hashTarget = HASHTarget_POW;
1506 else hashTarget = HASHTarget;
5be6abbf 1507 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 1508#ifdef ENABLE_WALLET
e9e70b95 1509 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1510#else
e9e70b95 1511 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 1512#endif
e9e70b95 1513 (std::vector<unsigned char> soln) {
c21c6306 1514 int32_t z; arith_uint256 h; CBlock B;
51eb5273
JG
1515 // Write the solution to the hash and compute the result.
1516 LogPrint("pow", "- Checking solution against target\n");
8e165d57 1517 pblock->nSolution = soln;
e7d59bbc 1518 solutionTargetChecks.increment();
eff2c3a3 1519 B = *pblock;
1520 h = UintToArith256(B.GetHash());
c21c6306 1521 if ( h > hashTarget )
51eb5273 1522 return false;
eff2c3a3 1523 /*for (z=31; z>=16; z--)
02c30aac 1524 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
aea2d1aa 1525 fprintf(stderr," mined ");
1526 for (z=31; z>=16; z--)
18443f69 1527 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
aea2d1aa 1528 fprintf(stderr," hashTarget ");
1529 for (z=31; z>=16; z--)
18443f69 1530 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
eff2c3a3 1531 fprintf(stderr," POW\n");*/
6181f7d5 1532 if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
d7d27bb3 1533 {
97e9d76e 1534 fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
596b05ba 1535 while ( GetAdjustedTime() < B.nTime-2 )
8e9ef91c 1536 {
eb1ba5a0 1537 sleep(1);
4cc387ec 1538 if ( chainActive.Tip()->nHeight >= Mining_height )
1539 {
1540 fprintf(stderr,"new block arrived\n");
1541 return(false);
1542 }
8e9ef91c 1543 }
eb1ba5a0 1544 }
8e9ef91c 1545 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 1546 {
9703f8a0 1547 if ( NOTARY_PUBKEY33[0] != 0 )
8e9ef91c 1548 {
26810a26 1549 int32_t r;
9703f8a0 1550 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
596b05ba 1551 MilliSleep((rand() % (r * 1000)) + 1000);
ef70c5b2 1552 }
e5430f52 1553 }
8e9ef91c 1554 else
d7d27bb3 1555 {
deba7f20 1556 if ( NOTARY_PUBKEY33[0] != 0 )
1557 {
ef70c5b2 1558 printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
eff2c3a3 1559 while ( GetAdjustedTime() < B.nTime )
deba7f20 1560 sleep(1);
1561 }
68d0354d 1562 else
1563 {
286d95b1 1564 uint256 tmp = B.GetHash();
b7aaca4b 1565 int32_t z; for (z=31; z>=0; z--)
1566 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1567 fprintf(stderr," mined block!\n");
68d0354d 1568 }
d7d27bb3 1569 }
8fc79ac9 1570 CValidationState state;
1571 if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
d2d3c766 1572 {
8fc79ac9 1573 h = UintToArith256(B.GetHash());
1574 for (z=31; z>=0; z--)
1575 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1576 fprintf(stderr," Invalid block mined, try again\n");
1577 return(false);
d2d3c766 1578 }
b3183e3e 1579 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
1580 // Found a solution
1581 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 1582 LogPrintf("KomodoMiner:\n");
eff2c3a3 1583 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 1584#ifdef ENABLE_WALLET
eff2c3a3 1585 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
8e8b6d70 1586#else
eff2c3a3 1587 if (ProcessBlockFound(&B)) {
8e8b6d70 1588#endif
e9e70b95 1589 // Ignore chain updates caused by us
1590 std::lock_guard<std::mutex> lock{m_cs};
1591 cancelSolver = false;
1592 }
1593 KOMODO_CHOSEN_ONE = 0;
1594 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1595 // In regression test mode, stop mining after a block is found.
1596 if (chainparams.MineBlocksOnDemand()) {
1597 // Increment here because throwing skips the call below
1598 ehSolverRuns.increment();
1599 throw boost::thread_interrupted();
1600 }
1601 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1602 // sleep(1800);
1603 return true;
1604 };
1605 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
a6a0d913 1606 std::lock_guard<std::mutex> lock{m_cs};
e9e70b95 1607 return cancelSolver;
1608 };
1609
1610 // TODO: factor this out into a function with the same API for each solver.
1611 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1612 // Create solver and initialize it.
1613 equi eq(1);
1614 eq.setstate(&curr_state);
1615
1616 // Initialization done, start algo driver.
1617 eq.digit0(0);
c7aaab7a 1618 eq.xfull = eq.bfull = eq.hfull = 0;
e9e70b95 1619 eq.showbsizes(0);
1620 for (u32 r = 1; r < WK; r++) {
1621 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1622 eq.xfull = eq.bfull = eq.hfull = 0;
1623 eq.showbsizes(r);
c7aaab7a 1624 }
e9e70b95 1625 eq.digitK(0);
1626 ehSolverRuns.increment();
1627
1628 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1629 for (size_t s = 0; s < eq.nsols; s++) {
1630 LogPrint("pow", "Checking solution %d\n", s+1);
1631 std::vector<eh_index> index_vector(PROOFSIZE);
1632 for (size_t i = 0; i < PROOFSIZE; i++) {
1633 index_vector[i] = eq.sols[s][i];
1634 }
1635 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1636
1637 if (validBlock(sol_char)) {
1638 // If we find a POW solution, do not try other solutions
1639 // because they become invalid as we created a new block in blockchain.
1640 break;
1641 }
1642 }
1643 } else {
1644 try {
1645 // If we find a valid block, we rebuild
1646 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1647 ehSolverRuns.increment();
1648 if (found) {
997ddd92 1649 int32_t i; uint256 hash = pblock->GetHash();
e9e70b95 1650 for (i=0; i<32; i++)
1651 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1652 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1653 FOUND_BLOCK = 1;
1654 KOMODO_MAYBEMINED = Mining_height;
1655 break;
1656 }
1657 } catch (EhSolverCancelledException&) {
1658 LogPrint("pow", "Equihash solver cancelled\n");
1659 std::lock_guard<std::mutex> lock{m_cs};
1660 cancelSolver = false;
c7aaab7a
DH
1661 }
1662 }
e9e70b95 1663
1664 // Check for stop or if block needs to be rebuilt
1665 boost::this_thread::interruption_point();
1666 // Regtest mode doesn't require peers
1667 if ( FOUND_BLOCK != 0 )
1668 {
1669 FOUND_BLOCK = 0;
1670 fprintf(stderr,"FOUND_BLOCK!\n");
1671 //sleep(2000);
1672 }
1673 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1674 {
1675 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1676 {
1677 fprintf(stderr,"no nodes, break\n");
c7aaab7a 1678 break;
a6df7ab5 1679 }
c7aaab7a 1680 }
997ddd92 1681 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
10694486 1682 {
e9e70b95 1683 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1684 fprintf(stderr,"0xffff, break\n");
d90cef0b 1685 break;
10694486 1686 }
e9e70b95 1687 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1688 {
1689 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1690 fprintf(stderr,"timeout, break\n");
1691 break;
1692 }
1693 if ( pindexPrev != chainActive.Tip() )
1694 {
1695 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1696 fprintf(stderr,"Tip advanced, break\n");
1697 break;
1698 }
1699 // Update nNonce and nTime
1700 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1701 pblock->nBits = savebits;
18dd6a3b 1702 /*if ( NOTARY_PUBKEY33[0] == 0 )
e9e70b95 1703 {
f8f740a9 1704 int32_t percPoS;
23fc88bb 1705 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1706 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1707 {
1708 // Changing pblock->nTime can change work required on testnet:
1709 HASHTarget.SetCompact(pblock->nBits);
18443f69 1710 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
23fc88bb 1711 }
18dd6a3b 1712 }*/
48265f3c 1713 }
d247a5d1
JG
1714 }
1715 }
e9e70b95 1716 catch (const boost::thread_interrupted&)
1717 {
1718 miningTimer.stop();
1719 c.disconnect();
1720 LogPrintf("KomodoMiner terminated\n");
1721 throw;
1722 }
1723 catch (const std::runtime_error &e)
1724 {
1725 miningTimer.stop();
1726 c.disconnect();
1727 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1728 return;
1729 }
07be8f7e 1730 miningTimer.stop();
5e9b555f 1731 c.disconnect();
bba7c249 1732 }
e9e70b95 1733
8e8b6d70 1734#ifdef ENABLE_WALLET
e9e70b95 1735 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70 1736#else
e9e70b95 1737 void GenerateBitcoins(bool fGenerate, int nThreads)
8e8b6d70 1738#endif
d247a5d1 1739 {
e9e70b95 1740 static boost::thread_group* minerThreads = NULL;
1741
1742 if (nThreads < 0)
1743 nThreads = GetNumCores();
1744
1745 if (minerThreads != NULL)
1746 {
1747 minerThreads->interrupt_all();
1748 delete minerThreads;
1749 minerThreads = NULL;
1750 }
135fa24e 1751
1f722359 1752 if ((nThreads == 0 && ASSETCHAINS_LWMAPOS == 0) || !fGenerate)
e9e70b95 1753 return;
135fa24e 1754
e9e70b95 1755 minerThreads = new boost::thread_group();
135fa24e 1756
1757#ifdef ENABLE_WALLET
1f722359 1758 if (ASSETCHAINS_LWMAPOS != 0)
135fa24e 1759 {
1760 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
1761 }
1762#endif
1763
e9e70b95 1764 for (int i = 0; i < nThreads; i++) {
135fa24e 1765
8e8b6d70 1766#ifdef ENABLE_WALLET
135fa24e 1767 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1768 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1769 else
1770 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
8e8b6d70 1771#else
135fa24e 1772 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
1773 minerThreads->create_thread(&BitcoinMiner);
1774 else
1775 minerThreads->create_thread(&BitcoinMiner_noeq);
8e8b6d70 1776#endif
e9e70b95 1777 }
8e8b6d70 1778 }
e9e70b95 1779
2cc0a252 1780#endif // ENABLE_MINING
This page took 0.707772 seconds and 4 git commands to generate.