]> 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{
4972b74b 103 pblock->nTime = 1 + 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);
d231a6a7 123int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
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;
c7a1d234 215 if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 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;
e12ea519 387 blocktime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9a0f2798 388 //pblock->nTime = blocktime + 1;
357e4ca5 389 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
7dbeae5d 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;
d231a6a7 394 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
234c0ac0 395 blocktime += 2;
d231a6a7 396 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
a4a40a38 397 {
66b4e563 398 CAmount txfees = 0;
a4a40a38 399 pblock->vtx.push_back(txStaked);
a4a40a38 400 pblocktemplate->vTxFees.push_back(txfees);
d231a6a7 401 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
a4a40a38 402 nFees += txfees;
9339a0cb 403 pblock->nTime = blocktime;
2fb22ef8 404 if ( GetAdjustedTime() < pblock->nTime )
f0cfc70f 405 {
2fb22ef8 406 printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime()));
da6e99a0 407 while ( GetAdjustedTime()+30 < pblock->nTime )
f0cfc70f 408 {
9465da96 409 sleep(30);
1599d4c8 410 fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime()));
2fb22ef8 411 }
412 fprintf(stderr,"finished waiting\n");
413 //sleep(pblock->nTime - GetAdjustedTime());
f0cfc70f 414 }
415
a0300536 416 } else fprintf(stderr,"no utxos eligible for staking\n");
a4a40a38 417 }
d247a5d1 418
f3ffa3d2 419 // Create coinbase tx
072099d7 420 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
f3ffa3d2
SB
421 txNew.vin.resize(1);
422 txNew.vin[0].prevout.SetNull();
d581f229 423 txNew.vout.resize(1);
f3ffa3d2 424 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
c9b1071d 425 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
aa0b9e00 426 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
9bb37bf0 427 txNew.nExpiryHeight = 0;
f3ffa3d2
SB
428 // Add fees
429 txNew.vout[0].nValue += nFees;
b867e409 430 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
6ae23274 431
8683bd8d 432 /*if ( ASSETCHAINS_SYMBOL[0] == 0 )
c9b1071d 433 {
8683bd8d 434 int32_t i,opretlen; uint8_t opret[256],*ptr;
44caf46a 435 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
c9b1071d 436 {
b4810651 437 if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed
d9a9d562 438 {
439 txNew.vout.resize(2);
440 txNew.vout[1].scriptPubKey.resize(opretlen);
441 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
442 for (i=0; i<opretlen; i++)
443 ptr[i] = opret[i];
444 txNew.vout[1].nValue = 0;
445 //fprintf(stderr,"opretlen.%d\n",opretlen);
768dccac 446 } //else printf("null opretlen for prices\n");
8683bd8d 447 }
c9b1071d 448 }
654dfaaf 449 else if ( komodo_is_issuer() != 0 )
c9b1071d 450 {
7322eaa0 451 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
1ecb8541 452 if ( txNew.vout.size() > 1 )
4a21ccd2 453 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
8683bd8d 454 }*/
8f3aa743 455
4949004d 456 pblock->vtx[0] = txNew;
852af44b 457 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission(pblocktemplate->block)) != 0 )
c000c9ca 458 {
459 int32_t i; uint8_t *ptr;
9ed1be03 460 txNew.vout.resize(2);
461 txNew.vout[1].nValue = commission;
462 txNew.vout[1].scriptPubKey.resize(35);
463 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
c000c9ca 464 ptr[0] = 33;
465 for (i=0; i<33; i++)
466 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
467 ptr[34] = OP_CHECKSIG;
146d2aa2 468 //printf("autocreate commision vout\n");
9ed1be03 469 pblock->vtx[0] = txNew;
c000c9ca 470 }
d247a5d1 471 pblocktemplate->vTxFees[0] = -nFees;
8e165d57
JG
472 // Randomise nonce
473 arith_uint256 nonce = UintToArith256(GetRandHash());
474 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
475 nonce <<= 32;
476 nonce >>= 16;
477 pblock->nNonce = ArithToUint256(nonce);
478
d247a5d1
JG
479 // Fill in header
480 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 481 pblock->hashReserved = uint256();
9a0f2798 482 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
483 {
484 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
485 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
486 }
fdda3c50 487 pblock->nSolution.clear();
d247a5d1
JG
488 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
489
c583e2a9 490 CValidationState state;
0af2786d 491 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
af805d53 492 {
d0f7ead0 493 static uint32_t counter;
3283cb53 494 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
495 fprintf(stderr,"warning: miner testblockvalidity failed\n");
14aa6cc0 496 return(0);
af805d53 497 }
d247a5d1
JG
498 }
499
500 return pblocktemplate.release();
501}
502
1a31463b 503/*
8e8b6d70
JG
504#ifdef ENABLE_WALLET
505boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
506#else
507boost::optional<CScript> GetMinerScriptPubKey()
508#endif
509{
510 CKeyID keyID;
511 CBitcoinAddress addr;
512 if (addr.SetString(GetArg("-mineraddress", ""))) {
513 addr.GetKeyID(keyID);
514 } else {
515#ifdef ENABLE_WALLET
516 CPubKey pubkey;
517 if (!reservekey.GetReservedKey(pubkey)) {
518 return boost::optional<CScript>();
519 }
520 keyID = pubkey.GetID();
521#else
522 return boost::optional<CScript>();
523#endif
524 }
525
526 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
527 return scriptPubKey;
528}
529
1a31463b 530#ifdef ENABLE_WALLET
48265f3c 531CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 532{
8e8b6d70
JG
533 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
534#else
535CBlockTemplate* CreateNewBlockWithKey()
536{
537 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
538#endif
acfa0333 539
8e8b6d70
JG
540 if (!scriptPubKey) {
541 return NULL;
542 }
543 return CreateNewBlock(*scriptPubKey);
945f015d 544}*/
acfa0333 545
c1de826f
JG
546//////////////////////////////////////////////////////////////////////////////
547//
548// Internal miner
549//
550
2cc0a252 551#ifdef ENABLE_MINING
c1de826f 552
d247a5d1
JG
553void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
554{
555 // Update nExtraNonce
556 static uint256 hashPrevBlock;
557 if (hashPrevBlock != pblock->hashPrevBlock)
558 {
559 nExtraNonce = 0;
560 hashPrevBlock = pblock->hashPrevBlock;
561 }
562 ++nExtraNonce;
563 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
564 CMutableTransaction txCoinbase(pblock->vtx[0]);
565 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
566 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
d247a5d1 567
4949004d 568 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
569 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
570}
571
4a85e067 572#ifdef ENABLE_WALLET
acfa0333
WL
573//////////////////////////////////////////////////////////////////////////////
574//
575// Internal miner
576//
acfa0333 577
48265f3c 578CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 579{
f6c647ed 580 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 581 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 582 {
7bfc207a 583 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 584 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 585 }
586 else
587 {
588 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 589 {
f6c647ed 590 return NULL;
1b5b89ba 591 }
f6c647ed 592 scriptPubKey.resize(35);
f66f65ec 593 ptr = (uint8_t *)pubkey.begin();
f6c647ed 594 script = (uint8_t *)scriptPubKey.data();
595 script[0] = 33;
596 for (i=0; i<33; i++)
597 script[i+1] = ptr[i];
598 script[34] = OP_CHECKSIG;
599 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
600 }
48265f3c 601 return CreateNewBlock(scriptPubKey);
acfa0333
WL
602}
603
945f015d 604
269d8ba0 605static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
8e8b6d70
JG
606#else
607static bool ProcessBlockFound(CBlock* pblock)
608#endif // ENABLE_WALLET
d247a5d1 609{
81212588 610 LogPrintf("%s\n", pblock->ToString());
35915149 611 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
d247a5d1
JG
612
613 // Found a solution
614 {
615 LOCK(cs_main);
4c6d41b8 616 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
ba8419c7 617 {
618 uint256 hash; int32_t i;
619 hash = pblock->hashPrevBlock;
92266e99 620 for (i=31; i>=0; i--)
ba8419c7 621 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 622 fprintf(stderr," <- prev (stale)\n");
ba8419c7 623 hash = chainActive.Tip()->GetBlockHash();
92266e99 624 for (i=31; i>=0; i--)
ba8419c7 625 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
c0dbb034 626 fprintf(stderr," <- chainTip (stale)\n");
ba8419c7 627
2e500f50 628 return error("KomodoMiner: generated block is stale");
ba8419c7 629 }
18e72167 630 }
d247a5d1 631
8e8b6d70 632#ifdef ENABLE_WALLET
18e72167 633 // Remove key from key pool
998397aa 634 if ( IS_KOMODO_NOTARY == 0 )
945f015d 635 {
636 if (GetArg("-mineraddress", "").empty()) {
637 // Remove key from key pool
638 reservekey.KeepKey();
639 }
8e8b6d70 640 }
18e72167 641 // Track how many getdata requests this block gets
438ba9c1 642 //if ( 0 )
18e72167
PW
643 {
644 LOCK(wallet.cs_wallet);
645 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1 646 }
8e8b6d70 647#endif
d247a5d1 648
18e72167
PW
649 // Process this block the same as if we had received it from another node
650 CValidationState state;
35915149 651 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 652 return error("KomodoMiner: ProcessNewBlock, block not accepted");
18e72167 653
d793f94b 654 TrackMinedBlock(pblock->GetHash());
a6df7ab5 655
d247a5d1
JG
656 return true;
657}
658
078f6af1 659int32_t komodo_baseid(char *origbase);
a30dd993 660int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
13691369 661arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
8ee93080 662int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 663extern int32_t KOMODO_LASTMINED;
8b51b9e4 664int32_t roundrobin_delay;
88287857 665arith_uint256 HASHTarget;
078f6af1 666
8e8b6d70 667#ifdef ENABLE_WALLET
d247a5d1 668void static BitcoinMiner(CWallet *pwallet)
8e8b6d70
JG
669#else
670void static BitcoinMiner()
671#endif
d247a5d1 672{
2e500f50 673 LogPrintf("KomodoMiner started\n");
d247a5d1 674 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 675 RenameThread("komodo-miner");
bebe7282 676 const CChainParams& chainparams = Params();
d247a5d1 677
8e8b6d70
JG
678#ifdef ENABLE_WALLET
679 // Each thread has its own key
d247a5d1 680 CReserveKey reservekey(pwallet);
8e8b6d70
JG
681#endif
682
683 // Each thread has its own counter
d247a5d1
JG
684 unsigned int nExtraNonce = 0;
685
e9574728
JG
686 unsigned int n = chainparams.EquihashN();
687 unsigned int k = chainparams.EquihashK();
8683bd8d 688 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
b7ba6413 689 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 690 {
691 sleep(1);
4e624c04 692 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
693 break;
755ead98 694 }
8683bd8d 695 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
fdda3c50 696
755ead98 697 std::string solver;
e1e65cef 698 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
755ead98 699 solver = "tromp";
e1e65cef 700 //else solver = "default";
5f0009b2 701 assert(solver == "tromp" || solver == "default");
c7aaab7a 702 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 703 if ( ASSETCHAINS_SYMBOL[0] != 0 )
25f7ef8c 704 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
5a360a5c
JG
705 std::mutex m_cs;
706 bool cancelSolver = false;
707 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
708 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
709 std::lock_guard<std::mutex> lock{m_cs};
710 cancelSolver = true;
711 }
712 );
07be8f7e 713 miningTimer.start();
5a360a5c 714
0655fac0 715 try {
ad84148d 716 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 717 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 718 while (true)
719 {
2c70b583 720 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 721 {
a96fd7b5 722 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
723 // break;
0655fac0
PK
724 // Busy-wait for the network to come online so we don't waste time mining
725 // on an obsolete chain. In regtest mode we expect to fly solo.
07be8f7e 726 miningTimer.stop();
bba7c249
GM
727 do {
728 bool fvNodesEmpty;
729 {
730 LOCK(cs_vNodes);
731 fvNodesEmpty = vNodes.empty();
732 }
269fe243 733 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
bba7c249 734 break;
f8e367eb 735 MilliSleep(5000);
ad84148d 736 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
f8e367eb 737
bba7c249 738 } while (true);
ad84148d 739 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
07be8f7e 740 miningTimer.start();
0655fac0 741 }
f70ced6a 742 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
8fc7222d 743 {
744 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
745 sleep(3);
d82623d2 746 }*/
0655fac0
PK
747 //
748 // Create new block
749 //
750 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 751 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 752 if ( Mining_height != pindexPrev->nHeight+1 )
753 {
754 Mining_height = pindexPrev->nHeight+1;
755 Mining_start = (uint32_t)time(NULL);
756 }
8e9ef91c 757 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2825c0b5 758 {
40304479 759 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2825c0b5 760 sleep(3);
761 }
8e8b6d70 762#ifdef ENABLE_WALLET
08d0b73c 763 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
8e8b6d70 764#else
945f015d 765 CBlockTemplate *ptr = CreateNewBlockWithKey();
8e8b6d70 766#endif
08d0b73c 767 if ( ptr == 0 )
768 {
d0f7ead0 769 static uint32_t counter;
5bb3d0fe 770 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
1b5b89ba 771 fprintf(stderr,"created illegal block, retry\n");
d0f7ead0 772 continue;
08d0b73c 773 }
774 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 775 if (!pblocktemplate.get())
6c37f7fd 776 {
8e8b6d70 777 if (GetArg("-mineraddress", "").empty()) {
945f015d 778 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
8e8b6d70
JG
779 } else {
780 // Should never reach here, because -mineraddress validity is checked in init.cpp
945f015d 781 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
8e8b6d70 782 }
0655fac0 783 return;
6c37f7fd 784 }
0655fac0 785 CBlock *pblock = &pblocktemplate->block;
16c7bf6b 786 if ( ASSETCHAINS_SYMBOL[0] != 0 )
787 {
8683bd8d 788 if ( ASSETCHAINS_REWARD == 0 )
16c7bf6b 789 {
8683bd8d 790 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
791 {
792 static uint32_t counter;
793 if ( counter++ < 10 )
794 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
795 sleep(10);
796 continue;
797 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
798 }
16c7bf6b 799 }
0655fac0 800 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 801 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
802 //
803 // Search
804 //
a30dd993 805 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 806 savebits = pblock->nBits;
88287857 807 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
f0100e72 808 roundrobin_delay = ROUNDROBIN_DELAY;
3e7e3109 809 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
5203fc4b 810 {
fda5f849 811 j = 65;
5a471ba9 812 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 813 {
a30dd993 814 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
29e60e48 815 if ( nonzpkeys > 0 )
816 {
ccb71a6e 817 for (i=0; i<33; i++)
818 if( pubkeys[0][i] != 0 )
819 break;
820 if ( i == 33 )
821 externalflag = 1;
822 else externalflag = 0;
49b49585 823 if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) )
b176c125 824 {
345e545e 825 for (i=1; i<66; i++)
826 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
827 break;
ccb71a6e 828 if ( externalflag == 0 && i != 66 )
345e545e 829 printf("VIOLATION at %d\n",i);
2c7ad758 830 for (j=gpucount=0; j<65; j++)
831 {
49b49585 832 if ( mids[j] >= 0 || notaryid == 34 )
8fa91017 833 fprintf(stderr,"%d ",mids[j]);
834 else fprintf(stderr,"GPU ");
2c7ad758 835 if ( mids[j] == -1 )
836 gpucount++;
837 }
b000fa04 838 if ( gpucount > j/2 )
f0100e72 839 {
dd98c02d 840 double delta;
d2d3c766 841 if ( notaryid < 0 )
842 i = (rand() % 64);
843 else i = ((Mining_height + notaryid) % 64);
b000fa04 844 delta = sqrt((double)gpucount - j/2) / 2.;
dd98c02d 845 roundrobin_delay += ((delta * i) / 64) - delta;
67478d4a 846 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
f0100e72 847 }
848 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 849 }
29e60e48 850 for (j=0; j<65; j++)
851 if ( mids[j] == notaryid )
852 break;
49b49585 853 if ( j == 65 )
854 KOMODO_LASTMINED = 0;
965f0f7e 855 } else fprintf(stderr,"no nonz pubkeys\n");
49b49585 856 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 857 {
88287857 858 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
fda5f849 859 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
860 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 861 } else Mining_start = 0;
d7d27bb3 862 } else Mining_start = 0;
deba7f20 863 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
864 {
865 int32_t percPoS,z;
c966741f 866 if ( Mining_height <= 100 )
867 {
868 sleep(60);
869 continue;
870 }
88287857 871 HASHTarget = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
deba7f20 872 for (z=31; z>=0; z--)
88287857 873 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
deba7f20 874 fprintf(stderr," PoW for staked coin\n");
875 }
e725f1cb 876 while (true)
877 {
16c7bf6b 878 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
16cd9f2d 879 {
880 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
881 sleep(10);
882 break;
16c7bf6b 883 }*/
7213c0b1 884 // Hash state
8c22eb46 885 KOMODO_CHOSEN_ONE = 0;
7213c0b1 886 crypto_generichash_blake2b_state state;
e9574728 887 EhInitialiseState(n, k, state);
7213c0b1
JG
888 // I = the block header minus nonce and solution.
889 CEquihashInput I{*pblock};
890 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
891 ss << I;
7213c0b1
JG
892 // H(I||...
893 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
894 // H(I||V||...
895 crypto_generichash_blake2b_state curr_state;
896 curr_state = state;
7a4c01c9 897 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 898 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 899 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
7da84107 900 arith_uint256 hashTarget = HASHTarget;
6be3b162 901 //fprintf(stderr,"running solver\n");
5be6abbf 902 std::function<bool(std::vector<unsigned char>)> validBlock =
8e8b6d70 903#ifdef ENABLE_WALLET
7da84107 904 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 905#else
7da84107 906 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
8e8b6d70 907#endif
5be6abbf 908 (std::vector<unsigned char> soln) {
51eb5273
JG
909 // Write the solution to the hash and compute the result.
910 LogPrint("pow", "- Checking solution against target\n");
8e165d57 911 pblock->nSolution = soln;
e7d59bbc 912 solutionTargetChecks.increment();
88287857 913 if ( UintToArith256(pblock->GetHash()) > HASHTarget )
e5430f52 914 {
25d977f7 915 //if ( ASSETCHAINS_SYMBOL[0] != 0 )
916 // fprintf(stderr," missed target\n");
51eb5273 917 return false;
e5430f52 918 }
9dd93da4 919 CValidationState state;
920 if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false))
921 {
922 fprintf(stderr,"Invalid block mined, try again\n");
923 return(false);
924 }
8e9ef91c 925 if ( ASSETCHAINS_STAKED == 0 )
d7d27bb3 926 {
8e9ef91c 927 if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
928 {
929 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
930 int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
931 if ( nseconds > 0 )
932 sleep(nseconds);
933 MilliSleep((rand() % 1700) + 1);
934 }
935 else if ( ASSETCHAINS_SYMBOL[0] != 0 )
936 {
937 sleep(rand() % 30);
938 }
d7d27bb3 939 }
8e9ef91c 940 else
d2d3c766 941 {
deba7f20 942 if ( NOTARY_PUBKEY33[0] != 0 )
943 {
944 printf("need to wait %d seconds to submit\n",(int32_t)(pblock->nTime - GetAdjustedTime()));
945 while ( GetAdjustedTime() < pblock->nTime )
946 sleep(1);
947 }
68d0354d 948 else
949 {
e4821a82 950 uint256 tmp = pblock->GetHash();
b7aaca4b 951 int32_t z; for (z=31; z>=0; z--)
952 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
953 fprintf(stderr," mined block!\n");
68d0354d 954 }
d2d3c766 955 }
b3183e3e 956 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
957 // Found a solution
958 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 959 LogPrintf("KomodoMiner:\n");
88287857 960 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), HASHTarget.GetHex());
8e8b6d70 961#ifdef ENABLE_WALLET
5a360a5c 962 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
8e8b6d70
JG
963#else
964 if (ProcessBlockFound(pblock)) {
965#endif
a6a0d913 966 // Ignore chain updates caused by us
967 std::lock_guard<std::mutex> lock{m_cs};
5a360a5c
JG
968 cancelSolver = false;
969 }
8c22eb46 970 KOMODO_CHOSEN_ONE = 0;
8e165d57 971 SetThreadPriority(THREAD_PRIORITY_LOWEST);
8e165d57 972 // In regression test mode, stop mining after a block is found.
a6df7ab5
JG
973 if (chainparams.MineBlocksOnDemand()) {
974 // Increment here because throwing skips the call below
975 ehSolverRuns.increment();
8e165d57 976 throw boost::thread_interrupted();
a6df7ab5 977 }
b78471c2 978 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
979 // sleep(1800);
51eb5273
JG
980 return true;
981 };
982 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
983 std::lock_guard<std::mutex> lock{m_cs};
984 return cancelSolver;
985 };
c7aaab7a 986
5f0009b2 987 // TODO: factor this out into a function with the same API for each solver.
e1e65cef 988 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
c7aaab7a
DH
989 // Create solver and initialize it.
990 equi eq(1);
991 eq.setstate(&curr_state);
992
c938fb1f 993 // Initialization done, start algo driver.
c7aaab7a
DH
994 eq.digit0(0);
995 eq.xfull = eq.bfull = eq.hfull = 0;
996 eq.showbsizes(0);
997 for (u32 r = 1; r < WK; r++) {
998 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
999 eq.xfull = eq.bfull = eq.hfull = 0;
1000 eq.showbsizes(r);
1001 }
1002 eq.digitK(0);
a6df7ab5 1003 ehSolverRuns.increment();
c7aaab7a
DH
1004
1005 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1006 for (size_t s = 0; s < eq.nsols; s++) {
1007 LogPrint("pow", "Checking solution %d\n", s+1);
1008 std::vector<eh_index> index_vector(PROOFSIZE);
1009 for (size_t i = 0; i < PROOFSIZE; i++) {
1010 index_vector[i] = eq.sols[s][i];
1011 }
1012 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1013
1014 if (validBlock(sol_char)) {
1015 // If we find a POW solution, do not try other solutions
1016 // because they become invalid as we created a new block in blockchain.
1017 break;
1018 }
1019 }
1020 } else {
1021 try {
1022 // If we find a valid block, we rebuild
a6df7ab5
JG
1023 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1024 ehSolverRuns.increment();
1025 if (found) {
a8aa4375 1026 int32_t i; uint256 hash = pblock->GetHash();
1027 for (i=0; i<32; i++)
1028 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1029 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
b78471c2 1030 FOUND_BLOCK = 1;
8ee93080 1031 KOMODO_MAYBEMINED = Mining_height;
c7aaab7a 1032 break;
a6df7ab5 1033 }
c7aaab7a
DH
1034 } catch (EhSolverCancelledException&) {
1035 LogPrint("pow", "Equihash solver cancelled\n");
1036 std::lock_guard<std::mutex> lock{m_cs};
1037 cancelSolver = false;
1038 }
48265f3c 1039 }
d247a5d1 1040
0655fac0
PK
1041 // Check for stop or if block needs to be rebuilt
1042 boost::this_thread::interruption_point();
1043 // Regtest mode doesn't require peers
b78471c2 1044 if ( FOUND_BLOCK != 0 )
1045 {
1046 FOUND_BLOCK = 0;
1047 fprintf(stderr,"FOUND_BLOCK!\n");
9152feb5 1048 //sleep(2000);
b78471c2 1049 }
bebe7282 1050 if (vNodes.empty() && chainparams.MiningRequiresPeers())
e5430f52 1051 {
f70ced6a 1052 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
10694486 1053 {
bd6ef155 1054 fprintf(stderr,"no nodes, break\n");
d90cef0b 1055 break;
10694486 1056 }
e5430f52 1057 }
8e165d57 1058 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
e5430f52 1059 {
198286a5 1060 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1061 fprintf(stderr,"0xffff, break\n");
0655fac0 1062 break;
e5430f52 1063 }
0655fac0 1064 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
e5430f52 1065 {
6be3b162 1066 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1067 fprintf(stderr,"timeout, break\n");
0655fac0 1068 break;
e5430f52 1069 }
1070 if ( pindexPrev != chainActive.Tip() )
1071 {
6be3b162 1072 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 1073 fprintf(stderr,"Tip advanced, break\n");
0655fac0 1074 break;
e5430f52 1075 }
8e165d57
JG
1076 // Update nNonce and nTime
1077 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
404391b5 1078 pblock->nBits = savebits;
0d8ffadc 1079 if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
357e4ca5 1080 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
bebe7282 1081 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
48265f3c
WL
1082 {
1083 // Changing pblock->nTime can change work required on testnet:
88287857 1084 HASHTarget.SetCompact(pblock->nBits);
48265f3c 1085 }
d247a5d1
JG
1086 }
1087 }
0655fac0 1088 }
27df4123 1089 catch (const boost::thread_interrupted&)
d247a5d1 1090 {
07be8f7e 1091 miningTimer.stop();
5e9b555f 1092 c.disconnect();
2e500f50 1093 LogPrintf("KomodoMiner terminated\n");
d247a5d1
JG
1094 throw;
1095 }
bba7c249
GM
1096 catch (const std::runtime_error &e)
1097 {
07be8f7e 1098 miningTimer.stop();
5e9b555f 1099 c.disconnect();
2e500f50 1100 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
bba7c249
GM
1101 return;
1102 }
07be8f7e 1103 miningTimer.stop();
5a360a5c 1104 c.disconnect();
d247a5d1
JG
1105}
1106
8e8b6d70 1107#ifdef ENABLE_WALLET
c8b74258 1108void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
8e8b6d70
JG
1109#else
1110void GenerateBitcoins(bool fGenerate, int nThreads)
1111#endif
d247a5d1
JG
1112{
1113 static boost::thread_group* minerThreads = NULL;
1114
2854c4e3
WL
1115 if (nThreads < 0)
1116 nThreads = GetNumCores();
d247a5d1
JG
1117
1118 if (minerThreads != NULL)
1119 {
1120 minerThreads->interrupt_all();
1121 delete minerThreads;
1122 minerThreads = NULL;
1123 }
1124
1125 if (nThreads == 0 || !fGenerate)
1126 return;
1127
1128 minerThreads = new boost::thread_group();
8e8b6d70
JG
1129 for (int i = 0; i < nThreads; i++) {
1130#ifdef ENABLE_WALLET
d247a5d1 1131 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
8e8b6d70
JG
1132#else
1133 minerThreads->create_thread(&BitcoinMiner);
1134#endif
1135 }
d247a5d1
JG
1136}
1137
2cc0a252 1138#endif // ENABLE_MINING
This page took 0.524742 seconds and 4 git commands to generate.