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