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