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