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