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