Remove print() methods: all unused
[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     unsigned char* pdata = (unsigned char*)pbuffer;
26     unsigned int blocks = 1 + ((len + 8) / 64);
27     unsigned char* pend = pdata + 64 * blocks;
28     memset(pdata + len, 0, 64 * blocks - len);
29     pdata[len] = 0x80;
30     unsigned int bits = len * 8;
31     pend[-1] = (bits >> 0) & 0xff;
32     pend[-2] = (bits >> 8) & 0xff;
33     pend[-3] = (bits >> 16) & 0xff;
34     pend[-4] = (bits >> 24) & 0xff;
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 boost::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 (a.get<1>() == b.get<1>())
92                 return a.get<0>() < b.get<0>();
93             return a.get<1>() < b.get<1>();
94         }
95         else
96         {
97             if (a.get<0>() == b.get<0>())
98                 return a.get<1>() < b.get<1>();
99             return a.get<0>() < b.get<0>();
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     auto_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     unsigned int nBlockMaxSize = GetArgUInt("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
143     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
144     nBlockMaxSize = std::max(1000u, std::min(MAX_BLOCK_SIZE-1000u, nBlockMaxSize));
145
146     // How much of the block should be dedicated to high-priority transactions,
147     // included regardless of the fees they pay
148     unsigned int nBlockPrioritySize = GetArgUInt("-blockprioritysize", 27000);
149     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
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     unsigned int nBlockMinSize = GetArgUInt("-blockminsize", 0);
154     nBlockMinSize = std::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     int64_t nMinTxFee = MIN_TX_FEE;
162     if (mapArgs.count("-mintxfee"))
163         ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
164
165     CBlockIndex* pindexPrev = pindexBest;
166
167     pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
168
169     // Collect memory pool transactions into the block
170     int64_t nFees = 0;
171     {
172         LOCK2(cs_main, mempool.cs);
173         CBlockIndex* pindexPrev = pindexBest;
174         CTxDB txdb("r");
175
176         // Priority order to process transactions
177         list<COrphan> vOrphan; // list memory doesn't move
178         map<uint256, vector<COrphan*> > mapDependers;
179
180         // This vector will be sorted into a priority queue:
181         vector<TxPriority> vecPriority;
182         vecPriority.reserve(mempool.mapTx.size());
183         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
184         {
185             CTransaction& tx = (*mi).second;
186             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
187                 continue;
188
189             COrphan* porphan = NULL;
190             double dPriority = 0;
191             int64_t nTotalIn = 0;
192             bool fMissingInputs = false;
193             BOOST_FOREACH(const CTxIn& txin, tx.vin)
194             {
195                 // Read prev transaction
196                 CTransaction txPrev;
197                 CTxIndex txindex;
198                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
199                 {
200                     // This should never happen; all transactions in the memory
201                     // pool should connect to either transactions in the chain
202                     // or other transactions in the memory pool.
203                     if (!mempool.mapTx.count(txin.prevout.hash))
204                     {
205                         printf("ERROR: mempool transaction missing input\n");
206                         if (fDebug) assert("mempool transaction missing input" == 0);
207                         fMissingInputs = true;
208                         if (porphan)
209                             vOrphan.pop_back();
210                         break;
211                     }
212
213                     // Has to wait for dependencies
214                     if (!porphan)
215                     {
216                         // Use list for automatic deletion
217                         vOrphan.push_back(COrphan(&tx));
218                         porphan = &vOrphan.back();
219                     }
220                     mapDependers[txin.prevout.hash].push_back(porphan);
221                     porphan->setDependsOn.insert(txin.prevout.hash);
222                     nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
223                     continue;
224                 }
225                 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
226                 nTotalIn += nValueIn;
227
228                 int nConf = txindex.GetDepthInMainChain();
229                 dPriority += (double)nValueIn * nConf;
230             }
231             if (fMissingInputs) continue;
232
233             // Priority is sum(valuein * age) / txsize
234             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
235             dPriority /= nTxSize;
236
237             // This is a more accurate fee-per-kilobyte than is used by the client code, because the
238             // client code rounds up the size to the nearest 1K. That's good, because it gives an
239             // incentive to create smaller transactions.
240             double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
241
242             if (porphan)
243             {
244                 porphan->dPriority = dPriority;
245                 porphan->dFeePerKb = dFeePerKb;
246             }
247             else
248                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
249         }
250
251         // Collect transactions into block
252         map<uint256, CTxIndex> mapTestPool;
253         uint64_t nBlockSize = 1000;
254         uint64_t nBlockTx = 0;
255         int nBlockSigOps = 100;
256         bool fSortedByFee = (nBlockPrioritySize <= 0);
257
258         TxPriorityCompare comparer(fSortedByFee);
259         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
260
261         while (!vecPriority.empty())
262         {
263             // Take highest priority transaction off the priority queue:
264             double dPriority = vecPriority.front().get<0>();
265             double dFeePerKb = vecPriority.front().get<1>();
266             CTransaction& tx = *(vecPriority.front().get<2>());
267
268             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
269             vecPriority.pop_back();
270
271             // Size limits
272             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
273             if (nBlockSize + nTxSize >= nBlockMaxSize)
274                 continue;
275
276             // Legacy limits on sigOps:
277             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
278             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
279                 continue;
280
281             // Timestamp limit
282             if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > txCoinStake->nTime))
283                 continue;
284
285             // Skip free transactions if we're past the minimum block size:
286             if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
287                 continue;
288
289             // Prioritize by fee once past the priority size or we run out of high-priority
290             // transactions:
291             if (!fSortedByFee &&
292                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
293             {
294                 fSortedByFee = true;
295                 comparer = TxPriorityCompare(fSortedByFee);
296                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
297             }
298
299             // Connecting shouldn't fail due to dependency on other memory pool transactions
300             // because we're already processing them in order of dependency
301             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
302             MapPrevTx mapInputs;
303             bool fInvalid;
304             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
305                 continue;
306
307             // Transaction fee
308             int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
309             int64_t nMinFee = tx.GetMinFee(nBlockSize, true, GMF_BLOCK, nTxSize);
310             if (nTxFees < nMinFee)
311                 continue;
312
313             // Sigops accumulation
314             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
315             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
316                 continue;
317
318             if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, true, MANDATORY_SCRIPT_VERIFY_FLAGS))
319                 continue;
320             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
321             swap(mapTestPool, mapTestPoolTmp);
322
323             // Added
324             pblock->vtx.push_back(tx);
325             nBlockSize += nTxSize;
326             ++nBlockTx;
327             nBlockSigOps += nTxSigOps;
328             nFees += nTxFees;
329
330             if (fDebug && GetBoolArg("-printpriority"))
331             {
332                 printf("priority %.1f feeperkb %.1f txid %s\n",
333                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
334             }
335
336             // Add transactions that depend on this one to the priority queue
337             uint256 hash = tx.GetHash();
338             if (mapDependers.count(hash))
339             {
340                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
341                 {
342                     if (!porphan->setDependsOn.empty())
343                     {
344                         porphan->setDependsOn.erase(hash);
345                         if (porphan->setDependsOn.empty())
346                         {
347                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
348                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
349                         }
350                     }
351                 }
352             }
353         }
354
355         nLastBlockTx = nBlockTx;
356         nLastBlockSize = nBlockSize;
357
358         if (!fProofOfStake)
359         {
360             pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits, nFees);
361
362             if (fDebug)
363                 printf("CreateNewBlock(): PoW reward %" PRIu64 "\n", pblock->vtx[0].vout[0].nValue);
364         }
365
366         if (fDebug && GetBoolArg("-printpriority"))
367             printf("CreateNewBlock(): total size %" PRIu64 "\n", nBlockSize);
368
369         // Fill in header
370         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
371         if (!fProofOfStake)
372         {
373             pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
374             pblock->nTime          = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
375             pblock->UpdateTime(pindexPrev);
376         }
377         pblock->nNonce         = 0;
378     }
379
380     return pblock.release();
381 }
382
383
384 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
385 {
386     // Update nExtraNonce
387     static uint256 hashPrevBlock;
388     if (hashPrevBlock != pblock->hashPrevBlock)
389     {
390         nExtraNonce = 0;
391         hashPrevBlock = pblock->hashPrevBlock;
392     }
393     ++nExtraNonce;
394
395     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
396     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
397     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
398
399     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
400 }
401
402
403 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
404 {
405     //
406     // Pre-build hash buffers
407     //
408     struct
409     {
410         struct unnamed2
411         {
412             int nVersion;
413             uint256 hashPrevBlock;
414             uint256 hashMerkleRoot;
415             unsigned int nTime;
416             unsigned int nBits;
417             unsigned int nNonce;
418         }
419         block;
420         unsigned char pchPadding0[64];
421         uint256 hash1;
422         unsigned char pchPadding1[64];
423     }
424     tmp;
425     memset(&tmp, 0, sizeof(tmp));
426
427     tmp.block.nVersion       = pblock->nVersion;
428     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
429     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
430     tmp.block.nTime          = pblock->nTime;
431     tmp.block.nBits          = pblock->nBits;
432     tmp.block.nNonce         = pblock->nNonce;
433
434     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
435     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
436
437     // Byte swap all the input buffer
438     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
439         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
440
441     // Precalc the first half of the first hash, which stays constant
442     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
443
444     memcpy(pdata, &tmp.block, 128);
445     memcpy(phash1, &tmp.hash1, 64);
446 }
447
448
449 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
450 {
451     uint256 hashBlock = pblock->GetHash();
452     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
453
454     if(!pblock->IsProofOfWork())
455         return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
456
457     if (hashBlock > hashTarget)
458         return error("CheckWork() : proof-of-work not meeting target");
459
460     //// debug print
461     printf("CheckWork() : new proof-of-work block found  \n  hash: %s  \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
462     pblock->print();
463     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
464
465     // Found a solution
466     {
467         LOCK(cs_main);
468         if (pblock->hashPrevBlock != hashBestChain)
469             return error("CheckWork() : generated block is stale");
470
471         // Remove key from key pool
472         reservekey.KeepKey();
473
474         // Track how many getdata requests this block gets
475         {
476             LOCK(wallet.cs_wallet);
477             wallet.mapRequestCount[hashBlock] = 0;
478         }
479
480         // Process this block the same as if we had received it from another node
481         if (!ProcessBlock(NULL, pblock))
482             return error("CheckWork() : ProcessBlock, block not accepted");
483     }
484
485     return true;
486 }
487
488 bool CheckStake(CBlock* pblock, CWallet& wallet)
489 {
490     uint256 proofHash = 0, hashTarget = 0;
491     uint256 hashBlock = pblock->GetHash();
492
493     if(!pblock->IsProofOfStake())
494         return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
495
496     // verify hash target and signature of coinstake tx
497     if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
498         return error("CheckStake() : proof-of-stake checking failed");
499
500     //// debug print
501     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());
502     pblock->print();
503     printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
504
505     // Found a solution
506     {
507         LOCK(cs_main);
508         if (pblock->hashPrevBlock != hashBestChain)
509             return error("CheckStake() : generated block is stale");
510
511         // Track how many getdata requests this block gets
512         {
513             LOCK(wallet.cs_wallet);
514             wallet.mapRequestCount[hashBlock] = 0;
515         }
516
517         // Process this block the same as if we had received it from another node
518         if (!ProcessBlock(NULL, pblock))
519             return error("CheckStake() : ProcessBlock, block not accepted");
520     }
521
522     return true;
523 }
524
525 // Precalculated SHA256 contexts and metadata
526 // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
527 typedef std::map<std::pair<uint256, unsigned int>, std::pair<std::vector<unsigned char>, std::pair<uint32_t, uint64_t> > > MidstateMap;
528
529 // Fill the inputs map with precalculated contexts and metadata
530 bool FillMap(CWallet *pwallet, uint32_t nUpperTime, MidstateMap &inputsMap)
531 {
532     // Choose coins to use
533     int64_t nBalance = pwallet->GetBalance();
534
535     if (nBalance <= nReserveBalance)
536         return false;
537
538     uint32_t nTime = GetAdjustedTime();
539
540     CTxDB txdb("r");
541     {
542         LOCK2(cs_main, pwallet->cs_wallet);
543
544         CoinsSet setCoins;
545         int64_t nValueIn = 0;
546         if (!pwallet->SelectCoinsSimple(nBalance - nReserveBalance, MIN_TX_FEE, MAX_MONEY, nUpperTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
547             return error("FillMap() : SelectCoinsSimple failed");
548
549         if (setCoins.empty())
550             return false;
551
552         CBlock block;
553         CTxIndex txindex;
554
555         for(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
556         {
557             pair<uint256, uint32_t> key = make_pair(pcoin->first->GetHash(), pcoin->second);
558
559             // Skip existent inputs
560             if (inputsMap.find(key) != inputsMap.end())
561                 continue;
562
563             // Trying to parse scriptPubKey
564             txnouttype whichType;
565             vector<valtype> vSolutions;
566             if (!Solver(pcoin->first->vout[pcoin->second].scriptPubKey, whichType, vSolutions))
567                 continue;
568
569             // Only support pay to public key and pay to address
570             if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
571                 continue;
572
573             // Load transaction index item
574             if (!txdb.ReadTxIndex(pcoin->first->GetHash(), txindex))
575                 continue;
576
577             // Read block header
578             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
579                 continue;
580
581             // Only load coins meeting min age requirement
582             if (nStakeMinAge + block.nTime > nTime - nMaxStakeSearchInterval)
583                 continue;
584
585             // Get stake modifier
586             uint64_t nStakeModifier = 0;
587             if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
588                 continue;
589
590             // Build static part of kernel
591             CDataStream ssKernel(SER_GETHASH, 0);
592             ssKernel << nStakeModifier;
593             ssKernel << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << pcoin->first->nTime << pcoin->second;
594
595             // (txid, vout.n) => (kernel, (tx.nTime, nAmount))
596             inputsMap[key] = make_pair(std::vector<unsigned char>(ssKernel.begin(), ssKernel.end()), make_pair(pcoin->first->nTime, pcoin->first->vout[pcoin->second].nValue));
597         }
598
599         nStakeInputsMapSize = inputsMap.size();
600
601         if (fDebug)
602             printf("FillMap() : Map of %" PRIu64 " precalculated contexts has been created by stake miner\n", nStakeInputsMapSize);
603     }
604
605     return true;
606 }
607
608 // Scan inputs map in order to find a solution
609 bool ScanMap(const MidstateMap &inputsMap, uint32_t nBits, MidstateMap::key_type &LuckyInput, std::pair<uint256, uint32_t> &solution)
610 {
611     static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
612     uint32_t nSearchTime = GetAdjustedTime();
613
614     if (inputsMap.size() > 0 && nSearchTime > nLastCoinStakeSearchTime)
615     {
616         // Scanning interval (begintime, endtime)
617         std::pair<uint32_t, uint32_t> interval;
618
619         interval.first = nSearchTime;
620         interval.second = nSearchTime - min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
621
622         // (txid, nout) => (kernel, (tx.nTime, nAmount))
623         for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
624         {
625             unsigned char *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     CWallet* pwallet = (CWallet*)parg;
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     printf("ThreadStakeMinter started\n");
666
667     try
668     {
669         vnThreadsRunning[THREAD_MINTER]++;
670
671         MidstateMap::key_type LuckyInput;
672         std::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                 CBlock* pblock;
729                 pblock = CreateNewBlock(pwallet, &txCoinStake);
730                 if (!pblock)
731                 {
732                     string strMessage = _("Warning: Unable to allocate memory for the new block object. Mining thread has been stopped.");
733                     strMiscWarning = strMessage;
734                     printf("*** %s\n", strMessage.c_str());
735
736                     break;
737                 }
738
739                 unsigned int nExtraNonce = 0;
740                 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
741
742                 // ... and sign it
743                 if (!key.Sign(pblock->GetHash(), pblock->vchBlockSig))
744                 {
745                     string strMessage = _("Warning: Proof-of-Stake miner is unable to sign the block (locked wallet?). Mining thread has been stopped.");
746                     strMiscWarning = strMessage;
747                     printf("*** %s\n", strMessage.c_str());
748
749                     break;
750                 }
751
752                 CheckStake(pblock, *pwallet);
753                 SetThreadPriority(THREAD_PRIORITY_LOWEST);
754                 Sleep(500);
755             }
756
757             if (pindexPrev != pindexBest)
758             {
759                 // The best block has been changed, we need to refill the map
760                 if (FillMap(pwallet, GetAdjustedTime(), inputsMap))
761                 {
762                     pindexPrev = pindexBest;
763                     nBits = GetNextTargetRequired(pindexPrev, true);
764                 }
765                 else
766                 {
767                     // Clear existent data if FillMap failed
768                     inputsMap.clear();
769                 }
770             }
771
772             Sleep(500);
773
774             _endloop:
775                 (void)0; // do nothing
776         }
777         while(!fShutdown);
778
779         vnThreadsRunning[THREAD_MINTER]--;
780     }
781     catch (std::exception& e) {
782         vnThreadsRunning[THREAD_MINTER]--;
783         PrintException(&e, "ThreadStakeMinter()");
784     } catch (...) {
785         vnThreadsRunning[THREAD_MINTER]--;
786         PrintException(NULL, "ThreadStakeMinter()");
787     }
788     printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
789 }