1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2013 The NovaCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "txdb-leveldb.h"
10 #include "kernel_worker.h"
13 //////////////////////////////////////////////////////////////////////////////
18 int64_t nReserveBalance = 0;
19 static unsigned int nMaxStakeSearchInterval = 60;
20 uint64_t nStakeInputsMapSize = 0;
22 int static FormatHashBlocks(void* pbuffer, unsigned int len)
24 unsigned char* pdata = (unsigned char*)pbuffer;
25 unsigned int blocks = 1 + ((len + 8) / 64);
26 unsigned char* pend = pdata + 64 * blocks;
27 memset(pdata + len, 0, 64 * blocks - len);
29 unsigned int bits = len * 8;
30 pend[-1] = (bits >> 0) & 0xff;
31 pend[-2] = (bits >> 8) & 0xff;
32 pend[-3] = (bits >> 16) & 0xff;
33 pend[-4] = (bits >> 24) & 0xff;
37 static const unsigned int pSHA256InitState[8] =
38 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
40 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
43 unsigned char data[64];
47 for (int i = 0; i < 16; i++)
48 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
50 for (int i = 0; i < 8; i++)
51 ctx.h[i] = ((uint32_t*)pinit)[i];
53 SHA256_Update(&ctx, data, sizeof(data));
54 for (int i = 0; i < 8; i++)
55 ((uint32_t*)pstate)[i] = ctx.h[i];
58 // Some explaining would be appreciated
63 std::set<uint256> setDependsOn;
67 COrphan(CTransaction* ptxIn)
70 dPriority = dFeePerKb = 0;
75 uint64_t nLastBlockTx = 0;
76 uint64_t nLastBlockSize = 0;
77 uint32_t nLastCoinStakeSearchInterval = 0;
79 // We want to sort transactions by priority and fee, so:
80 typedef std::tuple<double, double, CTransaction*> TxPriority;
81 class TxPriorityCompare
85 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
86 bool operator()(const TxPriority& a, const TxPriority& b)
90 if (std::get<1>(a) == std::get<1>(b))
91 return std::get<0>(a) < std::get<0>(b);
92 return std::get<1>(a) < std::get<1>(b);
96 if (std::get<0>(a) == std::get<0>(b))
97 return std::get<1>(a) < std::get<1>(b);
98 return std::get<0>(a) < std::get<0>(b);
103 // CreateNewBlock: create new block (without proof-of-work/with provided coinstake)
104 std::shared_ptr<CBlock> CreateNewBlock(CWallet* pwallet, CTransaction *txCoinStake)
106 bool fProofOfStake = txCoinStake != nullptr;
109 std::shared_ptr<CBlock> pblock(new CBlock());
113 // Create coinbase tx
114 CTransaction txCoinBase;
115 txCoinBase.vin.resize(1);
116 txCoinBase.vin[0].prevout.SetNull();
117 txCoinBase.vout.resize(1);
121 CReserveKey reservekey(pwallet);
122 txCoinBase.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
124 // Add our coinbase tx as first transaction
125 pblock->vtx.push_back(txCoinBase);
129 // Coinbase output must be empty for Proof-of-Stake block
130 txCoinBase.vout[0].SetEmpty();
132 // Syncronize timestamps
133 pblock->nTime = txCoinBase.nTime = txCoinStake->nTime;
135 // Add coinbase and coinstake transactions
136 pblock->vtx.push_back(txCoinBase);
137 pblock->vtx.push_back(*txCoinStake);
140 // Largest block you're willing to create:
141 unsigned int nBlockMaxSize = GetArgUInt("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
142 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
143 nBlockMaxSize = std::max(1000u, std::min(MAX_BLOCK_SIZE-1000u, nBlockMaxSize));
145 // How much of the block should be dedicated to high-priority transactions,
146 // included regardless of the fees they pay
147 unsigned int nBlockPrioritySize = GetArgUInt("-blockprioritysize", 27000);
148 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
150 // Minimum block size you want to create; block will be filled with free transactions
151 // until there are no more or the block reaches this size:
152 unsigned int nBlockMinSize = GetArgUInt("-blockminsize", 0);
153 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
155 // Fee-per-kilobyte amount considered the same as "free"
156 // Be careful setting this: if you set it to zero then
157 // a transaction spammer can cheaply fill blocks using
158 // 1-satoshi-fee transactions. It should be set above the real
159 // cost to you of processing a transaction.
160 int64_t nMinTxFee = MIN_TX_FEE;
161 if (mapArgs.count("-mintxfee")) {
162 bool fResult = ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
163 if (!fResult) // Parse error
164 nMinTxFee = MIN_TX_FEE;
167 CBlockIndex* pindexPrev = pindexBest;
169 pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
171 // Collect memory pool transactions into the block
174 LOCK2(cs_main, mempool.cs);
175 CBlockIndex* pindexPrev = pindexBest;
178 // Priority order to process transactions
179 std::list<COrphan> vOrphan; // list memory doesn't move
180 std::map<uint256, std::vector<COrphan*> > mapDependers;
182 // This vector will be sorted into a priority queue:
183 std::vector<TxPriority> vecPriority;
184 vecPriority.reserve(mempool.mapTx.size());
185 for (std::map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
187 CTransaction& tx = (*mi).second;
188 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
191 COrphan* porphan = nullptr;
192 double dPriority = 0;
193 int64_t nTotalIn = 0;
194 bool fMissingInputs = false;
195 for (const CTxIn& txin : tx.vin)
197 // Read prev transaction
200 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
202 // This should never happen; all transactions in the memory
203 // pool should connect to either transactions in the chain
204 // or other transactions in the memory pool.
205 if (!mempool.mapTx.count(txin.prevout.hash))
207 printf("ERROR: mempool transaction missing input\n");
208 if (fDebug) assert("mempool transaction missing input" == 0);
209 fMissingInputs = true;
215 // Has to wait for dependencies
218 // Use list for automatic deletion
219 vOrphan.push_back(COrphan(&tx));
220 porphan = &vOrphan.back();
222 mapDependers[txin.prevout.hash].push_back(porphan);
223 porphan->setDependsOn.insert(txin.prevout.hash);
224 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
227 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
228 nTotalIn += nValueIn;
230 int nConf = txindex.GetDepthInMainChain();
231 dPriority += (double)nValueIn * nConf;
233 if (fMissingInputs) continue;
235 // Priority is sum(valuein * age) / txsize
236 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
237 dPriority /= nTxSize;
239 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
240 // client code rounds up the size to the nearest 1K. That's good, because it gives an
241 // incentive to create smaller transactions.
242 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
246 porphan->dPriority = dPriority;
247 porphan->dFeePerKb = dFeePerKb;
250 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
253 // Collect transactions into block
254 std::map<uint256, CTxIndex> mapTestPool;
255 uint64_t nBlockSize = 1000;
256 uint64_t nBlockTx = 0;
257 int nBlockSigOps = 100;
258 bool fSortedByFee = (nBlockPrioritySize <= 0);
260 TxPriorityCompare comparer(fSortedByFee);
261 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
263 while (!vecPriority.empty())
265 // Take highest priority transaction off the priority queue:
266 double dPriority = std::get<0>(vecPriority.front());
267 double dFeePerKb = std::get<1>(vecPriority.front());
268 CTransaction& tx = *(std::get<2>(vecPriority.front()));
270 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
271 vecPriority.pop_back();
274 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
275 if (nBlockSize + nTxSize >= nBlockMaxSize)
278 // Legacy limits on sigOps:
279 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
280 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
284 if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > txCoinStake->nTime))
287 // Skip free transactions if we're past the minimum block size:
288 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
291 // Prioritize by fee once past the priority size or we run out of high-priority
294 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
297 comparer = TxPriorityCompare(fSortedByFee);
298 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
301 // Connecting shouldn't fail due to dependency on other memory pool transactions
302 // because we're already processing them in order of dependency
303 std::map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
306 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
310 int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
311 int64_t nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
312 if (nTxFees < nMinFee)
315 // Sigops accumulation
316 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
317 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
320 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, true, MANDATORY_SCRIPT_VERIFY_FLAGS))
322 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
323 swap(mapTestPool, mapTestPoolTmp);
326 pblock->vtx.push_back(tx);
327 nBlockSize += nTxSize;
329 nBlockSigOps += nTxSigOps;
332 if (fDebug && GetBoolArg("-printpriority"))
334 printf("priority %.1f feeperkb %.1f txid %s\n",
335 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
338 // Add transactions that depend on this one to the priority queue
339 uint256 hash = tx.GetHash();
340 if (mapDependers.count(hash))
342 for (COrphan* porphan : mapDependers[hash])
344 if (!porphan->setDependsOn.empty())
346 porphan->setDependsOn.erase(hash);
347 if (porphan->setDependsOn.empty())
349 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
350 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
357 nLastBlockTx = nBlockTx;
358 nLastBlockSize = nBlockSize;
362 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits) + nFees;
365 printf("CreateNewBlock(): PoW reward %" PRIu64 "\n", pblock->vtx[0].vout[0].nValue);
368 if (fDebug && GetBoolArg("-printpriority"))
369 printf("CreateNewBlock(): total size %" PRIu64 "\n", nBlockSize);
372 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
375 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
376 pblock->nTime = std::max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
377 pblock->UpdateTime(pindexPrev);
386 void IncrementExtraNonce(std::shared_ptr<CBlock>& pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
388 // Update nExtraNonce
389 static uint256 hashPrevBlock;
390 if (hashPrevBlock != pblock->hashPrevBlock)
393 hashPrevBlock = pblock->hashPrevBlock;
397 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
398 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
399 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
401 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
405 void FormatHashBuffers(const std::shared_ptr<CBlock>& pblock, char* pmidstate, char* pdata, char* phash1)
408 // Pre-build hash buffers
415 uint256 hashPrevBlock;
416 uint256 hashMerkleRoot;
422 unsigned char pchPadding0[64];
424 unsigned char pchPadding1[64];
427 memset(&tmp, 0, sizeof(tmp));
429 tmp.block.nVersion = pblock->nVersion;
430 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
431 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
432 tmp.block.nTime = pblock->nTime;
433 tmp.block.nBits = pblock->nBits;
434 tmp.block.nNonce = pblock->nNonce;
436 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
437 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
439 // Byte swap all the input buffer
440 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
441 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
443 // Precalc the first half of the first hash, which stays constant
444 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
446 memcpy(pdata, &tmp.block, 128);
447 memcpy(phash1, &tmp.hash1, 64);
451 bool CheckWork(const std::shared_ptr<CBlock>& pblock, CWallet& wallet, CReserveKey& reservekey)
453 uint256 hashBlock = pblock->GetHash();
454 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
456 if(!pblock->IsProofOfWork())
457 return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
459 if (hashBlock > hashTarget)
460 return error("CheckWork() : proof-of-work not meeting target");
463 printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
465 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
470 if (pblock->hashPrevBlock != hashBestChain)
471 return error("CheckWork() : generated block is stale");
473 // Remove key from key pool
474 reservekey.KeepKey();
476 // Track how many getdata requests this block gets
478 LOCK(wallet.cs_wallet);
479 wallet.mapRequestCount[hashBlock] = 0;
482 // Process this block the same as if we had received it from another node
483 if (!ProcessBlock(nullptr, pblock.get()))
484 return error("CheckWork() : ProcessBlock, block not accepted");
490 bool CheckStake(const std::shared_ptr<CBlock>& pblock, CWallet& wallet)
492 uint256 proofHash = 0, hashTarget = 0;
493 uint256 hashBlock = pblock->GetHash();
495 if(!pblock->IsProofOfStake())
496 return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
498 // verify hash target and signature of coinstake tx
499 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
500 return error("CheckStake() : proof-of-stake checking failed");
503 printf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str());
505 printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
510 if (pblock->hashPrevBlock != hashBestChain)
511 return error("CheckStake() : generated block is stale");
513 // Track how many getdata requests this block gets
515 LOCK(wallet.cs_wallet);
516 wallet.mapRequestCount[hashBlock] = 0;
519 // Process this block the same as if we had received it from another node
520 if (!ProcessBlock(nullptr, pblock.get()))
521 return error("CheckStake() : ProcessBlock, block not accepted");
527 // Precalculated SHA256 contexts and metadata
528 // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
529 typedef std::map<std::pair<uint256, unsigned int>, std::pair<std::vector<unsigned char>, std::pair<uint32_t, uint64_t> > > MidstateMap;
531 // Fill the inputs map with precalculated contexts and metadata
532 bool FillMap(CWallet *pwallet, uint32_t nUpperTime, MidstateMap &inputsMap)
534 // Choose coins to use
535 int64_t nBalance = pwallet->GetBalance();
537 if (nBalance <= nReserveBalance)
540 uint32_t nTime = GetAdjustedTime();
544 LOCK2(cs_main, pwallet->cs_wallet);
547 int64_t nValueIn = 0;
548 if (!pwallet->SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nUpperTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
549 return error("FillMap() : SelectCoinsSimple failed");
551 if (setCoins.empty())
557 for(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
559 std::pair<uint256, uint32_t> key = {pcoin->first->GetHash(), pcoin->second};
561 // Skip existent inputs
562 if (inputsMap.find(key) != inputsMap.end())
565 // Trying to parse scriptPubKey
566 txnouttype whichType;
567 std::vector<valtype> vSolutions;
568 if (!Solver(pcoin->first->vout[pcoin->second].scriptPubKey, whichType, vSolutions))
571 // Only support pay to public key and pay to address
572 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
575 // Load transaction index item
576 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
580 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
583 // Only load coins meeting min age requirement
584 if (nStakeMinAge + block.nTime > nTime - nMaxStakeSearchInterval)
587 // Get stake modifier
588 uint64_t nStakeModifier = 0;
589 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
592 // Build static part of kernel
593 CDataStream ssKernel(SER_GETHASH, 0);
594 ssKernel << nStakeModifier;
595 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin->first->nTime << pcoin->second;
597 // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
598 inputsMap[key] = {std::vector<unsigned char>(ssKernel.begin(), ssKernel.end()), {pcoin->first->nTime, pcoin->first->vout[pcoin->second].nValue}};
601 nStakeInputsMapSize = inputsMap.size();
604 printf("FillMap() : Map of %" PRIu64 " precalculated contexts has been created by stake miner\n", nStakeInputsMapSize);
610 // Scan inputs map in order to find a solution
611 bool ScanMap(const MidstateMap &inputsMap, uint32_t nBits, MidstateMap::key_type &LuckyInput, std::pair<uint256, uint32_t> &solution)
613 static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
614 uint32_t nSearchTime = GetAdjustedTime();
616 if (inputsMap.size() > 0 && nSearchTime > nLastCoinStakeSearchTime)
618 // Scanning interval (begintime, endtime)
619 std::pair<uint32_t, uint32_t> interval;
621 interval.first = nSearchTime;
622 interval.second = nSearchTime - std::min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
624 // (txid, nout) => (kernel, (tx.nTime, nAmount))
625 for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
627 unsigned char *kernel = (unsigned char *) &input->second.first[0];
629 // scan(State, Bits, Time, Amount, ...)
630 if (ScanKernelBackward(kernel, nBits, input->second.second.first, input->second.second.second, interval, solution))
633 LuckyInput = input->first; // (txid, nout)
639 // Inputs map iteration can be big enough to consume few seconds while scanning.
640 // We're using dynamical calculation of scanning interval in order to compensate this delay.
641 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
642 nLastCoinStakeSearchTime = nSearchTime;
645 // No solutions were found
649 // Stake miner thread
650 void ThreadStakeMiner(void* parg)
652 SetThreadPriority(THREAD_PRIORITY_LOWEST);
654 // Make this thread recognisable as the mining thread
655 RenameThread("novacoin-miner");
656 CWallet* pwallet = (CWallet*)parg;
658 MidstateMap inputsMap;
659 if (!FillMap(pwallet, GetAdjustedTime(), inputsMap))
662 bool fTrySync = true;
664 CBlockIndex* pindexPrev = pindexBest;
665 uint32_t nBits = GetNextTargetRequired(pindexPrev, true);
667 printf("ThreadStakeMinter started\n");
671 vnThreadsRunning[THREAD_MINTER]++;
673 MidstateMap::key_type LuckyInput;
674 std::pair<uint256, uint32_t> solution;
682 while (pwallet->IsLocked())
686 goto _endloop; // Don't be afraid to use a goto if that's the best option.
689 while (vNodes.empty() || IsInitialBlockDownload())
700 // Don't try mine blocks unless we're at the top of chain and have at least three p2p connections.
702 if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
709 if (ScanMap(inputsMap, nBits, LuckyInput, solution))
711 SetThreadPriority(THREAD_PRIORITY_NORMAL);
713 // Remove lucky input from the map
714 inputsMap.erase(inputsMap.find(LuckyInput));
717 CTransaction txCoinStake;
719 // Create new coinstake transaction
720 if (!pwallet->CreateCoinStake(LuckyInput.first, LuckyInput.second, solution.second, nBits, txCoinStake, key))
722 std::string strMessage = _("Warning: Unable to create coinstake transaction, see debug.log for the details. Mining thread has been stopped.");
723 strMiscWarning = strMessage;
724 printf("*** %s\n", strMessage.c_str());
729 // Now we have new coinstake, it's time to create the block ...
730 std::shared_ptr<CBlock> pblock = CreateNewBlock(pwallet, &txCoinStake);
733 std::string strMessage = _("Warning: Unable to allocate memory for the new block object. Mining thread has been stopped.");
734 strMiscWarning = strMessage;
735 printf("*** %s\n", strMessage.c_str());
740 unsigned int nExtraNonce = 0;
741 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
744 if (!key.Sign(pblock->GetHash(), pblock->vchBlockSig))
746 std::string strMessage = _("Warning: Proof-of-Stake miner is unable to sign the block (locked wallet?). Mining thread has been stopped.");
747 strMiscWarning = strMessage;
748 printf("*** %s\n", strMessage.c_str());
753 CheckStake(pblock, *pwallet);
754 SetThreadPriority(THREAD_PRIORITY_LOWEST);
758 if (pindexPrev != pindexBest)
760 // The best block has been changed, we need to refill the map
761 if (FillMap(pwallet, GetAdjustedTime(), inputsMap))
763 pindexPrev = pindexBest;
764 nBits = GetNextTargetRequired(pindexPrev, true);
768 // Clear existent data if FillMap failed
776 (void)0; // do nothing
780 vnThreadsRunning[THREAD_MINTER]--;
782 catch (std::exception& e) {
783 vnThreadsRunning[THREAD_MINTER]--;
784 PrintException(&e, "ThreadStakeMinter()");
786 vnThreadsRunning[THREAD_MINTER]--;
787 PrintException(nullptr, "ThreadStakeMinter()");
789 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);