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"
14 //////////////////////////////////////////////////////////////////////////////
19 int64_t nReserveBalance = 0;
20 static unsigned int nMaxStakeSearchInterval = 60;
21 uint64_t nStakeInputsMapSize = 0;
23 int static FormatHashBlocks(void* pbuffer, unsigned int len)
25 unsigned char* pdata = (unsigned char*)pbuffer;
26 unsigned int blocks = 1 + ((len + 8) / 64);
27 unsigned char* pend = pdata + 64 * blocks;
28 memset(pdata + len, 0, 64 * blocks - len);
30 unsigned int bits = len * 8;
31 pend[-1] = (bits >> 0) & 0xff;
32 pend[-2] = (bits >> 8) & 0xff;
33 pend[-3] = (bits >> 16) & 0xff;
34 pend[-4] = (bits >> 24) & 0xff;
38 static const unsigned int pSHA256InitState[8] =
39 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
41 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
44 unsigned char data[64];
48 for (int i = 0; i < 16; i++)
49 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
51 for (int i = 0; i < 8; i++)
52 ctx.h[i] = ((uint32_t*)pinit)[i];
54 SHA256_Update(&ctx, data, sizeof(data));
55 for (int i = 0; i < 8; i++)
56 ((uint32_t*)pstate)[i] = ctx.h[i];
59 // Some explaining would be appreciated
64 std::set<uint256> setDependsOn;
68 COrphan(CTransaction* ptxIn)
71 dPriority = dFeePerKb = 0;
76 uint64_t nLastBlockTx = 0;
77 uint64_t nLastBlockSize = 0;
78 uint32_t nLastCoinStakeSearchInterval = 0;
80 // We want to sort transactions by priority and fee, so:
81 typedef std::tuple<double, double, CTransaction*> TxPriority;
82 class TxPriorityCompare
86 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
87 bool operator()(const TxPriority& a, const TxPriority& b)
91 if (std::get<1>(a) == std::get<1>(b))
92 return std::get<0>(a) < std::get<0>(b);
93 return std::get<1>(a) < std::get<1>(b);
97 if (std::get<0>(a) == std::get<0>(b))
98 return std::get<1>(a) < std::get<1>(b);
99 return std::get<0>(a) < std::get<0>(b);
104 // CreateNewBlock: create new block (without proof-of-work/with provided coinstake)
105 std::shared_ptr<CBlock> CreateNewBlock(CWallet* pwallet, CTransaction *txCoinStake)
107 bool fProofOfStake = txCoinStake != nullptr;
110 std::shared_ptr<CBlock> pblock(new CBlock());
114 // Create coinbase tx
115 CTransaction txCoinBase;
116 txCoinBase.vin.resize(1);
117 txCoinBase.vin[0].prevout.SetNull();
118 txCoinBase.vout.resize(1);
122 CReserveKey reservekey(pwallet);
123 txCoinBase.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
125 // Add our coinbase tx as first transaction
126 pblock->vtx.push_back(txCoinBase);
130 // Coinbase output must be empty for Proof-of-Stake block
131 txCoinBase.vout[0].SetEmpty();
133 // Syncronize timestamps
134 pblock->nTime = txCoinBase.nTime = txCoinStake->nTime;
136 // Add coinbase and coinstake transactions
137 pblock->vtx.push_back(txCoinBase);
138 pblock->vtx.push_back(*txCoinStake);
141 // Largest block you're willing to create:
142 unsigned int nBlockMaxSize = GetArgUInt("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
143 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
144 nBlockMaxSize = std::max(1000u, std::min(MAX_BLOCK_SIZE-1000u, nBlockMaxSize));
146 // How much of the block should be dedicated to high-priority transactions,
147 // included regardless of the fees they pay
148 unsigned int nBlockPrioritySize = GetArgUInt("-blockprioritysize", 27000);
149 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
151 // Minimum block size you want to create; block will be filled with free transactions
152 // until there are no more or the block reaches this size:
153 unsigned int nBlockMinSize = GetArgUInt("-blockminsize", 0);
154 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
156 // Fee-per-kilobyte amount considered the same as "free"
157 // Be careful setting this: if you set it to zero then
158 // a transaction spammer can cheaply fill blocks using
159 // 1-satoshi-fee transactions. It should be set above the real
160 // cost to you of processing a transaction.
161 int64_t nMinTxFee = MIN_TX_FEE;
162 if (mapArgs.count("-mintxfee")) {
163 bool fResult = ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
164 if (!fResult) // Parse error
165 nMinTxFee = MIN_TX_FEE;
168 CBlockIndex* pindexPrev = pindexBest;
170 pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
172 // Collect memory pool transactions into the block
175 LOCK2(cs_main, mempool.cs);
176 CBlockIndex* pindexPrev = pindexBest;
179 // Priority order to process transactions
180 std::list<COrphan> vOrphan; // list memory doesn't move
181 std::map<uint256, std::vector<COrphan*> > mapDependers;
183 // This vector will be sorted into a priority queue:
184 std::vector<TxPriority> vecPriority;
185 vecPriority.reserve(mempool.mapTx.size());
186 for (std::map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
188 CTransaction& tx = (*mi).second;
189 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
192 COrphan* porphan = nullptr;
193 double dPriority = 0;
194 int64_t nTotalIn = 0;
195 bool fMissingInputs = false;
196 for (const CTxIn& txin : tx.vin)
198 // Read prev transaction
201 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
203 // This should never happen; all transactions in the memory
204 // pool should connect to either transactions in the chain
205 // or other transactions in the memory pool.
206 if (!mempool.mapTx.count(txin.prevout.hash))
208 printf("ERROR: mempool transaction missing input\n");
209 if (fDebug) assert("mempool transaction missing input" == 0);
210 fMissingInputs = true;
216 // Has to wait for dependencies
219 // Use list for automatic deletion
220 vOrphan.push_back(COrphan(&tx));
221 porphan = &vOrphan.back();
223 mapDependers[txin.prevout.hash].push_back(porphan);
224 porphan->setDependsOn.insert(txin.prevout.hash);
225 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
228 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
229 nTotalIn += nValueIn;
231 int nConf = txindex.GetDepthInMainChain();
232 dPriority += (double)nValueIn * nConf;
234 if (fMissingInputs) continue;
236 // Priority is sum(valuein * age) / txsize
237 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
238 dPriority /= nTxSize;
240 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
241 // client code rounds up the size to the nearest 1K. That's good, because it gives an
242 // incentive to create smaller transactions.
243 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
247 porphan->dPriority = dPriority;
248 porphan->dFeePerKb = dFeePerKb;
251 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
254 // Collect transactions into block
255 std::map<uint256, CTxIndex> mapTestPool;
256 uint64_t nBlockSize = 1000;
257 uint64_t nBlockTx = 0;
258 int nBlockSigOps = 100;
259 bool fSortedByFee = (nBlockPrioritySize <= 0);
261 TxPriorityCompare comparer(fSortedByFee);
262 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
264 while (!vecPriority.empty())
266 // Take highest priority transaction off the priority queue:
267 double dPriority = std::get<0>(vecPriority.front());
268 double dFeePerKb = std::get<1>(vecPriority.front());
269 CTransaction& tx = *(std::get<2>(vecPriority.front()));
271 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
272 vecPriority.pop_back();
275 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
276 if (nBlockSize + nTxSize >= nBlockMaxSize)
279 // Legacy limits on sigOps:
280 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
281 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
285 if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > txCoinStake->nTime))
288 // Skip free transactions if we're past the minimum block size:
289 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
292 // Prioritize by fee once past the priority size or we run out of high-priority
295 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
298 comparer = TxPriorityCompare(fSortedByFee);
299 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
302 // Connecting shouldn't fail due to dependency on other memory pool transactions
303 // because we're already processing them in order of dependency
304 std::map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
307 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
311 int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
312 int64_t nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
313 if (nTxFees < nMinFee)
316 // Sigops accumulation
317 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
318 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
321 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, true, MANDATORY_SCRIPT_VERIFY_FLAGS))
323 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
324 swap(mapTestPool, mapTestPoolTmp);
327 pblock->vtx.push_back(tx);
328 nBlockSize += nTxSize;
330 nBlockSigOps += nTxSigOps;
333 if (fDebug && GetBoolArg("-printpriority"))
335 printf("priority %.1f feeperkb %.1f txid %s\n",
336 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
339 // Add transactions that depend on this one to the priority queue
340 uint256 hash = tx.GetHash();
341 if (mapDependers.count(hash))
343 for (COrphan* porphan : mapDependers[hash])
345 if (!porphan->setDependsOn.empty())
347 porphan->setDependsOn.erase(hash);
348 if (porphan->setDependsOn.empty())
350 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
351 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
358 nLastBlockTx = nBlockTx;
359 nLastBlockSize = nBlockSize;
363 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits) + nFees;
366 printf("CreateNewBlock(): PoW reward %" PRIu64 "\n", pblock->vtx[0].vout[0].nValue);
369 if (fDebug && GetBoolArg("-printpriority"))
370 printf("CreateNewBlock(): total size %" PRIu64 "\n", nBlockSize);
373 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
376 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
377 pblock->nTime = std::max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
378 pblock->UpdateTime(pindexPrev);
387 void IncrementExtraNonce(std::shared_ptr<CBlock>& pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
389 // Update nExtraNonce
390 static uint256 hashPrevBlock;
391 if (hashPrevBlock != pblock->hashPrevBlock)
394 hashPrevBlock = pblock->hashPrevBlock;
398 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
399 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
400 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
402 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
406 void FormatHashBuffers(const std::shared_ptr<CBlock>& pblock, char* pmidstate, char* pdata, char* phash1)
409 // Pre-build hash buffers
416 uint256 hashPrevBlock;
417 uint256 hashMerkleRoot;
423 unsigned char pchPadding0[64];
425 unsigned char pchPadding1[64];
428 memset(&tmp, 0, sizeof(tmp));
430 tmp.block.nVersion = pblock->nVersion;
431 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
432 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
433 tmp.block.nTime = pblock->nTime;
434 tmp.block.nBits = pblock->nBits;
435 tmp.block.nNonce = pblock->nNonce;
437 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
438 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
440 // Byte swap all the input buffer
441 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
442 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
444 // Precalc the first half of the first hash, which stays constant
445 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
447 memcpy(pdata, &tmp.block, 128);
448 memcpy(phash1, &tmp.hash1, 64);
452 bool CheckWork(const std::shared_ptr<CBlock>& pblock, CWallet& wallet, CReserveKey& reservekey)
454 uint256 hashBlock = pblock->GetHash();
455 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
457 if(!pblock->IsProofOfWork())
458 return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
460 if (hashBlock > hashTarget)
461 return error("CheckWork() : proof-of-work not meeting target");
464 printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
466 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
471 if (pblock->hashPrevBlock != hashBestChain)
472 return error("CheckWork() : generated block is stale");
474 // Remove key from key pool
475 reservekey.KeepKey();
477 // Track how many getdata requests this block gets
479 LOCK(wallet.cs_wallet);
480 wallet.mapRequestCount[hashBlock] = 0;
483 // Process this block the same as if we had received it from another node
484 if (!ProcessBlock(nullptr, pblock.get()))
485 return error("CheckWork() : ProcessBlock, block not accepted");
491 bool CheckStake(const std::shared_ptr<CBlock>& pblock, CWallet& wallet)
493 uint256 proofHash = 0, hashTarget = 0;
494 uint256 hashBlock = pblock->GetHash();
496 if(!pblock->IsProofOfStake())
497 return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
499 // verify hash target and signature of coinstake tx
500 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
501 return error("CheckStake() : proof-of-stake checking failed");
504 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());
506 printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
511 if (pblock->hashPrevBlock != hashBestChain)
512 return error("CheckStake() : generated block is stale");
514 // Track how many getdata requests this block gets
516 LOCK(wallet.cs_wallet);
517 wallet.mapRequestCount[hashBlock] = 0;
520 // Process this block the same as if we had received it from another node
521 if (!ProcessBlock(nullptr, pblock.get()))
522 return error("CheckStake() : ProcessBlock, block not accepted");
528 // Precalculated SHA256 contexts and metadata
529 // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
530 typedef std::map<std::pair<uint256, unsigned int>, std::pair<std::vector<unsigned char>, std::pair<uint32_t, uint64_t> > > MidstateMap;
532 // Fill the inputs map with precalculated contexts and metadata
533 bool FillMap(CWallet *pwallet, uint32_t nUpperTime, MidstateMap &inputsMap)
535 // Choose coins to use
536 int64_t nBalance = pwallet->GetBalance();
538 if (nBalance <= nReserveBalance)
541 uint32_t nTime = GetAdjustedTime();
545 LOCK2(cs_main, pwallet->cs_wallet);
548 int64_t nValueIn = 0;
549 if (!pwallet->SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nUpperTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
550 return error("FillMap() : SelectCoinsSimple failed");
552 if (setCoins.empty())
558 for(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
560 std::pair<uint256, uint32_t> key = {pcoin->first->GetHash(), pcoin->second};
562 // Skip existent inputs
563 if (inputsMap.find(key) != inputsMap.end())
566 // Trying to parse scriptPubKey
567 txnouttype whichType;
568 std::vector<valtype> vSolutions;
569 if (!Solver(pcoin->first->vout[pcoin->second].scriptPubKey, whichType, vSolutions))
572 // Only support pay to public key and pay to address
573 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
576 // Load transaction index item
577 if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
581 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
584 // Only load coins meeting min age requirement
585 if (nStakeMinAge + block.nTime > nTime - nMaxStakeSearchInterval)
588 // Get stake modifier
589 uint64_t nStakeModifier = 0;
590 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
593 // Build static part of kernel
594 CDataStream ssKernel(SER_GETHASH, 0);
595 ssKernel << nStakeModifier;
596 ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin->first->nTime << pcoin->second;
598 // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
599 inputsMap[key] = {std::vector<unsigned char>(ssKernel.begin(), ssKernel.end()), {pcoin->first->nTime, pcoin->first->vout[pcoin->second].nValue}};
602 nStakeInputsMapSize = inputsMap.size();
605 printf("FillMap() : Map of %" PRIu64 " precalculated contexts has been created by stake miner\n", nStakeInputsMapSize);
611 // Scan inputs map in order to find a solution
612 bool ScanMap(const MidstateMap &inputsMap, uint32_t nBits, MidstateMap::key_type &LuckyInput, std::pair<uint256, uint32_t> &solution)
614 static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
615 uint32_t nSearchTime = GetAdjustedTime();
617 if (inputsMap.size() > 0 && nSearchTime > nLastCoinStakeSearchTime)
619 // Scanning interval (begintime, endtime)
620 std::pair<uint32_t, uint32_t> interval;
622 interval.first = nSearchTime;
623 interval.second = nSearchTime - std::min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
625 // (txid, nout) => (kernel, (tx.nTime, nAmount))
626 for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
628 unsigned char *kernel = (unsigned char *) &input->second.first[0];
630 // scan(State, Bits, Time, Amount, ...)
631 if (ScanKernelBackward(kernel, nBits, input->second.second.first, input->second.second.second, interval, solution))
634 LuckyInput = input->first; // (txid, nout)
640 // Inputs map iteration can be big enough to consume few seconds while scanning.
641 // We're using dynamical calculation of scanning interval in order to compensate this delay.
642 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
643 nLastCoinStakeSearchTime = nSearchTime;
646 // No solutions were found
650 // Stake miner thread
651 void ThreadStakeMiner(void* parg)
653 SetThreadPriority(THREAD_PRIORITY_LOWEST);
655 // Make this thread recognisable as the mining thread
656 RenameThread("novacoin-miner");
657 CWallet* pwallet = (CWallet*)parg;
659 MidstateMap inputsMap;
660 if (!FillMap(pwallet, GetAdjustedTime(), inputsMap))
663 bool fTrySync = true;
665 CBlockIndex* pindexPrev = pindexBest;
666 uint32_t nBits = GetNextTargetRequired(pindexPrev, true);
668 printf("ThreadStakeMinter started\n");
672 vnThreadsRunning[THREAD_MINTER]++;
674 MidstateMap::key_type LuckyInput;
675 std::pair<uint256, uint32_t> solution;
683 while (pwallet->IsLocked())
687 goto _endloop; // Don't be afraid to use a goto if that's the best option.
690 while (vNodes.empty() || IsInitialBlockDownload())
701 // Don't try mine blocks unless we're at the top of chain and have at least three p2p connections.
703 if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
710 if (ScanMap(inputsMap, nBits, LuckyInput, solution))
712 SetThreadPriority(THREAD_PRIORITY_NORMAL);
714 // Remove lucky input from the map
715 inputsMap.erase(inputsMap.find(LuckyInput));
718 CTransaction txCoinStake;
720 // Create new coinstake transaction
721 if (!pwallet->CreateCoinStake(LuckyInput.first, LuckyInput.second, solution.second, nBits, txCoinStake, key))
723 std::string strMessage = _("Warning: Unable to create coinstake transaction, see debug.log for the details. Mining thread has been stopped.");
724 strMiscWarning = strMessage;
725 printf("*** %s\n", strMessage.c_str());
730 // Now we have new coinstake, it's time to create the block ...
731 std::shared_ptr<CBlock> pblock = CreateNewBlock(pwallet, &txCoinStake);
734 std::string strMessage = _("Warning: Unable to allocate memory for the new block object. Mining thread has been stopped.");
735 strMiscWarning = strMessage;
736 printf("*** %s\n", strMessage.c_str());
741 unsigned int nExtraNonce = 0;
742 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
745 if (!key.Sign(pblock->GetHash(), pblock->vchBlockSig))
747 std::string strMessage = _("Warning: Proof-of-Stake miner is unable to sign the block (locked wallet?). Mining thread has been stopped.");
748 strMiscWarning = strMessage;
749 printf("*** %s\n", strMessage.c_str());
754 CheckStake(pblock, *pwallet);
755 SetThreadPriority(THREAD_PRIORITY_LOWEST);
759 if (pindexPrev != pindexBest)
761 // The best block has been changed, we need to refill the map
762 if (FillMap(pwallet, GetAdjustedTime(), inputsMap))
764 pindexPrev = pindexBest;
765 nBits = GetNextTargetRequired(pindexPrev, true);
769 // Clear existent data if FillMap failed
777 (void)0; // do nothing
781 vnThreadsRunning[THREAD_MINTER]--;
783 catch (std::exception& e) {
784 vnThreadsRunning[THREAD_MINTER]--;
785 PrintException(&e, "ThreadStakeMinter()");
787 vnThreadsRunning[THREAD_MINTER]--;
788 PrintException(nullptr, "ThreadStakeMinter()");
790 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);