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