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