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