Update CMakeLists.txt - play with openssl
[novacoin.git] / src / miner.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2013 The NovaCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
7 #include "txdb-leveldb.h"
8 #include "miner.h"
9 #include "kernel.h"
10 #include "kernel_worker.h"
11 #include "wallet.h"
12
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     std::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 std::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 (std::get<1>(a) == std::get<1>(b))
92                 return std::get<0>(a) < std::get<0>(b);
93             return std::get<1>(a) < std::get<1>(b);
94         }
95         else
96         {
97             if (std::get<0>(a) == std::get<0>(b))
98                 return std::get<1>(a) < std::get<1>(b);
99             return std::get<0>(a) < std::get<0>(b);
100         }
101     }
102 };
103
104 // CreateNewBlock: create new block (without proof-of-work/with provided coinstake)
105 std::shared_ptr<CBlock> CreateNewBlock(CWallet* pwallet, CTransaction *txCoinStake)
106 {
107     bool fProofOfStake = txCoinStake != nullptr;
108
109     // Create new block
110     std::shared_ptr<CBlock> pblock(new CBlock());
111     if (!pblock.get())
112         return nullptr;
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         bool fResult = ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
164         if (!fResult) // Parse error
165             nMinTxFee = MIN_TX_FEE;
166     }
167
168     CBlockIndex* 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         std::list<COrphan> vOrphan; // list memory doesn't move
181         std::map<uint256, std::vector<COrphan*> > mapDependers;
182
183         // This vector will be sorted into a priority queue:
184         std::vector<TxPriority> vecPriority;
185         vecPriority.reserve(mempool.mapTx.size());
186         for (std::map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
187         {
188             CTransaction& tx = (*mi).second;
189             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
190                 continue;
191
192             COrphan* porphan = nullptr;
193             double dPriority = 0;
194             int64_t nTotalIn = 0;
195             bool fMissingInputs = false;
196             for (const CTxIn& 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                 int64_t 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             unsigned int 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             double 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         std::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         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
263
264         while (!vecPriority.empty())
265         {
266             // Take highest priority transaction off the priority queue:
267             double dPriority = std::get<0>(vecPriority.front());
268             double dFeePerKb = std::get<1>(vecPriority.front());
269             CTransaction& tx = *(std::get<2>(vecPriority.front()));
270
271             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
272             vecPriority.pop_back();
273
274             // Size limits
275             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
276             if (nBlockSize + nTxSize >= nBlockMaxSize)
277                 continue;
278
279             // Legacy limits on sigOps:
280             unsigned int 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                 std::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             std::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             int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
312             int64_t 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             uint256 hash = tx.GetHash();
341             if (mapDependers.count(hash))
342             {
343                 for (COrphan* 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                             std::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          = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
377             pblock->nTime          = std::max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
378             pblock->UpdateTime(pindexPrev);
379         }
380         pblock->nNonce         = 0;
381     }
382
383     return pblock;
384 }
385
386
387 void IncrementExtraNonce(std::shared_ptr<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(const std::shared_ptr<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(const std::shared_ptr<CBlock>& pblock, CWallet& wallet, CReserveKey& reservekey)
453 {
454     uint256 hashBlock = pblock->GetHash();
455     uint256 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(nullptr, pblock.get()))
485             return error("CheckWork() : ProcessBlock, block not accepted");
486     }
487
488     return true;
489 }
490
491 bool CheckStake(const std::shared_ptr<CBlock>& pblock, CWallet& wallet)
492 {
493     uint256 proofHash = 0, hashTarget = 0;
494     uint256 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(nullptr, pblock.get()))
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 std::map<std::pair<uint256, unsigned int>, std::pair<std::vector<unsigned char>, std::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     int64_t 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(CoinsSet::const_iterator pcoin = setCoins.begin(); pcoin != setCoins.end(); pcoin++)
559         {
560             std::pair<uint256, uint32_t> key = {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             std::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] = {std::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, std::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         std::pair<uint32_t, uint32_t> interval;
621
622         interval.first = nSearchTime;
623         interval.second = nSearchTime - std::min(nSearchTime-nLastCoinStakeSearchTime, nMaxStakeSearchInterval);
624
625         // (txid, nout) => (kernel, (tx.nTime, nAmount))
626         for(MidstateMap::const_iterator input = inputsMap.begin(); input != inputsMap.end(); input++)
627         {
628             unsigned char *kernel = (unsigned char *) &input->second.first[0];
629
630             // scan(State, Bits, Time, Amount, ...)
631             if (ScanKernelBackward(kernel, nBits, input->second.second.first, input->second.second.second, interval, solution))
632             {
633                 // Solution found
634                 LuckyInput = input->first; // (txid, nout)
635
636                 return true;
637             }
638         }
639
640         // Inputs map iteration can be big enough to consume few seconds while scanning.
641         // We're using dynamical calculation of scanning interval in order to compensate this delay.
642         nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
643         nLastCoinStakeSearchTime = nSearchTime;
644     }
645
646     // No solutions were found
647     return false;
648 }
649
650 // Stake miner thread
651 void ThreadStakeMiner(void* parg)
652 {
653     SetThreadPriority(THREAD_PRIORITY_LOWEST);
654
655     // Make this thread recognisable as the mining thread
656     RenameThread("novacoin-miner");
657     CWallet* pwallet = (CWallet*)parg;
658
659     MidstateMap inputsMap;
660     if (!FillMap(pwallet, GetAdjustedTime(), inputsMap))
661         return;
662
663     bool fTrySync = true;
664
665     CBlockIndex* pindexPrev = pindexBest;
666     uint32_t nBits = GetNextTargetRequired(pindexPrev, true);
667
668     printf("ThreadStakeMinter started\n");
669
670     try
671     {
672         vnThreadsRunning[THREAD_MINTER]++;
673
674         MidstateMap::key_type LuckyInput;
675         std::pair<uint256, uint32_t> solution;
676
677         // Main miner loop
678         do
679         {
680             if (fShutdown)
681                 goto _endloop;
682
683             while (pwallet->IsLocked())
684             {
685                 Sleep(1000);
686                 if (fShutdown)
687                     goto _endloop; // Don't be afraid to use a goto if that's the best option.
688             }
689
690             while (vNodes.empty() || IsInitialBlockDownload())
691             {
692                 fTrySync = true;
693
694                 Sleep(1000);
695                 if (fShutdown)
696                     goto _endloop;
697             }
698
699             if (fTrySync)
700             {
701                 // Don't try mine blocks unless we're at the top of chain and have at least three p2p connections.
702                 fTrySync = false;
703                 if (vNodes.size() < 3 || nBestHeight < GetNumBlocksOfPeers())
704                 {
705                     Sleep(1000);
706                     continue;
707                 }
708             }
709
710             if (ScanMap(inputsMap, nBits, LuckyInput, solution))
711             {
712                 SetThreadPriority(THREAD_PRIORITY_NORMAL);
713
714                 // Remove lucky input from the map
715                 inputsMap.erase(inputsMap.find(LuckyInput));
716
717                 CKey key;
718                 CTransaction txCoinStake;
719
720                 // Create new coinstake transaction
721                 if (!pwallet->CreateCoinStake(LuckyInput.first, LuckyInput.second, solution.second, nBits, txCoinStake, key))
722                 {
723                     std::string strMessage = _("Warning: Unable to create coinstake transaction, see debug.log for the details. Mining thread has been stopped.");
724                     strMiscWarning = strMessage;
725                     printf("*** %s\n", strMessage.c_str());
726
727                     break;
728                 }
729
730                 // Now we have new coinstake, it's time to create the block ...
731                 std::shared_ptr<CBlock> pblock = CreateNewBlock(pwallet, &txCoinStake);
732                 if (!pblock)
733                 {
734                     std::string strMessage = _("Warning: Unable to allocate memory for the new block object. Mining thread has been stopped.");
735                     strMiscWarning = strMessage;
736                     printf("*** %s\n", strMessage.c_str());
737
738                     break;
739                 }
740
741                 unsigned int nExtraNonce = 0;
742                 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
743
744                 // ... and sign it
745                 if (!key.Sign(pblock->GetHash(), pblock->vchBlockSig))
746                 {
747                     std::string strMessage = _("Warning: Proof-of-Stake miner is unable to sign the block (locked wallet?). Mining thread has been stopped.");
748                     strMiscWarning = strMessage;
749                     printf("*** %s\n", strMessage.c_str());
750
751                     break;
752                 }
753
754                 CheckStake(pblock, *pwallet);
755                 SetThreadPriority(THREAD_PRIORITY_LOWEST);
756                 Sleep(500);
757             }
758
759             if (pindexPrev != pindexBest)
760             {
761                 // The best block has been changed, we need to refill the map
762                 if (FillMap(pwallet, GetAdjustedTime(), inputsMap))
763                 {
764                     pindexPrev = pindexBest;
765                     nBits = GetNextTargetRequired(pindexPrev, true);
766                 }
767                 else
768                 {
769                     // Clear existent data if FillMap failed
770                     inputsMap.clear();
771                 }
772             }
773
774             Sleep(500);
775
776             _endloop:
777                 (void)0; // do nothing
778         }
779         while(!fShutdown);
780
781         vnThreadsRunning[THREAD_MINTER]--;
782     }
783     catch (std::exception& e) {
784         vnThreadsRunning[THREAD_MINTER]--;
785         PrintException(&e, "ThreadStakeMinter()");
786     } catch (...) {
787         vnThreadsRunning[THREAD_MINTER]--;
788         PrintException(nullptr, "ThreadStakeMinter()");
789     }
790     printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
791 }