Move out fees from base pow reward
[novacoin.git] / src / miner.cpp
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.
6
7 #include "txdb-leveldb.h"
8 #include "miner.h"
9 #include "kernel.h"
10 #include "kernel_worker.h"
11
12
13 //////////////////////////////////////////////////////////////////////////////
14 //
15 // BitcoinMiner
16 //
17
18 int64_t nReserveBalance = 0;
19 static unsigned int nMaxStakeSearchInterval = 60;
20 uint64_t nStakeInputsMapSize = 0;
21
22 int static FormatHashBlocks(void* pbuffer, unsigned int len)
23 {
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);
28     pdata[len] = 0x80;
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;
34     return blocks;
35 }
36
37 static const unsigned int pSHA256InitState[8] =
38 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
39
40 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
41 {
42     SHA256_CTX ctx;
43     unsigned char data[64];
44
45     SHA256_Init(&ctx);
46
47     for (int i = 0; i < 16; i++)
48         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
49
50     for (int i = 0; i < 8; i++)
51         ctx.h[i] = ((uint32_t*)pinit)[i];
52
53     SHA256_Update(&ctx, data, sizeof(data));
54     for (int i = 0; i < 8; i++)
55         ((uint32_t*)pstate)[i] = ctx.h[i];
56 }
57
58 // Some explaining would be appreciated
59 class COrphan
60 {
61 public:
62     CTransaction* ptx;
63     std::set<uint256> setDependsOn;
64     double dPriority;
65     double dFeePerKb;
66
67     COrphan(CTransaction* ptxIn)
68     {
69         ptx = ptxIn;
70         dPriority = dFeePerKb = 0;
71     }
72 };
73
74
75 uint64_t nLastBlockTx = 0;
76 uint64_t nLastBlockSize = 0;
77 uint32_t nLastCoinStakeSearchInterval = 0;
78  
79 // We want to sort transactions by priority and fee, so:
80 typedef std::tuple<double, double, CTransaction*> TxPriority;
81 class TxPriorityCompare
82 {
83     bool byFee;
84 public:
85     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
86     bool operator()(const TxPriority& a, const TxPriority& b)
87     {
88         if (byFee)
89         {
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);
93         }
94         else
95         {
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);
99         }
100     }
101 };
102
103 // CreateNewBlock: create new block (without proof-of-work/with provided coinstake)
104 std::shared_ptr<CBlock> CreateNewBlock(CWallet* pwallet, CTransaction *txCoinStake)
105 {
106     bool fProofOfStake = txCoinStake != nullptr;
107
108     // Create new block
109     std::shared_ptr<CBlock> pblock(new CBlock());
110     if (!pblock.get())
111         return nullptr;
112
113     // Create coinbase tx
114     CTransaction txCoinBase;
115     txCoinBase.vin.resize(1);
116     txCoinBase.vin[0].prevout.SetNull();
117     txCoinBase.vout.resize(1);
118
119     if (!fProofOfStake)
120     {
121         CReserveKey reservekey(pwallet);
122         txCoinBase.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
123
124         // Add our coinbase tx as first transaction
125         pblock->vtx.push_back(txCoinBase);
126     }
127     else
128     {
129         // Coinbase output must be empty for Proof-of-Stake block
130         txCoinBase.vout[0].SetEmpty();
131
132         // Syncronize timestamps
133         pblock->nTime = txCoinBase.nTime = txCoinStake->nTime;
134
135         // Add coinbase and coinstake transactions
136         pblock->vtx.push_back(txCoinBase);
137         pblock->vtx.push_back(*txCoinStake);
138     }
139
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));
144
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);
149
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);
154
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;
165     }
166
167     CBlockIndex* pindexPrev = pindexBest;
168
169     pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
170
171     // Collect memory pool transactions into the block
172     int64_t nFees = 0;
173     {
174         LOCK2(cs_main, mempool.cs);
175         CBlockIndex* pindexPrev = pindexBest;
176         CTxDB txdb("r");
177
178         // Priority order to process transactions
179         std::list<COrphan> vOrphan; // list memory doesn't move
180         std::map<uint256, std::vector<COrphan*> > mapDependers;
181
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)
186         {
187             CTransaction& tx = (*mi).second;
188             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
189                 continue;
190
191             COrphan* porphan = nullptr;
192             double dPriority = 0;
193             int64_t nTotalIn = 0;
194             bool fMissingInputs = false;
195             for (const CTxIn& txin : tx.vin)
196             {
197                 // Read prev transaction
198                 CTransaction txPrev;
199                 CTxIndex txindex;
200                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
201                 {
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))
206                     {
207                         printf("ERROR: mempool transaction missing input\n");
208                         if (fDebug) assert("mempool transaction missing input" == 0);
209                         fMissingInputs = true;
210                         if (porphan)
211                             vOrphan.pop_back();
212                         break;
213                     }
214
215                     // Has to wait for dependencies
216                     if (!porphan)
217                     {
218                         // Use list for automatic deletion
219                         vOrphan.push_back(COrphan(&tx));
220                         porphan = &vOrphan.back();
221                     }
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;
225                     continue;
226                 }
227                 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
228                 nTotalIn += nValueIn;
229
230                 int nConf = txindex.GetDepthInMainChain();
231                 dPriority += (double)nValueIn * nConf;
232             }
233             if (fMissingInputs) continue;
234
235             // Priority is sum(valuein * age) / txsize
236             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
237             dPriority /= nTxSize;
238
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);
243
244             if (porphan)
245             {
246                 porphan->dPriority = dPriority;
247                 porphan->dFeePerKb = dFeePerKb;
248             }
249             else
250                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
251         }
252
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);
259
260         TxPriorityCompare comparer(fSortedByFee);
261         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
262
263         while (!vecPriority.empty())
264         {
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()));
269
270             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
271             vecPriority.pop_back();
272
273             // Size limits
274             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
275             if (nBlockSize + nTxSize >= nBlockMaxSize)
276                 continue;
277
278             // Legacy limits on sigOps:
279             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
280             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
281                 continue;
282
283             // Timestamp limit
284             if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > txCoinStake->nTime))
285                 continue;
286
287             // Skip free transactions if we're past the minimum block size:
288             if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
289                 continue;
290
291             // Prioritize by fee once past the priority size or we run out of high-priority
292             // transactions:
293             if (!fSortedByFee &&
294                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
295             {
296                 fSortedByFee = true;
297                 comparer = TxPriorityCompare(fSortedByFee);
298                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
299             }
300
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);
304             MapPrevTx mapInputs;
305             bool fInvalid;
306             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
307                 continue;
308
309             // Transaction fee
310             int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
311             int64_t nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
312             if (nTxFees < nMinFee)
313                 continue;
314
315             // Sigops accumulation
316             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
317             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
318                 continue;
319
320             if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, true, MANDATORY_SCRIPT_VERIFY_FLAGS))
321                 continue;
322             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
323             swap(mapTestPool, mapTestPoolTmp);
324
325             // Added
326             pblock->vtx.push_back(tx);
327             nBlockSize += nTxSize;
328             ++nBlockTx;
329             nBlockSigOps += nTxSigOps;
330             nFees += nTxFees;
331
332             if (fDebug && GetBoolArg("-printpriority"))
333             {
334                 printf("priority %.1f feeperkb %.1f txid %s\n",
335                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
336             }
337
338             // Add transactions that depend on this one to the priority queue
339             uint256 hash = tx.GetHash();
340             if (mapDependers.count(hash))
341             {
342                 for (COrphan* porphan : mapDependers[hash])
343                 {
344                     if (!porphan->setDependsOn.empty())
345                     {
346                         porphan->setDependsOn.erase(hash);
347                         if (porphan->setDependsOn.empty())
348                         {
349                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
350                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
351                         }
352                     }
353                 }
354             }
355         }
356
357         nLastBlockTx = nBlockTx;
358         nLastBlockSize = nBlockSize;
359
360         if (!fProofOfStake)
361         {
362             pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits) + nFees;
363
364             if (fDebug)
365                 printf("CreateNewBlock(): PoW reward %" PRIu64 "\n", pblock->vtx[0].vout[0].nValue);
366         }
367
368         if (fDebug && GetBoolArg("-printpriority"))
369             printf("CreateNewBlock(): total size %" PRIu64 "\n", nBlockSize);
370
371         // Fill in header
372         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
373         if (!fProofOfStake)
374         {
375             pblock->nTime          = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
376             pblock->nTime          = std::max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
377             pblock->UpdateTime(pindexPrev);
378         }
379         pblock->nNonce         = 0;
380     }
381
382     return pblock;
383 }
384
385
386 void IncrementExtraNonce(std::shared_ptr<CBlock>& pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
387 {
388     // Update nExtraNonce
389     static uint256 hashPrevBlock;
390     if (hashPrevBlock != pblock->hashPrevBlock)
391     {
392         nExtraNonce = 0;
393         hashPrevBlock = pblock->hashPrevBlock;
394     }
395     ++nExtraNonce;
396
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);
400
401     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
402 }
403
404
405 void FormatHashBuffers(const std::shared_ptr<CBlock>& pblock, char* pmidstate, char* pdata, char* phash1)
406 {
407     //
408     // Pre-build hash buffers
409     //
410     struct
411     {
412         struct unnamed2
413         {
414             int nVersion;
415             uint256 hashPrevBlock;
416             uint256 hashMerkleRoot;
417             unsigned int nTime;
418             unsigned int nBits;
419             unsigned int nNonce;
420         }
421         block;
422         unsigned char pchPadding0[64];
423         uint256 hash1;
424         unsigned char pchPadding1[64];
425     }
426     tmp;
427     memset(&tmp, 0, sizeof(tmp));
428
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;
435
436     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
437     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
438
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]);
442
443     // Precalc the first half of the first hash, which stays constant
444     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
445
446     memcpy(pdata, &tmp.block, 128);
447     memcpy(phash1, &tmp.hash1, 64);
448 }
449
450
451 bool CheckWork(const std::shared_ptr<CBlock>& pblock, CWallet& wallet, CReserveKey& reservekey)
452 {
453     uint256 hashBlock = pblock->GetHash();
454     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
455
456     if(!pblock->IsProofOfWork())
457         return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
458
459     if (hashBlock > hashTarget)
460         return error("CheckWork() : proof-of-work not meeting target");
461
462     //// debug print
463     printf("CheckWork() : new proof-of-work block found  \n  hash: %s  \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
464     pblock->print();
465     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
466
467     // Found a solution
468     {
469         LOCK(cs_main);
470         if (pblock->hashPrevBlock != hashBestChain)
471             return error("CheckWork() : generated block is stale");
472
473         // Remove key from key pool
474         reservekey.KeepKey();
475
476         // Track how many getdata requests this block gets
477         {
478             LOCK(wallet.cs_wallet);
479             wallet.mapRequestCount[hashBlock] = 0;
480         }
481
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");
485     }
486
487     return true;
488 }
489
490 bool CheckStake(const std::shared_ptr<CBlock>& pblock, CWallet& wallet)
491 {
492     uint256 proofHash = 0, hashTarget = 0;
493     uint256 hashBlock = pblock->GetHash();
494
495     if(!pblock->IsProofOfStake())
496         return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
497
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");
501
502     //// debug print
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());
504     pblock->print();
505     printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
506
507     // Found a solution
508     {
509         LOCK(cs_main);
510         if (pblock->hashPrevBlock != hashBestChain)
511             return error("CheckStake() : generated block is stale");
512
513         // Track how many getdata requests this block gets
514         {
515             LOCK(wallet.cs_wallet);
516             wallet.mapRequestCount[hashBlock] = 0;
517         }
518
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");
522     }
523
524     return true;
525 }
526
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;
530
531 // Fill the inputs map with precalculated contexts and metadata
532 bool FillMap(CWallet *pwallet, uint32_t nUpperTime, MidstateMap &inputsMap)
533 {
534     // Choose coins to use
535     int64_t nBalance = pwallet->GetBalance();
536
537     if (nBalance <= nReserveBalance)
538         return false;
539
540     uint32_t nTime = GetAdjustedTime();
541
542     CTxDB txdb("r");
543     {
544         LOCK2(cs_main, pwallet->cs_wallet);
545
546         CoinsSet setCoins;
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");
550
551         if (setCoins.empty())
552             return false;
553
554         CBlock block;
555         CTxIndex txindex;
556
557         for(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
558         {
559             std::pair<uint256, uint32_t> key = {pcoin->first->GetHash(), pcoin->second};
560
561             // Skip existent inputs
562             if (inputsMap.find(key) != inputsMap.end())
563                 continue;
564
565             // Trying to parse scriptPubKey
566             txnouttype whichType;
567             std::vector<valtype> vSolutions;
568             if (!Solver(pcoin->first->vout[pcoin->second].scriptPubKey, whichType, vSolutions))
569                 continue;
570
571             // Only support pay to public key and pay to address
572             if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
573                 continue;
574
575             // Load transaction index item
576             if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
577                 continue;
578
579             // Read block header
580             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
581                 continue;
582
583             // Only load coins meeting min age requirement
584             if (nStakeMinAge + block.nTime > nTime - nMaxStakeSearchInterval)
585                 continue;
586
587             // Get stake modifier
588             uint64_t nStakeModifier = 0;
589             if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
590                 continue;
591
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;
596
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}};
599         }
600
601         nStakeInputsMapSize = inputsMap.size();
602
603         if (fDebug)
604             printf("FillMap() : Map of %" PRIu64 " precalculated contexts has been created by stake miner\n", nStakeInputsMapSize);
605     }
606
607     return true;
608 }
609
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)
612 {
613     static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
614     uint32_t nSearchTime = GetAdjustedTime();
615
616     if (inputsMap.size() > 0 && nSearchTime > nLastCoinStakeSearchTime)
617     {
618         // Scanning interval (begintime, endtime)
619         std::pair<uint32_t, uint32_t> interval;
620
621         interval.first = nSearchTime;
622         interval.second = nSearchTime - std::min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
623
624         // (txid, nout) => (kernel, (tx.nTime, nAmount))
625         for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
626         {
627             unsigned char *kernel = (unsigned char *) &input->second.first[0];
628
629             // scan(State, Bits, Time, Amount, ...)
630             if (ScanKernelBackward(kernel, nBits, input->second.second.first, input->second.second.second, interval, solution))
631             {
632                 // Solution found
633                 LuckyInput = input->first; // (txid, nout)
634
635                 return true;
636             }
637         }
638
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;
643     }
644
645     // No solutions were found
646     return false;
647 }
648
649 // Stake miner thread
650 void ThreadStakeMiner(void* parg)
651 {
652     SetThreadPriority(THREAD_PRIORITY_LOWEST);
653
654     // Make this thread recognisable as the mining thread
655     RenameThread("novacoin-miner");
656     CWallet* pwallet = (CWallet*)parg;
657
658     MidstateMap inputsMap;
659     if (!FillMap(pwallet, GetAdjustedTime(), inputsMap))
660         return;
661
662     bool fTrySync = true;
663
664     CBlockIndex* pindexPrev = pindexBest;
665     uint32_t nBits = GetNextTargetRequired(pindexPrev, true);
666
667     printf("ThreadStakeMinter started\n");
668
669     try
670     {
671         vnThreadsRunning[THREAD_MINTER]++;
672
673         MidstateMap::key_type LuckyInput;
674         std::pair<uint256, uint32_t> solution;
675
676         // Main miner loop
677         do
678         {
679             if (fShutdown)
680                 goto _endloop;
681
682             while (pwallet->IsLocked())
683             {
684                 Sleep(1000);
685                 if (fShutdown)
686                     goto _endloop; // Don't be afraid to use a goto if that's the best option.
687             }
688
689             while (vNodes.empty() || IsInitialBlockDownload())
690             {
691                 fTrySync = true;
692
693                 Sleep(1000);
694                 if (fShutdown)
695                     goto _endloop;
696             }
697
698             if (fTrySync)
699             {
700                 // Don't try mine blocks unless we're at the top of chain and have at least three p2p connections.
701                 fTrySync = false;
702                 if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
703                 {
704                     Sleep(1000);
705                     continue;
706                 }
707             }
708
709             if (ScanMap(inputsMap, nBits, LuckyInput, solution))
710             {
711                 SetThreadPriority(THREAD_PRIORITY_NORMAL);
712
713                 // Remove lucky input from the map
714                 inputsMap.erase(inputsMap.find(LuckyInput));
715
716                 CKey key;
717                 CTransaction txCoinStake;
718
719                 // Create new coinstake transaction
720                 if (!pwallet->CreateCoinStake(LuckyInput.first, LuckyInput.second, solution.second, nBits, txCoinStake, key))
721                 {
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());
725
726                     break;
727                 }
728
729                 // Now we have new coinstake, it's time to create the block ...
730                 std::shared_ptr<CBlock> pblock = CreateNewBlock(pwallet, &txCoinStake);
731                 if (!pblock)
732                 {
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());
736
737                     break;
738                 }
739
740                 unsigned int nExtraNonce = 0;
741                 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
742
743                 // ... and sign it
744                 if (!key.Sign(pblock->GetHash(), pblock->vchBlockSig))
745                 {
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());
749
750                     break;
751                 }
752
753                 CheckStake(pblock, *pwallet);
754                 SetThreadPriority(THREAD_PRIORITY_LOWEST);
755                 Sleep(500);
756             }
757
758             if (pindexPrev != pindexBest)
759             {
760                 // The best block has been changed, we need to refill the map
761                 if (FillMap(pwallet, GetAdjustedTime(), inputsMap))
762                 {
763                     pindexPrev = pindexBest;
764                     nBits = GetNextTargetRequired(pindexPrev, true);
765                 }
766                 else
767                 {
768                     // Clear existent data if FillMap failed
769                     inputsMap.clear();
770                 }
771             }
772
773             Sleep(500);
774
775             _endloop:
776                 (void)0; // do nothing
777         }
778         while(!fShutdown);
779
780         vnThreadsRunning[THREAD_MINTER]--;
781     }
782     catch (std::exception& e) {
783         vnThreadsRunning[THREAD_MINTER]--;
784         PrintException(&e, "ThreadStakeMinter()");
785     } catch (...) {
786         vnThreadsRunning[THREAD_MINTER]--;
787         PrintException(nullptr, "ThreadStakeMinter()");
788     }
789     printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
790 }