]> Git Repo - VerusCoin.git/blame - src/miner.cpp
Revert "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"
c7aaab7a 7#include "pow/tromp/equi_miner.h"
51ed9ec9 8
eda37330 9#include "amount.h"
bebe7282 10#include "chainparams.h"
691161d4 11#include "consensus/consensus.h"
da29ecbc 12#include "consensus/validation.h"
85aab2a0 13#include "hash.h"
d247a5d1 14#include "main.h"
a6df7ab5 15#include "metrics.h"
51ed9ec9 16#include "net.h"
df852d2b 17#include "pow.h"
bebe7282 18#include "primitives/transaction.h"
8e165d57 19#include "random.h"
22c4272b 20#include "timedata.h"
ad49c256
WL
21#include "util.h"
22#include "utilmoneystr.h"
df840de5 23#ifdef ENABLE_WALLET
fdda3c50 24#include "crypto/equihash.h"
50c72f23 25#include "wallet/wallet.h"
2dbabb11 26#include <functional>
df840de5 27#endif
09eb201b 28
fdda3c50
JG
29#include "sodium.h"
30
ad49c256 31#include <boost/thread.hpp>
a3c26c2e 32#include <boost/tuple/tuple.hpp>
5a360a5c 33#include <mutex>
ad49c256 34
09eb201b 35using namespace std;
7b4737c8 36
d247a5d1
JG
37//////////////////////////////////////////////////////////////////////////////
38//
39// BitcoinMiner
40//
41
c6cb21d1
GA
42//
43// Unconfirmed transactions in the memory pool often depend on other
44// transactions in the memory pool. When we select transactions from the
45// pool, we select by highest priority or fee rate, so we might consider
46// transactions that depend on transactions that aren't yet in the block.
47// The COrphan class keeps track of these 'temporary orphans' while
48// CreateBlock is figuring out which transactions to include.
49//
d247a5d1
JG
50class COrphan
51{
52public:
4d707d51 53 const CTransaction* ptx;
d247a5d1 54 set<uint256> setDependsOn;
c6cb21d1 55 CFeeRate feeRate;
02bec4b2 56 double dPriority;
d247a5d1 57
c6cb21d1 58 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
d247a5d1 59 {
d247a5d1 60 }
d247a5d1
JG
61};
62
51ed9ec9
BD
63uint64_t nLastBlockTx = 0;
64uint64_t nLastBlockSize = 0;
d247a5d1 65
c6cb21d1
GA
66// We want to sort transactions by priority and fee rate, so:
67typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
d247a5d1
JG
68class TxPriorityCompare
69{
70 bool byFee;
0655fac0 71
d247a5d1
JG
72public:
73 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
0655fac0 74
d247a5d1
JG
75 bool operator()(const TxPriority& a, const TxPriority& b)
76 {
77 if (byFee)
78 {
79 if (a.get<1>() == b.get<1>())
80 return a.get<0>() < b.get<0>();
81 return a.get<1>() < b.get<1>();
82 }
83 else
84 {
85 if (a.get<0>() == b.get<0>())
86 return a.get<1>() < b.get<1>();
87 return a.get<0>() < b.get<0>();
88 }
89 }
90};
91
bebe7282 92void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
22c4272b 93{
94 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
95
96 // Updating time can change work required on testnet:
bebe7282
JT
97 if (consensusParams.fPowAllowMinDifficultyBlocks)
98 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
22c4272b 99}
100
0ae2af2b 101#define ASSETCHAINS_MINHEIGHT 100
c55d5f09 102#define KOMODO_ELECTION_GAP 2000
dd14cffe 103#define ROUNDROBIN_DELAY 59
ab918767 104extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE;
f24b36ca 105extern char ASSETCHAINS_SYMBOL[16];
106extern std::string NOTARY_PUBKEY;
107extern uint8_t NOTARY_PUBKEY33[33];
108uint32_t Mining_start,Mining_height;
109int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33);
110int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]);
1e81ccb7 111int32_t komodo_pax_opreturn(uint8_t *opret,int32_t maxsize);
9cc05f24 112uint64_t komodo_paxtotal();
d63fdb34 113int32_t komodo_baseid(char *origbase);
654dfaaf 114int32_t komodo_is_issuer();
635dd34d 115int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
48a3cd18 116int32_t komodo_isrealtime(int32_t *kmdheightp);
7652ed92 117
48265f3c 118CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
d247a5d1 119{
ab918767 120 uint64_t deposits; int32_t isrealtime,kmdheight; const CChainParams& chainparams = Params();
d247a5d1 121 // Create new block
4dddc096 122 unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
d247a5d1 123 if(!pblocktemplate.get())
1b5b89ba 124 {
125 fprintf(stderr,"pblocktemplate.get() failure\n");
d247a5d1 126 return NULL;
1b5b89ba 127 }
d247a5d1 128 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
4b6162f0 129 if ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
a5e36fdd 130 {
48a3cd18 131 isrealtime = komodo_isrealtime(&kmdheight);
3da07d2e 132 deposits = komodo_paxtotal();
5ba0ce9d 133 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
ec7ad5f6 134 {
79562bf3 135 deposits = komodo_paxtotal();
c5b295d8 136 if ( KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
79562bf3 137 {
bbaa688c 138 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
79562bf3 139 }
2bec17cb 140 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
4a21ccd2 141 {
eb928486 142 fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
79562bf3 143 break;
4a21ccd2 144 }
79562bf3 145 sleep(10);
ec7ad5f6 146 }
f24b36ca 147 KOMODO_ON_DEMAND = 0;
79562bf3 148 if ( 0 && deposits != 0 )
149 printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
a5e36fdd 150 }
dbca89b7
GA
151 // -regtest only: allow overriding block.nVersion with
152 // -blockversion=N to test forking scenarios
153 if (Params().MineBlocksOnDemand())
154 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
155
4949004d
PW
156 // Add dummy coinbase tx as first transaction
157 pblock->vtx.push_back(CTransaction());
d247a5d1
JG
158 pblocktemplate->vTxFees.push_back(-1); // updated at end
159 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
160
161 // Largest block you're willing to create:
ad898b40 162 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
d247a5d1
JG
163 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
164 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
165
166 // How much of the block should be dedicated to high-priority transactions,
167 // included regardless of the fees they pay
168 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
169 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
170
171 // Minimum block size you want to create; block will be filled with free transactions
172 // until there are no more or the block reaches this size:
037b4f14 173 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
d247a5d1
JG
174 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
175
176 // Collect memory pool transactions into the block
a372168e 177 CAmount nFees = 0;
0655fac0 178
d247a5d1
JG
179 {
180 LOCK2(cs_main, mempool.cs);
48265f3c 181 CBlockIndex* pindexPrev = chainActive.Tip();
b867e409 182 const int nHeight = pindexPrev->nHeight + 1;
75a4d512 183 pblock->nTime = GetAdjustedTime();
a1d3c6fb 184 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
7c70438d 185 CCoinsViewCache view(pcoinsTip);
d247a5d1
JG
186
187 // Priority order to process transactions
188 list<COrphan> vOrphan; // list memory doesn't move
189 map<uint256, vector<COrphan*> > mapDependers;
190 bool fPrintPriority = GetBoolArg("-printpriority", false);
191
192 // This vector will be sorted into a priority queue:
193 vector<TxPriority> vecPriority;
194 vecPriority.reserve(mempool.mapTx.size());
4d707d51
GA
195 for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin();
196 mi != mempool.mapTx.end(); ++mi)
d247a5d1 197 {
4d707d51 198 const CTransaction& tx = mi->second.GetTx();
a1d3c6fb
MF
199
200 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
201 ? nMedianTimePast
202 : pblock->GetBlockTime();
203
204 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff))
d247a5d1
JG
205 continue;
206
207 COrphan* porphan = NULL;
208 double dPriority = 0;
a372168e 209 CAmount nTotalIn = 0;
d247a5d1
JG
210 bool fMissingInputs = false;
211 BOOST_FOREACH(const CTxIn& txin, tx.vin)
212 {
213 // Read prev transaction
214 if (!view.HaveCoins(txin.prevout.hash))
215 {
216 // This should never happen; all transactions in the memory
217 // pool should connect to either transactions in the chain
218 // or other transactions in the memory pool.
219 if (!mempool.mapTx.count(txin.prevout.hash))
220 {
881a85a2 221 LogPrintf("ERROR: mempool transaction missing input\n");
d247a5d1
JG
222 if (fDebug) assert("mempool transaction missing input" == 0);
223 fMissingInputs = true;
224 if (porphan)
225 vOrphan.pop_back();
226 break;
227 }
228
229 // Has to wait for dependencies
230 if (!porphan)
231 {
232 // Use list for automatic deletion
233 vOrphan.push_back(COrphan(&tx));
234 porphan = &vOrphan.back();
235 }
236 mapDependers[txin.prevout.hash].push_back(porphan);
237 porphan->setDependsOn.insert(txin.prevout.hash);
4d707d51 238 nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue;
d247a5d1
JG
239 continue;
240 }
629d75fa
PW
241 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
242 assert(coins);
d247a5d1 243
a372168e 244 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
d247a5d1
JG
245 nTotalIn += nValueIn;
246
b867e409 247 int nConf = nHeight - coins->nHeight;
d247a5d1
JG
248
249 dPriority += (double)nValueIn * nConf;
250 }
2b2bc69e
SB
251 nTotalIn += tx.GetJoinSplitValueIn();
252
d247a5d1
JG
253 if (fMissingInputs) continue;
254
d6eb2599 255 // Priority is sum(valuein * age) / modified_txsize
d247a5d1 256 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4d707d51 257 dPriority = tx.ComputePriority(dPriority, nTxSize);
d247a5d1 258
805344dc 259 uint256 hash = tx.GetHash();
2a72d459
LD
260 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
261
c6cb21d1 262 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
d247a5d1
JG
263
264 if (porphan)
265 {
266 porphan->dPriority = dPriority;
c6cb21d1 267 porphan->feeRate = feeRate;
d247a5d1
JG
268 }
269 else
c6cb21d1 270 vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx()));
d247a5d1
JG
271 }
272
273 // Collect transactions into block
51ed9ec9
BD
274 uint64_t nBlockSize = 1000;
275 uint64_t nBlockTx = 0;
355ca565 276 int64_t interest;
d247a5d1
JG
277 int nBlockSigOps = 100;
278 bool fSortedByFee = (nBlockPrioritySize <= 0);
279
280 TxPriorityCompare comparer(fSortedByFee);
281 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
282
283 while (!vecPriority.empty())
284 {
285 // Take highest priority transaction off the priority queue:
286 double dPriority = vecPriority.front().get<0>();
c6cb21d1 287 CFeeRate feeRate = vecPriority.front().get<1>();
4d707d51 288 const CTransaction& tx = *(vecPriority.front().get<2>());
d247a5d1
JG
289
290 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
291 vecPriority.pop_back();
292
293 // Size limits
294 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
295 if (nBlockSize + nTxSize >= nBlockMaxSize)
296 continue;
297
298 // Legacy limits on sigOps:
299 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
300 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
301 continue;
302
303 // Skip free transactions if we're past the minimum block size:
805344dc 304 const uint256& hash = tx.GetHash();
2a72d459 305 double dPriorityDelta = 0;
a372168e 306 CAmount nFeeDelta = 0;
2a72d459 307 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
13fc83c7 308 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
d247a5d1
JG
309 continue;
310
2a72d459 311 // Prioritise by fee once past the priority size or we run out of high-priority
d247a5d1
JG
312 // transactions:
313 if (!fSortedByFee &&
314 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
315 {
316 fSortedByFee = true;
317 comparer = TxPriorityCompare(fSortedByFee);
318 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
319 }
320
321 if (!view.HaveInputs(tx))
322 continue;
323
17878015 324 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
d247a5d1
JG
325
326 nTxSigOps += GetP2SHSigOpCount(tx, view);
327 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
328 continue;
329
68f7d1d7
PT
330 // Note that flags: we don't want to set mempool/IsStandard()
331 // policy here, but we still have to ensure that the block we
332 // create only contains transactions that are valid in new blocks.
d247a5d1 333 CValidationState state;
c0dde76d 334 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
d247a5d1
JG
335 continue;
336
d7621ccf 337 UpdateCoins(tx, state, view, nHeight);
d247a5d1
JG
338
339 // Added
340 pblock->vtx.push_back(tx);
341 pblocktemplate->vTxFees.push_back(nTxFees);
342 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
343 nBlockSize += nTxSize;
344 ++nBlockTx;
345 nBlockSigOps += nTxSigOps;
346 nFees += nTxFees;
347
348 if (fPrintPriority)
349 {
3f0813b3 350 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
d247a5d1
JG
351 }
352
353 // Add transactions that depend on this one to the priority queue
354 if (mapDependers.count(hash))
355 {
356 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
357 {
358 if (!porphan->setDependsOn.empty())
359 {
360 porphan->setDependsOn.erase(hash);
361 if (porphan->setDependsOn.empty())
362 {
c6cb21d1 363 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
d247a5d1
JG
364 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
365 }
366 }
367 }
368 }
369 }
370
371 nLastBlockTx = nBlockTx;
372 nLastBlockSize = nBlockSize;
f48742c2 373 LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize);
d247a5d1 374
f3ffa3d2
SB
375 // Create coinbase tx
376 CMutableTransaction txNew;
cad0d1ca 377 //txNew.nLockTime = (uint32_t)time(NULL) - 60;
f3ffa3d2
SB
378 txNew.vin.resize(1);
379 txNew.vin[0].prevout.SetNull();
d581f229 380 txNew.vout.resize(1);
f3ffa3d2 381 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
c9b1071d 382 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
f3ffa3d2
SB
383 // Add fees
384 txNew.vout[0].nValue += nFees;
b867e409 385 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
c9b1071d 386 if ( ASSETCHAINS_SYMBOL[0] == 0 )
387 {
388 int32_t i,opretlen; uint8_t opret[256],*ptr;
44caf46a 389 if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 )
c9b1071d 390 {
44caf46a 391 if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 ) // have pricefeed
d9a9d562 392 {
393 txNew.vout.resize(2);
394 txNew.vout[1].scriptPubKey.resize(opretlen);
395 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
396 for (i=0; i<opretlen; i++)
397 ptr[i] = opret[i];
398 txNew.vout[1].nValue = 0;
399 //fprintf(stderr,"opretlen.%d\n",opretlen);
400 }
d581f229 401 }
c9b1071d 402 }
654dfaaf 403 else if ( komodo_is_issuer() != 0 )
c9b1071d 404 {
7322eaa0 405 komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0);
13c01d29 406 //if ( txNew.vout.size() > 1 )
4a21ccd2 407 fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size());
c9b1071d 408 }
4949004d 409 pblock->vtx[0] = txNew;
d247a5d1 410 pblocktemplate->vTxFees[0] = -nFees;
8e165d57
JG
411 // Randomise nonce
412 arith_uint256 nonce = UintToArith256(GetRandHash());
413 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
414 nonce <<= 32;
415 nonce >>= 16;
416 pblock->nNonce = ArithToUint256(nonce);
417
d247a5d1
JG
418 // Fill in header
419 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
a8d384ae 420 pblock->hashReserved = uint256();
bebe7282 421 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
4f5e03db 422 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
fdda3c50 423 pblock->nSolution.clear();
d247a5d1
JG
424 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
425
d247a5d1 426 CValidationState state;
34ad681a 427 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
af805d53 428 {
7255df32 429 //static uint32_t counter;
430 //if ( counter++ < 100 )
d4190a2a 431 fprintf(stderr,"warning: testblockvalidity failed\n");
7255df32 432 //return(0);
17d204f5 433 //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
af805d53 434 }
d247a5d1
JG
435 }
436
437 return pblocktemplate.release();
438}
439
d247a5d1
JG
440void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
441{
442 // Update nExtraNonce
443 static uint256 hashPrevBlock;
444 if (hashPrevBlock != pblock->hashPrevBlock)
445 {
446 nExtraNonce = 0;
447 hashPrevBlock = pblock->hashPrevBlock;
448 }
449 ++nExtraNonce;
450 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4949004d
PW
451 CMutableTransaction txCoinbase(pblock->vtx[0]);
452 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
453 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
d247a5d1 454
4949004d 455 pblock->vtx[0] = txCoinbase;
d247a5d1
JG
456 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
457}
458
4a85e067 459#ifdef ENABLE_WALLET
acfa0333
WL
460//////////////////////////////////////////////////////////////////////////////
461//
462// Internal miner
463//
c142de7e 464int8_t komodo_minerid(int32_t height,uint8_t *pubkey33);
acfa0333 465
48265f3c 466CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
acfa0333 467{
f6c647ed 468 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
7bfc207a 469 if ( USE_EXTERNAL_PUBKEY != 0 )
998397aa 470 {
7bfc207a 471 //fprintf(stderr,"use notary pubkey\n");
c95fd5e0 472 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
f6c647ed 473 }
474 else
475 {
476 if (!reservekey.GetReservedKey(pubkey))
1b5b89ba 477 {
f6c647ed 478 return NULL;
1b5b89ba 479 }
f6c647ed 480 scriptPubKey.resize(35);
f66f65ec 481 ptr = (uint8_t *)pubkey.begin();
f6c647ed 482 script = (uint8_t *)scriptPubKey.data();
483 script[0] = 33;
484 for (i=0; i<33; i++)
485 script[i+1] = ptr[i];
486 script[34] = OP_CHECKSIG;
487 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
488 }
bbaa688c 489 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
5aab0392 490 {
491 for (i=0; i<65; i++)
c142de7e 492 fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i,0));
91b99766 493 fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight);
5aab0392 494 }
48265f3c 495 return CreateNewBlock(scriptPubKey);
acfa0333
WL
496}
497
269d8ba0 498static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
d247a5d1 499{
81212588 500 LogPrintf("%s\n", pblock->ToString());
35915149 501 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
d247a5d1
JG
502
503 // Found a solution
504 {
505 LOCK(cs_main);
4c6d41b8 506 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
2e500f50 507 return error("KomodoMiner: generated block is stale");
18e72167 508 }
d247a5d1 509
18e72167 510 // Remove key from key pool
998397aa 511 if ( IS_KOMODO_NOTARY == 0 )
512 reservekey.KeepKey();
d247a5d1 513
18e72167
PW
514 // Track how many getdata requests this block gets
515 {
516 LOCK(wallet.cs_wallet);
517 wallet.mapRequestCount[pblock->GetHash()] = 0;
d247a5d1
JG
518 }
519
18e72167
PW
520 // Process this block the same as if we had received it from another node
521 CValidationState state;
35915149 522 if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
2e500f50 523 return error("KomodoMiner: ProcessNewBlock, block not accepted");
18e72167 524
d793f94b 525 TrackMinedBlock(pblock->GetHash());
a6df7ab5 526
d247a5d1
JG
527 return true;
528}
529
078f6af1 530int32_t komodo_baseid(char *origbase);
8c654ec5 531int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height);
8ee93080 532int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
9152feb5 533extern int32_t KOMODO_LASTMINED;
078f6af1 534
d247a5d1
JG
535void static BitcoinMiner(CWallet *pwallet)
536{
2e500f50 537 LogPrintf("KomodoMiner started\n");
d247a5d1 538 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2e500f50 539 RenameThread("komodo-miner");
bebe7282 540 const CChainParams& chainparams = Params();
d247a5d1
JG
541
542 // Each thread has its own key and counter
543 CReserveKey reservekey(pwallet);
544 unsigned int nExtraNonce = 0;
545
e9574728
JG
546 unsigned int n = chainparams.EquihashN();
547 unsigned int k = chainparams.EquihashK();
755ead98 548 int32_t notaryid = -1;
e317db75 549 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
755ead98 550 {
551 sleep(1);
078f6af1 552 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
553 break;
755ead98 554 }
1a8be0dc 555 komodo_chosennotary(&notaryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33);
fdda3c50 556
755ead98 557 std::string solver;
e1e65cef 558 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
755ead98 559 solver = "tromp";
e1e65cef 560 //else solver = "default";
5f0009b2 561 assert(solver == "tromp" || solver == "default");
c7aaab7a 562 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
9ee43671 563 if ( ASSETCHAINS_SYMBOL[0] != 0 )
0d141325 564 fprintf(stderr,"notaryid.%d Mining with %s\n",notaryid,solver.c_str());
5a360a5c
JG
565 std::mutex m_cs;
566 bool cancelSolver = false;
567 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
568 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
569 std::lock_guard<std::mutex> lock{m_cs};
570 cancelSolver = true;
571 }
572 );
573
0655fac0 574 try {
ad84148d 575 if ( ASSETCHAINS_SYMBOL[0] != 0 )
c96df8ec 576 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
e725f1cb 577 while (true)
578 {
e317db75 579 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
e725f1cb 580 {
a96fd7b5 581 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
582 // break;
0655fac0
PK
583 // Busy-wait for the network to come online so we don't waste time mining
584 // on an obsolete chain. In regtest mode we expect to fly solo.
ad84148d 585 //fprintf(stderr,"Wait for peers...\n");
bba7c249
GM
586 do {
587 bool fvNodesEmpty;
588 {
589 LOCK(cs_vNodes);
590 fvNodesEmpty = vNodes.empty();
591 }
592 if (!fvNodesEmpty && !IsInitialBlockDownload())
593 break;
f8e367eb 594 MilliSleep(5000);
ad84148d 595 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
f8e367eb 596
bba7c249 597 } while (true);
ad84148d 598 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
0655fac0 599 }
f70ced6a 600 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
8fc7222d 601 {
602 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
603 sleep(3);
d82623d2 604 }*/
0655fac0
PK
605 //
606 // Create new block
607 //
608 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
48265f3c 609 CBlockIndex* pindexPrev = chainActive.Tip();
4940066c 610 if ( Mining_height != pindexPrev->nHeight+1 )
611 {
612 Mining_height = pindexPrev->nHeight+1;
613 Mining_start = (uint32_t)time(NULL);
614 }
7255df32 615 //if ( ASSETCHAINS_SYMBOL[0] != 0 )
3a9746d2 616 fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
08d0b73c 617 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
618 if ( ptr == 0 )
619 {
7255df32 620 //static uint32_t counter;
621 //if ( counter++ < 100 )
1b5b89ba 622 fprintf(stderr,"created illegal block, retry\n");
4fb9b706 623 //continue;
08d0b73c 624 }
625 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
0655fac0 626 if (!pblocktemplate.get())
6c37f7fd 627 {
2e500f50 628 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
0655fac0 629 return;
6c37f7fd 630 }
0655fac0
PK
631 CBlock *pblock = &pblocktemplate->block;
632 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
2e500f50 633 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
634 //
635 // Search
636 //
2c7ad758 637 uint8_t pubkeys[66][33]; int mids[66],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
404391b5 638 savebits = pblock->nBits;
3505af19 639 arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
52c2553f 640 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )//komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
5203fc4b 641 {
fda5f849 642 j = 65;
5a471ba9 643 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
fb6c7505 644 {
8c654ec5 645 komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight);
29e60e48 646 if ( nonzpkeys > 0 )
647 {
ccb71a6e 648 for (i=0; i<33; i++)
649 if( pubkeys[0][i] != 0 )
650 break;
651 if ( i == 33 )
652 externalflag = 1;
653 else externalflag = 0;
db409a6e 654 if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 )
b176c125 655 {
345e545e 656 for (i=1; i<66; i++)
657 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
658 break;
ccb71a6e 659 if ( externalflag == 0 && i != 66 )
345e545e 660 printf("VIOLATION at %d\n",i);
8958c5ba 661 for (i=0; i<66; i++)
9152feb5 662 {break;
8958c5ba 663 for (j=0; j<33; j++)
664 printf("%02x",pubkeys[i][j]);
665 printf(" p%d -> %d\n",i,komodo_minerid(pindexPrev->nHeight-i,pubkeys[i]));
8c654ec5 666 }
2c7ad758 667 for (j=gpucount=0; j<65; j++)
668 {
8958c5ba 669 fprintf(stderr,"%d ",mids[j]);
2c7ad758 670 if ( mids[j] == -1 )
671 gpucount++;
672 }
673 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%%\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j);
b176c125 674 }
29e60e48 675 for (j=0; j<65; j++)
676 if ( mids[j] == notaryid )
677 break;
965f0f7e 678 } else fprintf(stderr,"no nonz pubkeys\n");
5a471ba9 679 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+3 && Mining_height > KOMODO_LASTMINED+64) )
fda5f849 680 {
681 hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
682 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
683 } //else fprintf(stderr,"duplicate at j.%d\n",j);
fb6c7505 684 } else Mining_start = 0;
d7d27bb3 685 } else Mining_start = 0;
e725f1cb 686 while (true)
687 {
eaba9a27 688 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
7322eaa0 689 {
7d2c861c 690 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
4a21ccd2 691 sleep(10);
7322eaa0 692 break;
693 }
7213c0b1 694 // Hash state
8c22eb46 695 KOMODO_CHOSEN_ONE = 0;
7213c0b1 696 crypto_generichash_blake2b_state state;
e9574728 697 EhInitialiseState(n, k, state);
7213c0b1
JG
698 // I = the block header minus nonce and solution.
699 CEquihashInput I{*pblock};
700 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
701 ss << I;
7213c0b1
JG
702 // H(I||...
703 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
8e165d57
JG
704 // H(I||V||...
705 crypto_generichash_blake2b_state curr_state;
706 curr_state = state;
7a4c01c9 707 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
8e165d57 708 // (x_1, x_2, ...) = A(I, V, n, k)
7a4c01c9 709 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
6be3b162 710 //fprintf(stderr,"running solver\n");
5be6abbf 711 std::function<bool(std::vector<unsigned char>)> validBlock =
51eb5273 712 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
e5430f52 713 (std::vector<unsigned char> soln)
714 {
51eb5273
JG
715 // Write the solution to the hash and compute the result.
716 LogPrint("pow", "- Checking solution against target\n");
8e165d57 717 pblock->nSolution = soln;
e7d59bbc 718 solutionTargetChecks.increment();
7a4c01c9 719 if ( UintToArith256(pblock->GetHash()) > hashTarget )
e5430f52 720 {
bd6ef155 721 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
7c3b0491 722 // fprintf(stderr," missed target\n");
51eb5273 723 return false;
e5430f52 724 }
1e983efa 725 if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+ROUNDROBIN_DELAY )
d7d27bb3 726 {
6be3b162 727 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+ROUNDROBIN_DELAY-time(NULL)));
52e87248 728 int32_t nseconds = Mining_start+ROUNDROBIN_DELAY-time(NULL);
729 if ( nseconds > 0 )
730 sleep(nseconds);
320a2e35 731 MilliSleep((rand() % 1700) + 1);
d7d27bb3 732 }
b3183e3e 733 KOMODO_CHOSEN_ONE = 1;
8e165d57
JG
734 // Found a solution
735 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2e500f50 736 LogPrintf("KomodoMiner:\n");
a6a0d913 737 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
5a360a5c 738 if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
a6a0d913 739 // Ignore chain updates caused by us
740 std::lock_guard<std::mutex> lock{m_cs};
5a360a5c
JG
741 cancelSolver = false;
742 }
8c22eb46 743 KOMODO_CHOSEN_ONE = 0;
8e165d57 744 SetThreadPriority(THREAD_PRIORITY_LOWEST);
8e165d57 745 // In regression test mode, stop mining after a block is found.
a6df7ab5
JG
746 if (chainparams.MineBlocksOnDemand()) {
747 // Increment here because throwing skips the call below
748 ehSolverRuns.increment();
8e165d57 749 throw boost::thread_interrupted();
a6df7ab5 750 }
b78471c2 751 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
752 // sleep(1800);
51eb5273
JG
753 return true;
754 };
755 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
756 std::lock_guard<std::mutex> lock{m_cs};
757 return cancelSolver;
758 };
c7aaab7a 759
5f0009b2 760 // TODO: factor this out into a function with the same API for each solver.
e1e65cef 761 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
c7aaab7a
DH
762 // Create solver and initialize it.
763 equi eq(1);
764 eq.setstate(&curr_state);
765
766 // Intialization done, start algo driver.
767 eq.digit0(0);
768 eq.xfull = eq.bfull = eq.hfull = 0;
769 eq.showbsizes(0);
770 for (u32 r = 1; r < WK; r++) {
771 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
772 eq.xfull = eq.bfull = eq.hfull = 0;
773 eq.showbsizes(r);
774 }
775 eq.digitK(0);
a6df7ab5 776 ehSolverRuns.increment();
c7aaab7a
DH
777
778 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
779 for (size_t s = 0; s < eq.nsols; s++) {
780 LogPrint("pow", "Checking solution %d\n", s+1);
781 std::vector<eh_index> index_vector(PROOFSIZE);
782 for (size_t i = 0; i < PROOFSIZE; i++) {
783 index_vector[i] = eq.sols[s][i];
784 }
785 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
786
787 if (validBlock(sol_char)) {
788 // If we find a POW solution, do not try other solutions
789 // because they become invalid as we created a new block in blockchain.
790 break;
791 }
792 }
793 } else {
794 try {
795 // If we find a valid block, we rebuild
a6df7ab5
JG
796 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
797 ehSolverRuns.increment();
798 if (found) {
a8aa4375 799 int32_t i; uint256 hash = pblock->GetHash();
800 for (i=0; i<32; i++)
801 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
802 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
b78471c2 803 FOUND_BLOCK = 1;
8ee93080 804 KOMODO_MAYBEMINED = Mining_height;
c7aaab7a 805 break;
a6df7ab5 806 }
c7aaab7a
DH
807 } catch (EhSolverCancelledException&) {
808 LogPrint("pow", "Equihash solver cancelled\n");
809 std::lock_guard<std::mutex> lock{m_cs};
810 cancelSolver = false;
811 }
48265f3c 812 }
d247a5d1 813
0655fac0
PK
814 // Check for stop or if block needs to be rebuilt
815 boost::this_thread::interruption_point();
816 // Regtest mode doesn't require peers
b78471c2 817 if ( FOUND_BLOCK != 0 )
818 {
819 FOUND_BLOCK = 0;
820 fprintf(stderr,"FOUND_BLOCK!\n");
9152feb5 821 //sleep(2000);
b78471c2 822 }
bebe7282 823 if (vNodes.empty() && chainparams.MiningRequiresPeers())
e5430f52 824 {
f70ced6a 825 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
10694486 826 {
bd6ef155 827 fprintf(stderr,"no nodes, break\n");
d90cef0b 828 break;
10694486 829 }
e5430f52 830 }
8e165d57 831 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
e5430f52 832 {
6be3b162 833 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 834 fprintf(stderr,"0xffff, break\n");
0655fac0 835 break;
e5430f52 836 }
0655fac0 837 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
e5430f52 838 {
6be3b162 839 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 840 fprintf(stderr,"timeout, break\n");
0655fac0 841 break;
e5430f52 842 }
843 if ( pindexPrev != chainActive.Tip() )
844 {
6be3b162 845 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
10694486 846 fprintf(stderr,"Tip advanced, break\n");
0655fac0 847 break;
e5430f52 848 }
8e165d57
JG
849 // Update nNonce and nTime
850 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
404391b5 851 pblock->nBits = savebits;
bebe7282
JT
852 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
853 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
48265f3c
WL
854 {
855 // Changing pblock->nTime can change work required on testnet:
856 hashTarget.SetCompact(pblock->nBits);
857 }
d247a5d1
JG
858 }
859 }
0655fac0 860 }
27df4123 861 catch (const boost::thread_interrupted&)
d247a5d1 862 {
5e9b555f 863 c.disconnect();
2e500f50 864 LogPrintf("KomodoMiner terminated\n");
d247a5d1
JG
865 throw;
866 }
bba7c249
GM
867 catch (const std::runtime_error &e)
868 {
5e9b555f 869 c.disconnect();
2e500f50 870 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
bba7c249
GM
871 return;
872 }
5a360a5c 873 c.disconnect();
d247a5d1
JG
874}
875
c8b74258 876void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
d247a5d1
JG
877{
878 static boost::thread_group* minerThreads = NULL;
879
d247a5d1 880 if (nThreads < 0) {
2595b9ac 881 // In regtest threads defaults to 1
882 if (Params().DefaultMinerThreads())
883 nThreads = Params().DefaultMinerThreads();
d247a5d1
JG
884 else
885 nThreads = boost::thread::hardware_concurrency();
886 }
887
888 if (minerThreads != NULL)
889 {
890 minerThreads->interrupt_all();
891 delete minerThreads;
892 minerThreads = NULL;
893 }
894
895 if (nThreads == 0 || !fGenerate)
896 return;
897
898 minerThreads = new boost::thread_group();
899 for (int i = 0; i < nThreads; i++)
900 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
901}
902
0655fac0 903#endif // ENABLE_WALLET
This page took 0.434986 seconds and 4 git commands to generate.