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