Miner module commit.
[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 "miner.h"
8 #include "kernel.h"
9
10 using namespace std;
11
12 //////////////////////////////////////////////////////////////////////////////
13 //
14 // BitcoinMiner
15 //
16
17 string strMintMessage = "Info: Minting suspended due to locked wallet.";
18 string strMintWarning;
19
20 int static FormatHashBlocks(void* pbuffer, unsigned int len)
21 {
22     unsigned char* pdata = (unsigned char*)pbuffer;
23     unsigned int blocks = 1 + ((len + 8) / 64);
24     unsigned char* pend = pdata + 64 * blocks;
25     memset(pdata + len, 0, 64 * blocks - len);
26     pdata[len] = 0x80;
27     unsigned int bits = len * 8;
28     pend[-1] = (bits >> 0) & 0xff;
29     pend[-2] = (bits >> 8) & 0xff;
30     pend[-3] = (bits >> 16) & 0xff;
31     pend[-4] = (bits >> 24) & 0xff;
32     return blocks;
33 }
34
35 static const unsigned int pSHA256InitState[8] =
36 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
37
38 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
39 {
40     SHA256_CTX ctx;
41     unsigned char data[64];
42
43     SHA256_Init(&ctx);
44
45     for (int i = 0; i < 16; i++)
46         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
47
48     for (int i = 0; i < 8; i++)
49         ctx.h[i] = ((uint32_t*)pinit)[i];
50
51     SHA256_Update(&ctx, data, sizeof(data));
52     for (int i = 0; i < 8; i++)
53         ((uint32_t*)pstate)[i] = ctx.h[i];
54 }
55
56 // Some explaining would be appreciated
57 class COrphan
58 {
59 public:
60     CTransaction* ptx;
61     set<uint256> setDependsOn;
62     double dPriority;
63     double dFeePerKb;
64
65     COrphan(CTransaction* ptxIn)
66     {
67         ptx = ptxIn;
68         dPriority = dFeePerKb = 0;
69     }
70
71     void print() const
72     {
73         printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
74                ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
75         BOOST_FOREACH(uint256 hash, setDependsOn)
76             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
77     }
78 };
79
80
81 uint64 nLastBlockTx = 0;
82 uint64 nLastBlockSize = 0;
83 int64 nLastCoinStakeSearchInterval = 0;
84  
85 // We want to sort transactions by priority and fee, so:
86 typedef boost::tuple<double, double, CTransaction*> TxPriority;
87 class TxPriorityCompare
88 {
89     bool byFee;
90 public:
91     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
92     bool operator()(const TxPriority& a, const TxPriority& b)
93     {
94         if (byFee)
95         {
96             if (a.get<1>() == b.get<1>())
97                 return a.get<0>() < b.get<0>();
98             return a.get<1>() < b.get<1>();
99         }
100         else
101         {
102             if (a.get<0>() == b.get<0>())
103                 return a.get<1>() < b.get<1>();
104             return a.get<0>() < b.get<0>();
105         }
106     }
107 };
108
109 // CreateNewBlock:
110 //   fProofOfStake: try (best effort) to make a proof-of-stake block
111 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
112 {
113     // Create new block
114     auto_ptr<CBlock> pblock(new CBlock());
115     if (!pblock.get())
116         return NULL;
117
118     // Create coinbase tx
119     CTransaction txNew;
120     txNew.vin.resize(1);
121     txNew.vin[0].prevout.SetNull();
122     txNew.vout.resize(1);
123
124     if (!fProofOfStake)
125     {
126         CReserveKey reservekey(pwallet);
127         txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
128     }
129     else
130         txNew.vout[0].SetEmpty();
131
132     // Add our coinbase tx as first transaction
133     pblock->vtx.push_back(txNew);
134
135     // Largest block you're willing to create:
136     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
137     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
138     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
139
140     // How much of the block should be dedicated to high-priority transactions,
141     // included regardless of the fees they pay
142     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
143     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
144
145     // Minimum block size you want to create; block will be filled with free transactions
146     // until there are no more or the block reaches this size:
147     unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
148     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
149
150     // Fee-per-kilobyte amount considered the same as "free"
151     // Be careful setting this: if you set it to zero then
152     // a transaction spammer can cheaply fill blocks using
153     // 1-satoshi-fee transactions. It should be set above the real
154     // cost to you of processing a transaction.
155     int64 nMinTxFee = MIN_TX_FEE;
156     if (mapArgs.count("-mintxfee"))
157         ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
158
159     // ppcoin: if coinstake available add coinstake tx
160     static int64 nLastCoinStakeSearchTime = GetAdjustedTime();  // only initialized at startup
161     CBlockIndex* pindexPrev = pindexBest;
162
163     if (fProofOfStake)  // attempt to find a coinstake
164     {
165         pblock->nBits = GetNextTargetRequired(pindexPrev, true);
166         CTransaction txCoinStake;
167         int64 nSearchTime = txCoinStake.nTime; // search to current time
168         if (nSearchTime > nLastCoinStakeSearchTime)
169         {
170             if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
171             {
172                 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
173                 {   // make sure coinstake would meet timestamp protocol
174                     // as it would be the same as the block timestamp
175                     pblock->vtx[0].nTime = txCoinStake.nTime;
176                     pblock->vtx.push_back(txCoinStake);
177                 }
178             }
179             nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
180             nLastCoinStakeSearchTime = nSearchTime;
181         }
182     }
183
184     pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
185
186     // Collect memory pool transactions into the block
187     int64 nFees = 0;
188     {
189         LOCK2(cs_main, mempool.cs);
190         CBlockIndex* pindexPrev = pindexBest;
191         CTxDB txdb("r");
192
193         // Priority order to process transactions
194         list<COrphan> vOrphan; // list memory doesn't move
195         map<uint256, vector<COrphan*> > mapDependers;
196
197         // This vector will be sorted into a priority queue:
198         vector<TxPriority> vecPriority;
199         vecPriority.reserve(mempool.mapTx.size());
200         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
201         {
202             CTransaction& tx = (*mi).second;
203             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
204                 continue;
205
206             COrphan* porphan = NULL;
207             double dPriority = 0;
208             int64 nTotalIn = 0;
209             bool fMissingInputs = false;
210             BOOST_FOREACH(const CTxIn& txin, tx.vin)
211             {
212                 // Read prev transaction
213                 CTransaction txPrev;
214                 CTxIndex txindex;
215                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
216                 {
217                     // This should never happen; all transactions in the memory
218                     // pool should connect to either transactions in the chain
219                     // or other transactions in the memory pool.
220                     if (!mempool.mapTx.count(txin.prevout.hash))
221                     {
222                         printf("ERROR: mempool transaction missing input\n");
223                         if (fDebug) assert("mempool transaction missing input" == 0);
224                         fMissingInputs = true;
225                         if (porphan)
226                             vOrphan.pop_back();
227                         break;
228                     }
229
230                     // Has to wait for dependencies
231                     if (!porphan)
232                     {
233                         // Use list for automatic deletion
234                         vOrphan.push_back(COrphan(&tx));
235                         porphan = &vOrphan.back();
236                     }
237                     mapDependers[txin.prevout.hash].push_back(porphan);
238                     porphan->setDependsOn.insert(txin.prevout.hash);
239                     nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
240                     continue;
241                 }
242                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
243                 nTotalIn += nValueIn;
244
245                 int nConf = txindex.GetDepthInMainChain();
246                 dPriority += (double)nValueIn * nConf;
247             }
248             if (fMissingInputs) continue;
249
250             // Priority is sum(valuein * age) / txsize
251             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
252             dPriority /= nTxSize;
253
254             // This is a more accurate fee-per-kilobyte than is used by the client code, because the
255             // client code rounds up the size to the nearest 1K. That's good, because it gives an
256             // incentive to create smaller transactions.
257             double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
258
259             if (porphan)
260             {
261                 porphan->dPriority = dPriority;
262                 porphan->dFeePerKb = dFeePerKb;
263             }
264             else
265                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
266         }
267
268         // Collect transactions into block
269         map<uint256, CTxIndex> mapTestPool;
270         uint64 nBlockSize = 1000;
271         uint64 nBlockTx = 0;
272         int nBlockSigOps = 100;
273         bool fSortedByFee = (nBlockPrioritySize <= 0);
274
275         TxPriorityCompare comparer(fSortedByFee);
276         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
277
278         while (!vecPriority.empty())
279         {
280             // Take highest priority transaction off the priority queue:
281             double dPriority = vecPriority.front().get<0>();
282             double dFeePerKb = vecPriority.front().get<1>();
283             CTransaction& tx = *(vecPriority.front().get<2>());
284
285             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
286             vecPriority.pop_back();
287
288             // Size limits
289             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
290             if (nBlockSize + nTxSize >= nBlockMaxSize)
291                 continue;
292
293             // Legacy limits on sigOps:
294             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
295             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
296                 continue;
297
298             // Timestamp limit
299             if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
300                 continue;
301
302             // ppcoin: simplify transaction fee - allow free = false
303             int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
304
305             // Skip free transactions if we're past the minimum block size:
306             if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
307                 continue;
308
309             // Prioritize by fee once past the priority size or we run out of high-priority
310             // transactions:
311             if (!fSortedByFee &&
312                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
313             {
314                 fSortedByFee = true;
315                 comparer = TxPriorityCompare(fSortedByFee);
316                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
317             }
318
319             // Connecting shouldn't fail due to dependency on other memory pool transactions
320             // because we're already processing them in order of dependency
321             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
322             MapPrevTx mapInputs;
323             bool fInvalid;
324             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
325                 continue;
326
327             int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
328             if (nTxFees < nMinFee)
329                 continue;
330
331             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
332             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
333                 continue;
334
335             if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
336                 continue;
337             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
338             swap(mapTestPool, mapTestPoolTmp);
339
340             // Added
341             pblock->vtx.push_back(tx);
342             nBlockSize += nTxSize;
343             ++nBlockTx;
344             nBlockSigOps += nTxSigOps;
345             nFees += nTxFees;
346
347             if (fDebug && GetBoolArg("-printpriority"))
348             {
349                 printf("priority %.1f feeperkb %.1f txid %s\n",
350                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
351             }
352
353             // Add transactions that depend on this one to the priority queue
354             uint256 hash = tx.GetHash();
355             if (mapDependers.count(hash))
356             {
357                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
358                 {
359                     if (!porphan->setDependsOn.empty())
360                     {
361                         porphan->setDependsOn.erase(hash);
362                         if (porphan->setDependsOn.empty())
363                         {
364                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
365                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
366                         }
367                     }
368                 }
369             }
370         }
371
372         nLastBlockTx = nBlockTx;
373         nLastBlockSize = nBlockSize;
374
375         if (fDebug && GetBoolArg("-printpriority"))
376             printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
377
378         if (pblock->IsProofOfWork())
379             pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
380
381         // Fill in header
382         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
383         if (pblock->IsProofOfStake())
384             pblock->nTime      = pblock->vtx[1].nTime; //same as coinstake timestamp
385         pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
386         pblock->nTime          = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
387         if (pblock->IsProofOfWork())
388             pblock->UpdateTime(pindexPrev);
389         pblock->nNonce         = 0;
390     }
391
392     return pblock.release();
393 }
394
395
396 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
397 {
398     // Update nExtraNonce
399     static uint256 hashPrevBlock;
400     if (hashPrevBlock != pblock->hashPrevBlock)
401     {
402         nExtraNonce = 0;
403         hashPrevBlock = pblock->hashPrevBlock;
404     }
405     ++nExtraNonce;
406     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
407     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
408     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
409
410     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
411 }
412
413
414 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
415 {
416     //
417     // Pre-build hash buffers
418     //
419     struct
420     {
421         struct unnamed2
422         {
423             int nVersion;
424             uint256 hashPrevBlock;
425             uint256 hashMerkleRoot;
426             unsigned int nTime;
427             unsigned int nBits;
428             unsigned int nNonce;
429         }
430         block;
431         unsigned char pchPadding0[64];
432         uint256 hash1;
433         unsigned char pchPadding1[64];
434     }
435     tmp;
436     memset(&tmp, 0, sizeof(tmp));
437
438     tmp.block.nVersion       = pblock->nVersion;
439     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
440     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
441     tmp.block.nTime          = pblock->nTime;
442     tmp.block.nBits          = pblock->nBits;
443     tmp.block.nNonce         = pblock->nNonce;
444
445     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
446     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
447
448     // Byte swap all the input buffer
449     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
450         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
451
452     // Precalc the first half of the first hash, which stays constant
453     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
454
455     memcpy(pdata, &tmp.block, 128);
456     memcpy(phash1, &tmp.hash1, 64);
457 }
458
459
460 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
461 {
462     uint256 hashBlock = pblock->GetHash();
463     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
464
465     if(!pblock->IsProofOfWork())
466         return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
467
468     if (hashBlock > hashTarget)
469         return error("CheckWork() : proof-of-work not meeting target");
470
471     //// debug print
472     printf("CheckWork() : new proof-of-stake block found  \n  hash: %s  \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
473     pblock->print();
474     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
475
476     // Found a solution
477     {
478         LOCK(cs_main);
479         if (pblock->hashPrevBlock != hashBestChain)
480             return error("CheckWork() : generated block is stale");
481
482         // Remove key from key pool
483         reservekey.KeepKey();
484
485         // Track how many getdata requests this block gets
486         {
487             LOCK(wallet.cs_wallet);
488             wallet.mapRequestCount[hashBlock] = 0;
489         }
490
491         // Process this block the same as if we had received it from another node
492         if (!ProcessBlock(NULL, pblock))
493             return error("CheckWork() : ProcessBlock, block not accepted");
494     }
495
496     return true;
497 }
498
499 bool CheckStake(CBlock* pblock, CWallet& wallet)
500 {
501     uint256 proofHash = 0, hashTarget = 0;
502     uint256 hashBlock = pblock->GetHash();
503
504     if(!pblock->IsProofOfStake())
505         return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
506
507     // verify hash target and signature of coinstake tx
508     if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
509         return error("CheckStake() : proof-of-stake checking failed");
510
511     //// debug print
512     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());
513     pblock->print();
514     printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
515
516     // Found a solution
517     {
518         LOCK(cs_main);
519         if (pblock->hashPrevBlock != hashBestChain)
520             return error("CheckStake() : generated block is stale");
521
522         // Track how many getdata requests this block gets
523         {
524             LOCK(wallet.cs_wallet);
525             wallet.mapRequestCount[hashBlock] = 0;
526         }
527
528         // Process this block the same as if we had received it from another node
529         if (!ProcessBlock(NULL, pblock))
530             return error("CheckStake() : ProcessBlock, block not accepted");
531     }
532
533     return true;
534 }
535
536 void StakeMiner(CWallet *pwallet)
537 {
538     SetThreadPriority(THREAD_PRIORITY_LOWEST);
539
540     // Make this thread recognisable as the mining thread
541     RenameThread("novacoin-miner");
542
543     // Each thread has its own counter
544     unsigned int nExtraNonce = 0;
545
546     while (true)
547     {
548         if (fShutdown)
549             return;
550         while (vNodes.empty() || IsInitialBlockDownload())
551         {
552             Sleep(1000);
553             if (fShutdown)
554                 return;
555         }
556
557         while (pwallet->IsLocked())
558         {
559             strMintWarning = strMintMessage;
560             Sleep(1000);
561         }
562         strMintWarning = "";
563
564         //
565         // Create new block
566         //
567         CBlockIndex* pindexPrev = pindexBest;
568
569         auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
570         if (!pblock.get())
571             return;
572         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
573
574         if(pblock->IsProofOfStake())
575         {
576             // Trying to sign a block
577             if (!pblock->SignBlock(*pwallet))
578             {
579                 strMintWarning = strMintMessage;
580                 continue;
581             }
582
583             strMintWarning = "";
584             SetThreadPriority(THREAD_PRIORITY_NORMAL);
585             CheckStake(pblock.get(), *pwallet);
586             SetThreadPriority(THREAD_PRIORITY_LOWEST);
587         }
588
589         Sleep(500);
590         continue;
591     }
592 }