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