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