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