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