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