]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Test
[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"
19#endif
85aab2a0 20#include "hash.h"
d247a5d1 21#include "main.h"
a6df7ab5 22#include "metrics.h"
51ed9ec9 23#include "net.h"
df852d2b 24#include "pow.h"
bebe7282 25#include "primitives/transaction.h"
8e165d57 26#include "random.h"
22c4272b 27#include "timedata.h"
8e8b6d70 28#include "ui_interface.h"
ad49c256
WL
29#include "util.h"
30#include "utilmoneystr.h"
df840de5 31#ifdef ENABLE_WALLET
50c72f23 32#include "wallet/wallet.h"
df840de5 33#endif
09eb201b 34
fdda3c50
JG
35#include "sodium.h"
36
ad49c256 37#include <boost/thread.hpp>
a3c26c2e 38#include <boost/tuple/tuple.hpp>
8e8b6d70
JG
39#ifdef ENABLE_MINING
40#include <functional>
41#endif
5a360a5c 42#include <mutex>
ad49c256 43
09eb201b 44using namespace std;
7b4737c8 45
d247a5d1
JG
46//////////////////////////////////////////////////////////////////////////////
47//
48// BitcoinMiner
49//
50
c6cb21d1
GA
51//
52// Unconfirmed transactions in the memory pool often depend on other
53// transactions in the memory pool. When we select transactions from the
54// pool, we select by highest priority or fee rate, so we might consider
55// transactions that depend on transactions that aren't yet in the block.
56// The COrphan class keeps track of these 'temporary orphans' while
57// CreateBlock is figuring out which transactions to include.
58//
d247a5d1
JG
59class COrphan
60{
61public:
4d707d51 62 const CTransaction* ptx;
d247a5d1 63 set<uint256> setDependsOn;
c6cb21d1 64 CFeeRate feeRate;
02bec4b2 65 double dPriority;
d247a5d1 66
c6cb21d1 67 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 68 {
d247a5d1 69 }
d247a5d1
JG
70};
71
51ed9ec9
BD
72uint64_t nLastBlockTx = 0;
73uint64_t nLastBlockSize = 0;
d247a5d1 74
c6cb21d1
GA
75// We want to sort transactions by priority and fee rate, so:
76typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
77class TxPriorityCompare
78{
79 bool byFee;
0655fac0 80
d247a5d1
JG
81public:
82 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
0655fac0 83
d247a5d1
JG
84 bool operator()(const TxPriority& a, const TxPriority& b)
85 {
86 if (byFee)
87 {
88 if (a.get<1>() == b.get<1>())
89 return a.get<0>() < b.get<0>();
90 return a.get<1>() < b.get<1>();
91 }
92 else
93 {
94 if (a.get<0>() == b.get<0>())
95 return a.get<1>() < b.get<1>();
96 return a.get<0>() < b.get<0>();
97 }
98 }
99};
100
bebe7282 101void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 102{
103 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
22c4272b 104}
105
5416af1d 106#include "komodo_defs.h"
107
16c7bf6b 108extern 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;
44d2da57 109extern uint64_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED;
7c130297 110extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
f24b36ca 111extern std::string NOTARY_PUBKEY;
94a465a6 112extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
f24b36ca 113uint32_t Mining_start,Mining_height;
8683bd8d 114int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
b4810651 115int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
9cc05f24 116uint64_t komodo_paxtotal();
d63fdb34 117int32_t komodo_baseid(char *origbase);
654dfaaf 118int32_t komodo_is_issuer();
635dd34d 119int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
48a3cd18 120int32_t komodo_isrealtime(int32_t *kmdheightp);
3bc88f14 121int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
6ae23274 122uint64_t komodo_commission(const CBlock &block);
357e4ca5 123int32_t komodo_staked(uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
a4a40a38 124
48265f3c 125CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
d247a5d1 126{
9339a0cb 127 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
d247a5d1 128 // Create new block
08c58194 129 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 130 if(!pblocktemplate.get())
1b5b89ba 131 {
132 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 133 return NULL;
1b5b89ba 134 }
d247a5d1 135 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
41ebe9c6 136 if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
a5e36fdd 137 {
48a3cd18 138 isrealtime = komodo_isrealtime(&kmdheight);
3da07d2e 139 deposits = komodo_paxtotal();
5ba0ce9d 140 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
ec7ad5f6 141 {
79562bf3 142 deposits = komodo_paxtotal();
16c7bf6b 143 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
79562bf3 144 {
bbaa688c 145 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
79562bf3 146 }
2bec17cb 147 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
4a21ccd2 148 {
eb928486 149 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 150 break;
4a21ccd2 151 }
6fd0ae11 152 sleep(10);
ec7ad5f6 153 }
f24b36ca 154 KOMODO_ON_DEMAND = 0;
16cd9f2d 155 if ( 0 && deposits != 0 )
79562bf3 156 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());
a5e36fdd 157 }
dbca89b7
GA
158 // -regtest only: allow overriding block.nVersion with
159 // -blockversion=N to test forking scenarios
160 if (Params().MineBlocksOnDemand())
161 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
162
4949004d
PW
163 // Add dummy coinbase tx as first transaction
164 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
165 pblocktemplate->vTxFees.push_back(-1); // updated at end
166 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
167
168 // Largest block you're willing to create:
ad898b40 169 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
170 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
171 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
172
173 // How much of the block should be dedicated to high-priority transactions,
174 // included regardless of the fees they pay
175 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
176 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
177
178 // Minimum block size you want to create; block will be filled with free transactions
179 // until there are no more or the block reaches this size:
037b4f14 180 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1
JG
181 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
182
183 // Collect memory pool transactions into the block
a372168e 184 CAmount nFees = 0;
0655fac0 185
d247a5d1
JG
186 {
187 LOCK2(cs_main, mempool.cs);
48265f3c 188 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 189 const int nHeight = pindexPrev->nHeight + 1;
be126699 190 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
75a4d512 191 pblock->nTime = GetAdjustedTime();
a1d3c6fb 192 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
7c70438d 193 CCoinsViewCache view(pcoinsTip);
f9155fec 194 uint32_t expired; uint64_t commission;
6ff77181 195
d247a5d1
JG
196 // Priority order to process transactions
197 list<COrphan> vOrphan; // list memory doesn't move
198 map<uint256, vector<COrphan*> > mapDependers;
199 bool fPrintPriority = GetBoolArg("-printpriority", false);
200
201 // This vector will be sorted into a priority queue:
202 vector<TxPriority> vecPriority;
203 vecPriority.reserve(mempool.mapTx.size());
e328fa32 204 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
4d707d51 205 mi != mempool.mapTx.end(); ++mi)
d247a5d1 206 {
e328fa32 207 const CTransaction& tx = mi->GetTx();
a1d3c6fb
MF
208
209 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
210 ? nMedianTimePast
211 : pblock->GetBlockTime();
212
9bb37bf0 213 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
14aa6cc0 214 continue;
bbaa0f9d 215 if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,2) < 0 )
6ff77181 216 {
14aa6cc0 217 fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n");
d247a5d1 218 continue;
14aa6cc0 219 }
d247a5d1
JG
220 COrphan* porphan = NULL;
221 double dPriority = 0;
a372168e 222 CAmount nTotalIn = 0;
d247a5d1
JG
223 bool fMissingInputs = false;
224 BOOST_FOREACH(const CTxIn& txin, tx.vin)
225 {
226 // Read prev transaction
227 if (!view.HaveCoins(txin.prevout.hash))
228 {
229 // This should never happen; all transactions in the memory
230 // pool should connect to either transactions in the chain
231 // or other transactions in the memory pool.
232 if (!mempool.mapTx.count(txin.prevout.hash))
233 {
881a85a2 234 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
235 if (fDebug) assert("mempool transaction missing input" == 0);
236 fMissingInputs = true;
237 if (porphan)
238 vOrphan.pop_back();
239 break;
240 }
241
242 // Has to wait for dependencies
243 if (!porphan)
244 {
245 // Use list for automatic deletion
246 vOrphan.push_back(COrphan(&tx));
247 porphan = &vOrphan.back();
248 }
249 mapDependers[txin.prevout.hash].push_back(porphan);
250 porphan->setDependsOn.insert(txin.prevout.hash);
e328fa32 251 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
252 continue;
253 }
629d75fa
PW
254 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
255 assert(coins);
d247a5d1 256
a372168e 257 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1
JG
258 nTotalIn += nValueIn;
259
b867e409 260 int nConf = nHeight - coins->nHeight;
d247a5d1
JG
261
262 dPriority += (double)nValueIn * nConf;
263 }
2b2bc69e
SB
264 nTotalIn += tx.GetJoinSplitValueIn();
265
d247a5d1
JG
266 if (fMissingInputs) continue;
267
d6eb2599 268 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 269 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 270 dPriority = tx.ComputePriority(dPriority, nTxSize);
d247a5d1 271
805344dc 272 uint256 hash = tx.GetHash();
2a72d459
LD
273 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
274
c6cb21d1 275 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
d247a5d1
JG
276
277 if (porphan)
278 {
279 porphan->dPriority = dPriority;
c6cb21d1 280 porphan->feeRate = feeRate;
d247a5d1
JG
281 }
282 else
e328fa32 283 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
d247a5d1
JG
284 }
285
286 // Collect transactions into block
51ed9ec9
BD
287 uint64_t nBlockSize = 1000;
288 uint64_t nBlockTx = 0;
355ca565 289 int64_t interest;
d247a5d1
JG
290 int nBlockSigOps = 100;
291 bool fSortedByFee = (nBlockPrioritySize <= 0);
292
293 TxPriorityCompare comparer(fSortedByFee);
294 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
295
296 while (!vecPriority.empty())
297 {
298 // Take highest priority transaction off the priority queue:
299 double dPriority = vecPriority.front().get<0>();
c6cb21d1 300 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 301 const CTransaction& tx = *(vecPriority.front().get<2>());
d247a5d1
JG
302
303 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
304 vecPriority.pop_back();
305
306 // Size limits
307 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
308 if (nBlockSize + nTxSize >= nBlockMaxSize)
309 continue;
310
311 // Legacy limits on sigOps:
312 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
a4a40a38 313 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
d247a5d1
JG
314 continue;
315
316 // Skip free transactions if we're past the minimum block size:
805344dc 317 const uint256& hash = tx.GetHash();
2a72d459 318 double dPriorityDelta = 0;
a372168e 319 CAmount nFeeDelta = 0;
2a72d459 320 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 321 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
d247a5d1
JG
322 continue;
323
2a72d459 324 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
325 // transactions:
326 if (!fSortedByFee &&
327 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
328 {
329 fSortedByFee = true;
330 comparer = TxPriorityCompare(fSortedByFee);
331 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
332 }
333
334 if (!view.HaveInputs(tx))
335 continue;
336
1141b678 337 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
d247a5d1
JG
338
339 nTxSigOps += GetP2SHSigOpCount(tx, view);
a4a40a38 340 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
d247a5d1
JG
341 continue;
342
68f7d1d7
PT
343 // Note that flags: we don't want to set mempool/IsStandard()
344 // policy here, but we still have to ensure that the block we
345 // create only contains transactions that are valid in new blocks.
d247a5d1 346 CValidationState state;
6514771a 347 PrecomputedTransactionData txdata(tx);
be126699 348 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
d247a5d1
JG
349 continue;
350
8cb98d91 351 UpdateCoins(tx, view, nHeight);
d247a5d1
JG
352
353 // Added
354 pblock->vtx.push_back(tx);
355 pblocktemplate->vTxFees.push_back(nTxFees);
356 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
357 nBlockSize += nTxSize;
358 ++nBlockTx;
359 nBlockSigOps += nTxSigOps;
360 nFees += nTxFees;
361
362 if (fPrintPriority)
363 {
3f0813b3 364 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1
JG
365 }
366
367 // Add transactions that depend on this one to the priority queue
368 if (mapDependers.count(hash))
369 {
370 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
371 {
372 if (!porphan->setDependsOn.empty())
373 {
374 porphan->setDependsOn.erase(hash);
375 if (porphan->setDependsOn.empty())
376 {
c6cb21d1 377 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
378 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
379 }
380 }
381 }
382 }
383 }
384
385 nLastBlockTx = nBlockTx;
386 nLastBlockSize = nBlockSize;
9339a0cb 387 blocktime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
357e4ca5 388 pblock->nTime = blocktime;
389 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
390 LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
a4a40a38 391 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
392 {
69530bb2 393 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
acb3822e 394 if ( (siglen= komodo_staked(pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
a4a40a38 395 {
396 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
66b4e563 397 CAmount txfees = 0;
a4a40a38 398 txStaked.vin.resize(1);
399 txStaked.vout.resize(1);
69530bb2 400 for (i=0; i<32; i++)
401 ((uint8_t *)&revtxid)[i] = ((uint8_t *)&utxotxid)[31 - i];
402 txStaked.vin[0].prevout.hash = revtxid;
a4a40a38 403 txStaked.vin[0].prevout.n = utxovout;
44d2da57 404 txStaked.vin[0].scriptSig.resize(siglen);
405 ptr = (uint8_t *)txStaked.vin[0].scriptSig.data();
406 for (i=0; i<siglen; i++)
407 ptr[i] = utxosig[i];
a4a40a38 408 txStaked.vout[0].scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
44d2da57 409 txStaked.vout[0].nValue = utxovalue - txfees;
9339a0cb 410 txStaked.nLockTime = blocktime;
a4a40a38 411
412 pblock->vtx.push_back(txStaked);
413 numsigs = GetLegacySigOpCount(txStaked);
414 pblocktemplate->vTxFees.push_back(txfees);
415 pblocktemplate->vTxSigOps.push_back(numsigs);
416 nFees += txfees;
9339a0cb 417 pblock->nTime = blocktime;
a4a40a38 418 }
419 }
d247a5d1 420
f3ffa3d2 421 // Create coinbase tx
072099d7 422 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
423 txNew.vin.resize(1);
424 txNew.vin[0].prevout.SetNull();
d581f229 425 txNew.vout.resize(1);
f3ffa3d2 426 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
c9b1071d 427 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
aa0b9e00 428 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9bb37bf0 429 txNew.nExpiryHeight = 0;
f3ffa3d2
SB
430 // Add fees
431 txNew.vout[0].nValue += nFees;
b867e409 432 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
6ae23274 433
8683bd8d 434 /*if ( ASSETCHAINS_SYMBOL[0] == 0 )
c9b1071d 435 {
8683bd8d 436 int32_t i,opretlen; uint8_t opret[256],*ptr;
44caf46a 437 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
c9b1071d 438 {
b4810651 439 if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed
d9a9d562 440 {
441 txNew.vout.resize(2);
442 txNew.vout[1].scriptPubKey.resize(opretlen);
443 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
444 for (i=0; i<opretlen; i++)
445 ptr[i] = opret[i];
446 txNew.vout[1].nValue = 0;
447 //fprintf(stderr,"opretlen.%d\n",opretlen);
768dccac 448 } //else printf("null opretlen for prices\n");
8683bd8d 449 }
c9b1071d 450 }
654dfaaf 451 else if ( komodo_is_issuer() != 0 )
c9b1071d 452 {
7322eaa0 453 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
1ecb8541 454 if ( txNew.vout.size() > 1 )
4a21ccd2 455 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
8683bd8d 456 }*/
8f3aa743 457
4949004d 458 pblock->vtx[0] = txNew;
852af44b 459 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission(pblocktemplate->block)) != 0 )
c000c9ca 460 {
461 int32_t i; uint8_t *ptr;
9ed1be03 462 txNew.vout.resize(2);
463 txNew.vout[1].nValue = commission;
464 txNew.vout[1].scriptPubKey.resize(35);
465 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
c000c9ca 466 ptr[0] = 33;
467 for (i=0; i<33; i++)
468 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
469 ptr[34] = OP_CHECKSIG;
146d2aa2 470 //printf("autocreate commision vout\n");
9ed1be03 471 pblock->vtx[0] = txNew;
c000c9ca 472 }
d247a5d1 473 pblocktemplate->vTxFees[0] = -nFees;
8e165d57
JG
474 // Randomise nonce
475 arith_uint256 nonce = UintToArith256(GetRandHash());
476 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
477 nonce <<= 32;
478 nonce >>= 16;
479 pblock->nNonce = ArithToUint256(nonce);
480
d247a5d1
JG
481 // Fill in header
482 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 483 pblock->hashReserved = uint256();
b366cab9 484 //UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
357e4ca5 485 //pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
fdda3c50 486 pblock->nSolution.clear();
d247a5d1
JG
487 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
488
c583e2a9 489 CValidationState state;
0af2786d 490 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
af805d53 491 {
d0f7ead0 492 static uint32_t counter;
493 if ( counter++ < 100 )
d4190a2a 494 fprintf(stderr,"warning: testblockvalidity failed\n");
14aa6cc0 495 return(0);
af805d53 496 }
d247a5d1
JG
497 }
498
499 return pblocktemplate.release();
500}
501
1a31463b 502/*
8e8b6d70
JG
503#ifdef ENABLE_WALLET
504boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
505#else
506boost::optional<CScript> GetMinerScriptPubKey()
507#endif
508{
509 CKeyID keyID;
510 CBitcoinAddress addr;
511 if (addr.SetString(GetArg("-mineraddress", ""))) {
512 addr.GetKeyID(keyID);
513 } else {
514#ifdef ENABLE_WALLET
515 CPubKey pubkey;
516 if (!reservekey.GetReservedKey(pubkey)) {
517 return boost::optional<CScript>();
518 }
519 keyID = pubkey.GetID();
520#else
521 return boost::optional<CScript>();
522#endif
523 }
524
525 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
526 return scriptPubKey;
527}
528
1a31463b 529#ifdef ENABLE_WALLET
48265f3c 530CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 531{
8e8b6d70
JG
532 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
533#else
534CBlockTemplate* CreateNewBlockWithKey()
535{
536 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
537#endif
acfa0333 538
8e8b6d70
JG
539 if (!scriptPubKey) {
540 return NULL;
541 }
542 return CreateNewBlock(*scriptPubKey);
945f015d 543}*/
acfa0333 544
c1de826f
JG
545//////////////////////////////////////////////////////////////////////////////
546//
547// Internal miner
548//
549
2cc0a252 550#ifdef ENABLE_MINING
c1de826f 551
d247a5d1
JG
552void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
553{
554 // Update nExtraNonce
555 static uint256 hashPrevBlock;
556 if (hashPrevBlock != pblock->hashPrevBlock)
557 {
558 nExtraNonce = 0;
559 hashPrevBlock = pblock->hashPrevBlock;
560 }
561 ++nExtraNonce;
562 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
563 CMutableTransaction txCoinbase(pblock->vtx[0]);
564 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
565 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
d247a5d1 566
4949004d 567 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
568 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
569}
570
4a85e067 571#ifdef ENABLE_WALLET
acfa0333
WL
572//////////////////////////////////////////////////////////////////////////////
573//
574// Internal miner
575//
acfa0333 576
48265f3c 577CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 578{
f6c647ed 579 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 580 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 581 {
7bfc207a 582 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 583 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 584 }
585 else
586 {
587 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 588 {
f6c647ed 589 return NULL;
1b5b89ba 590 }
f6c647ed 591 scriptPubKey.resize(35);
f66f65ec 592 ptr = (uint8_t *)pubkey.begin();
f6c647ed 593 script = (uint8_t *)scriptPubKey.data();
594 script[0] = 33;
595 for (i=0; i<33; i++)
596 script[i+1] = ptr[i];
597 script[34] = OP_CHECKSIG;
598 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
599 }
48265f3c 600 return CreateNewBlock(scriptPubKey);
acfa0333
WL
601}
602
945f015d 603
269d8ba0 604static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
605#else
606static bool ProcessBlockFound(CBlock* pblock)
607#endif // ENABLE_WALLET
d247a5d1 608{
81212588 609 LogPrintf("%s\n", pblock->ToString());
35915149 610 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
d247a5d1
JG
611
612 // Found a solution
613 {
614 LOCK(cs_main);
4c6d41b8 615 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
ba8419c7 616 {
617 uint256 hash; int32_t i;
618 hash = pblock->hashPrevBlock;
92266e99 619 for (i=31; i>=0; i--)
ba8419c7 620 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 621 fprintf(stderr," <- prev (stale)\n");
ba8419c7 622 hash = chainActive.Tip()->GetBlockHash();
92266e99 623 for (i=31; i>=0; i--)
ba8419c7 624 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 625 fprintf(stderr," <- chainTip (stale)\n");
ba8419c7 626
2e500f50 627 return error("KomodoMiner: generated block is stale");
ba8419c7 628 }
18e72167 629 }
d247a5d1 630
8e8b6d70 631#ifdef ENABLE_WALLET
18e72167 632 // Remove key from key pool
998397aa 633 if ( IS_KOMODO_NOTARY == 0 )
945f015d 634 {
635 if (GetArg("-mineraddress", "").empty()) {
636 // Remove key from key pool
637 reservekey.KeepKey();
638 }
8e8b6d70 639 }
18e72167 640 // Track how many getdata requests this block gets
438ba9c1 641 //if ( 0 )
18e72167
PW
642 {
643 LOCK(wallet.cs_wallet);
644 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 645 }
8e8b6d70 646#endif
d247a5d1 647
18e72167
PW
648 // Process this block the same as if we had received it from another node
649 CValidationState state;
35915149 650 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 651 return error("KomodoMiner: ProcessNewBlock, block not accepted");
18e72167 652
d793f94b 653 TrackMinedBlock(pblock->GetHash());
a6df7ab5 654
d247a5d1
JG
655 return true;
656}
657
078f6af1 658int32_t komodo_baseid(char *origbase);
8c654ec5 659int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
8ee93080 660int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 661extern int32_t KOMODO_LASTMINED;
8b51b9e4 662int32_t roundrobin_delay;
078f6af1 663
8e8b6d70 664#ifdef ENABLE_WALLET
d247a5d1 665void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
666#else
667void static BitcoinMiner()
668#endif
d247a5d1 669{
2e500f50 670 LogPrintf("KomodoMiner started\n");
d247a5d1 671 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 672 RenameThread("komodo-miner");
bebe7282 673 const CChainParams& chainparams = Params();
d247a5d1 674
8e8b6d70
JG
675#ifdef ENABLE_WALLET
676 // Each thread has its own key
d247a5d1 677 CReserveKey reservekey(pwallet);
8e8b6d70
JG
678#endif
679
680 // Each thread has its own counter
d247a5d1
JG
681 unsigned int nExtraNonce = 0;
682
e9574728
JG
683 unsigned int n = chainparams.EquihashN();
684 unsigned int k = chainparams.EquihashK();
8683bd8d 685 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
b7ba6413 686 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 687 {
688 sleep(1);
4e624c04 689 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
690 break;
755ead98 691 }
952b9905 692 //sleep(60);
8683bd8d 693 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
fdda3c50 694
755ead98 695 std::string solver;
e1e65cef 696 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
755ead98 697 solver = "tromp";
e1e65cef 698 //else solver = "default";
5f0009b2 699 assert(solver == "tromp" || solver == "default");
c7aaab7a 700 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 701 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 702 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
703 std::mutex m_cs;
704 bool cancelSolver = false;
705 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
706 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
707 std::lock_guard<std::mutex> lock{m_cs};
708 cancelSolver = true;
709 }
710 );
07be8f7e 711 miningTimer.start();
5a360a5c 712
0655fac0 713 try {
ad84148d 714 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 715 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 716 while (true)
717 {
2c70b583 718 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 719 {
a96fd7b5 720 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
721 // break;
0655fac0
PK
722 // Busy-wait for the network to come online so we don't waste time mining
723 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 724 miningTimer.stop();
bba7c249
GM
725 do {
726 bool fvNodesEmpty;
727 {
728 LOCK(cs_vNodes);
729 fvNodesEmpty = vNodes.empty();
730 }
269fe243 731 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 732 break;
f8e367eb 733 MilliSleep(5000);
ad84148d 734 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
f8e367eb 735
bba7c249 736 } while (true);
ad84148d 737 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 738 miningTimer.start();
0655fac0 739 }
f70ced6a 740 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
8fc7222d 741 {
742 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
743 sleep(3);
d82623d2 744 }*/
0655fac0
PK
745 //
746 // Create new block
747 //
748 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 749 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 750 if ( Mining_height != pindexPrev->nHeight+1 )
751 {
752 Mining_height = pindexPrev->nHeight+1;
753 Mining_start = (uint32_t)time(NULL);
754 }
2825c0b5 755 if ( ASSETCHAINS_SYMBOL[0] != 0 )
756 {
40304479 757 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2825c0b5 758 sleep(3);
759 }
8e8b6d70 760#ifdef ENABLE_WALLET
08d0b73c 761 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
8e8b6d70 762#else
945f015d 763 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 764#endif
08d0b73c 765 if ( ptr == 0 )
766 {
d0f7ead0 767 static uint32_t counter;
768 if ( counter++ < 100 )
1b5b89ba 769 fprintf(stderr,"created illegal block, retry\n");
d0f7ead0 770 continue;
08d0b73c 771 }
772 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 773 if (!pblocktemplate.get())
6c37f7fd 774 {
8e8b6d70 775 if (GetArg("-mineraddress", "").empty()) {
945f015d 776 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
777 } else {
778 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 779 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 780 }
0655fac0 781 return;
6c37f7fd 782 }
0655fac0 783 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 784 if ( ASSETCHAINS_SYMBOL[0] != 0 )
785 {
8683bd8d 786 if ( ASSETCHAINS_REWARD == 0 )
16c7bf6b 787 {
8683bd8d 788 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
789 {
790 static uint32_t counter;
791 if ( counter++ < 10 )
792 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
793 sleep(10);
794 continue;
795 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
796 }
16c7bf6b 797 }
0655fac0 798 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 799 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
800 //
801 // Search
802 //
8b51b9e4 803 uint8_t pubkeys[66][33]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
404391b5 804 savebits = pblock->nBits;
3505af19 805 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
f0100e72 806 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 807 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 808 {
fda5f849 809 j = 65;
5a471ba9 810 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 811 {
8c654ec5 812 komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
29e60e48 813 if ( nonzpkeys > 0 )
814 {
ccb71a6e 815 for (i=0; i<33; i++)
816 if( pubkeys[0][i] != 0 )
817 break;
818 if ( i == 33 )
819 externalflag = 1;
820 else externalflag = 0;
49b49585 821 if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) )
b176c125 822 {
345e545e 823 for (i=1; i<66; i++)
824 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
825 break;
ccb71a6e 826 if ( externalflag == 0 && i != 66 )
345e545e 827 printf("VIOLATION at %d\n",i);
2c7ad758 828 for (j=gpucount=0; j<65; j++)
829 {
49b49585 830 if ( mids[j] >= 0 || notaryid == 34 )
8fa91017 831 fprintf(stderr,"%d ",mids[j]);
832 else fprintf(stderr,"GPU ");
2c7ad758 833 if ( mids[j] == -1 )
834 gpucount++;
835 }
b000fa04 836 if ( gpucount > j/2 )
f0100e72 837 {
dd98c02d 838 double delta;
d2d3c766 839 if ( notaryid < 0 )
840 i = (rand() % 64);
841 else i = ((Mining_height + notaryid) % 64);
b000fa04 842 delta = sqrt((double)gpucount - j/2) / 2.;
dd98c02d 843 roundrobin_delay += ((delta * i) / 64) - delta;
67478d4a 844 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
f0100e72 845 }
846 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 847 }
29e60e48 848 for (j=0; j<65; j++)
849 if ( mids[j] == notaryid )
850 break;
49b49585 851 if ( j == 65 )
852 KOMODO_LASTMINED = 0;
965f0f7e 853 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 854 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 855 {
856 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
857 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
858 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 859 } else Mining_start = 0;
d7d27bb3 860 } else Mining_start = 0;
e725f1cb 861 while (true)
862 {
16c7bf6b 863 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
16cd9f2d 864 {
865 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
866 sleep(10);
867 break;
16c7bf6b 868 }*/
7213c0b1 869 // Hash state
8c22eb46 870 KOMODO_CHOSEN_ONE = 0;
7213c0b1 871 crypto_generichash_blake2b_state state;
e9574728 872 EhInitialiseState(n, k, state);
7213c0b1
JG
873 // I = the block header minus nonce and solution.
874 CEquihashInput I{*pblock};
875 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
876 ss << I;
7213c0b1
JG
877 // H(I||...
878 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
879 // H(I||V||...
880 crypto_generichash_blake2b_state curr_state;
881 curr_state = state;
7a4c01c9 882 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 883 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 884 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
6be3b162 885 //fprintf(stderr,"running solver\n");
5be6abbf 886 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 887#ifdef ENABLE_WALLET
51eb5273 888 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70
JG
889#else
890 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
891#endif
5be6abbf 892 (std::vector<unsigned char> soln) {
51eb5273
JG
893 // Write the solution to the hash and compute the result.
894 LogPrint("pow", "- Checking solution against target\n");
8e165d57 895 pblock->nSolution = soln;
e7d59bbc 896 solutionTargetChecks.increment();
7a4c01c9 897 if ( UintToArith256(pblock->GetHash()) > hashTarget )
e5430f52 898 {
bd6ef155 899 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
7c3b0491 900 // fprintf(stderr," missed target\n");
51eb5273 901 return false;
e5430f52 902 }
b35ca433 903 if ( /*ASSETCHAINS_SYMBOL[0] == 0 &&*/ Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
d7d27bb3 904 {
f0100e72 905 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
906 int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
52e87248 907 if ( nseconds > 0 )
908 sleep(nseconds);
320a2e35 909 MilliSleep((rand() % 1700) + 1);
d7d27bb3 910 }
2825c0b5 911 else if ( ASSETCHAINS_SYMBOL[0] != 0 )
d2d3c766 912 {
913 sleep(rand() % 30);
914 }
b3183e3e 915 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
916 // Found a solution
917 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 918 LogPrintf("KomodoMiner:\n");
a6a0d913 919 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
8e8b6d70 920#ifdef ENABLE_WALLET
5a360a5c 921 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
8e8b6d70
JG
922#else
923 if (ProcessBlockFound(pblock)) {
924#endif
a6a0d913 925 // Ignore chain updates caused by us
926 std::lock_guard<std::mutex> lock{m_cs};
5a360a5c
JG
927 cancelSolver = false;
928 }
8c22eb46 929 KOMODO_CHOSEN_ONE = 0;
8e165d57 930 SetThreadPriority(THREAD_PRIORITY_LOWEST);
8e165d57 931 // In regression test mode, stop mining after a block is found.
a6df7ab5
JG
932 if (chainparams.MineBlocksOnDemand()) {
933 // Increment here because throwing skips the call below
934 ehSolverRuns.increment();
8e165d57 935 throw boost::thread_interrupted();
a6df7ab5 936 }
b78471c2 937 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
938 // sleep(1800);
51eb5273
JG
939 return true;
940 };
941 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
942 std::lock_guard<std::mutex> lock{m_cs};
943 return cancelSolver;
944 };
c7aaab7a 945
5f0009b2 946 // TODO: factor this out into a function with the same API for each solver.
e1e65cef 947 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
c7aaab7a
DH
948 // Create solver and initialize it.
949 equi eq(1);
950 eq.setstate(&curr_state);
951
c938fb1f 952 // Initialization done, start algo driver.
c7aaab7a
DH
953 eq.digit0(0);
954 eq.xfull = eq.bfull = eq.hfull = 0;
955 eq.showbsizes(0);
956 for (u32 r = 1; r < WK; r++) {
957 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
958 eq.xfull = eq.bfull = eq.hfull = 0;
959 eq.showbsizes(r);
960 }
961 eq.digitK(0);
a6df7ab5 962 ehSolverRuns.increment();
c7aaab7a
DH
963
964 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
965 for (size_t s = 0; s < eq.nsols; s++) {
966 LogPrint("pow", "Checking solution %d\n", s+1);
967 std::vector<eh_index> index_vector(PROOFSIZE);
968 for (size_t i = 0; i < PROOFSIZE; i++) {
969 index_vector[i] = eq.sols[s][i];
970 }
971 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
972
973 if (validBlock(sol_char)) {
974 // If we find a POW solution, do not try other solutions
975 // because they become invalid as we created a new block in blockchain.
976 break;
977 }
978 }
979 } else {
980 try {
981 // If we find a valid block, we rebuild
a6df7ab5
JG
982 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
983 ehSolverRuns.increment();
984 if (found) {
a8aa4375 985 int32_t i; uint256 hash = pblock->GetHash();
986 for (i=0; i<32; i++)
987 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
988 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
b78471c2 989 FOUND_BLOCK = 1;
8ee93080 990 KOMODO_MAYBEMINED = Mining_height;
c7aaab7a 991 break;
a6df7ab5 992 }
c7aaab7a
DH
993 } catch (EhSolverCancelledException&) {
994 LogPrint("pow", "Equihash solver cancelled\n");
995 std::lock_guard<std::mutex> lock{m_cs};
996 cancelSolver = false;
997 }
48265f3c 998 }
d247a5d1 999
0655fac0
PK
1000 // Check for stop or if block needs to be rebuilt
1001 boost::this_thread::interruption_point();
1002 // Regtest mode doesn't require peers
b78471c2 1003 if ( FOUND_BLOCK != 0 )
1004 {
1005 FOUND_BLOCK = 0;
1006 fprintf(stderr,"FOUND_BLOCK!\n");
9152feb5 1007 //sleep(2000);
b78471c2 1008 }
bebe7282 1009 if (vNodes.empty() && chainparams.MiningRequiresPeers())
e5430f52 1010 {
f70ced6a 1011 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
10694486 1012 {
bd6ef155 1013 fprintf(stderr,"no nodes, break\n");
d90cef0b 1014 break;
10694486 1015 }
e5430f52 1016 }
8e165d57 1017 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
e5430f52 1018 {
198286a5 1019 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1020 fprintf(stderr,"0xffff, break\n");
0655fac0 1021 break;
e5430f52 1022 }
0655fac0 1023 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
e5430f52 1024 {
6be3b162 1025 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1026 fprintf(stderr,"timeout, break\n");
0655fac0 1027 break;
e5430f52 1028 }
1029 if ( pindexPrev != chainActive.Tip() )
1030 {
6be3b162 1031 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1032 fprintf(stderr,"Tip advanced, break\n");
0655fac0 1033 break;
e5430f52 1034 }
8e165d57
JG
1035 // Update nNonce and nTime
1036 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
404391b5 1037 pblock->nBits = savebits;
357e4ca5 1038 if ( ASSETCHAINS_STAKED == 0 )
1039 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
bebe7282 1040 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
48265f3c
WL
1041 {
1042 // Changing pblock->nTime can change work required on testnet:
1043 hashTarget.SetCompact(pblock->nBits);
1044 }
d247a5d1
JG
1045 }
1046 }
0655fac0 1047 }
27df4123 1048 catch (const boost::thread_interrupted&)
d247a5d1 1049 {
07be8f7e 1050 miningTimer.stop();
5e9b555f 1051 c.disconnect();
2e500f50 1052 LogPrintf("KomodoMiner terminated\n");
d247a5d1
JG
1053 throw;
1054 }
bba7c249
GM
1055 catch (const std::runtime_error &e)
1056 {
07be8f7e 1057 miningTimer.stop();
5e9b555f 1058 c.disconnect();
2e500f50 1059 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
bba7c249
GM
1060 return;
1061 }
07be8f7e 1062 miningTimer.stop();
5a360a5c 1063 c.disconnect();
d247a5d1
JG
1064}
1065
8e8b6d70 1066#ifdef ENABLE_WALLET
c8b74258 1067void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70
JG
1068#else
1069void GenerateBitcoins(bool fGenerate, int nThreads)
1070#endif
d247a5d1
JG
1071{
1072 static boost::thread_group* minerThreads = NULL;
1073
2854c4e3
WL
1074 if (nThreads < 0)
1075 nThreads = GetNumCores();
d247a5d1
JG
1076
1077 if (minerThreads != NULL)
1078 {
1079 minerThreads->interrupt_all();
1080 delete minerThreads;
1081 minerThreads = NULL;
1082 }
1083
1084 if (nThreads == 0 || !fGenerate)
1085 return;
1086
1087 minerThreads = new boost::thread_group();
8e8b6d70
JG
1088 for (int i = 0; i < nThreads; i++) {
1089#ifdef ENABLE_WALLET
d247a5d1 1090 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
8e8b6d70
JG
1091#else
1092 minerThreads->create_thread(&BitcoinMiner);
1093#endif
1094 }
d247a5d1
JG
1095}
1096
2cc0a252 1097#endif // ENABLE_MINING
This page took 0.49599 seconds and 4 git commands to generate.