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