7c494faba107f134d70f9476e4940d1925a87c6e
[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 "db.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: Mining suspended due to locked wallet.";
19 string strMintWarning;
20
21 extern unsigned int nMinerSleep;
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     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     void print() const
75     {
76         printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
77                ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
78         BOOST_FOREACH(uint256 hash, setDependsOn)
79             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
80     }
81 };
82
83
84 uint64 nLastBlockTx = 0;
85 uint64 nLastBlockSize = 0;
86 int64 nLastCoinStakeSearchInterval = 0;
87  
88 // We want to sort transactions by priority and fee, so:
89 typedef boost::tuple<double, double, CTransaction*> TxPriority;
90 class TxPriorityCompare
91 {
92     bool byFee;
93 public:
94     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
95     bool operator()(const TxPriority& a, const TxPriority& b)
96     {
97         if (byFee)
98         {
99             if (a.get<1>() == b.get<1>())
100                 return a.get<0>() < b.get<0>();
101             return a.get<1>() < b.get<1>();
102         }
103         else
104         {
105             if (a.get<0>() == b.get<0>())
106                 return a.get<1>() < b.get<1>();
107             return a.get<0>() < b.get<0>();
108         }
109     }
110 };
111
112 // CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
113 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
114 {
115     // Create new block
116     auto_ptr<CBlock> pblock(new CBlock());
117     if (!pblock.get())
118         return NULL;
119
120     // Create coinbase tx
121     CTransaction txNew;
122     txNew.vin.resize(1);
123     txNew.vin[0].prevout.SetNull();
124     txNew.vout.resize(1);
125
126     if (!fProofOfStake)
127     {
128         CReserveKey reservekey(pwallet);
129         txNew.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
130     }
131     else
132         txNew.vout[0].SetEmpty();
133
134     // Add our coinbase tx as first transaction
135     pblock->vtx.push_back(txNew);
136
137     // Largest block you're willing to create:
138     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
139     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
140     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
141
142     // How much of the block should be dedicated to high-priority transactions,
143     // included regardless of the fees they pay
144     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
145     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
146
147     // Minimum block size you want to create; block will be filled with free transactions
148     // until there are no more or the block reaches this size:
149     unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
150     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
151
152     // Fee-per-kilobyte amount considered the same as "free"
153     // Be careful setting this: if you set it to zero then
154     // a transaction spammer can cheaply fill blocks using
155     // 1-satoshi-fee transactions. It should be set above the real
156     // cost to you of processing a transaction.
157     int64 nMinTxFee = MIN_TX_FEE;
158     if (mapArgs.count("-mintxfee"))
159         ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
160
161     CBlockIndex* pindexPrev = pindexBest;
162
163     pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
164
165     // Collect memory pool transactions into the block
166     int64 nFees = 0;
167     {
168         LOCK2(cs_main, mempool.cs);
169         CCoinsViewCache view(*pcoinsTip, true);
170
171         // Priority order to process transactions
172         list<COrphan> vOrphan; // list memory doesn't move
173         map<uint256, vector<COrphan*> > mapDependers;
174
175         // This vector will be sorted into a priority queue:
176         vector<TxPriority> vecPriority;
177         vecPriority.reserve(mempool.mapTx.size());
178         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
179         {
180             CTransaction& tx = (*mi).second;
181             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
182                 continue;
183
184             COrphan* porphan = NULL;
185             double dPriority = 0;
186             int64 nTotalIn = 0;
187             bool fMissingInputs = false;
188             BOOST_FOREACH(const CTxIn& txin, tx.vin)
189             {
190                 // Read prev transaction
191                 CCoins coins;
192                 if (!view.GetCoins(txin.prevout.hash, coins))
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 = coins.vout[txin.prevout.n].nValue;
220                 nTotalIn += nValueIn;
221
222                 int nConf = pindexPrev->nHeight - coins.nHeight;
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         uint64 nBlockSize = 1000;
247         uint64 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             // second layer cached modifications just for this transaction
265             CCoinsViewCache viewTemp(view, true);
266
267             // Size limits
268             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
269             if (nBlockSize + nTxSize >= nBlockMaxSize)
270                 continue;
271
272             // Legacy limits on sigOps:
273             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
274             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
275                 continue;
276
277             // Timestamp limit
278             if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
279                 continue;
280
281             // Simplify transaction fee - allow free = false
282             int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
283
284             // Skip free transactions if we're past the minimum block size:
285             if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
286                 continue;
287
288             // Prioritize by fee once past the priority size or we run out of high-priority
289             // transactions:
290             if (!fSortedByFee &&
291                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
292             {
293                 fSortedByFee = true;
294                 comparer = TxPriorityCompare(fSortedByFee);
295                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
296             }
297
298             if (!tx.CheckInputs(viewTemp, CS_ALWAYS, true, false))
299                 continue;
300
301             int64 nTxFees = tx.GetValueIn(viewTemp)-tx.GetValueOut();
302             if (nTxFees < nMinFee)
303                 continue;
304
305             nTxSigOps += tx.GetP2SHSigOpCount(viewTemp);
306             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
307                 continue;
308
309             CTxUndo txundo;
310             if (!tx.UpdateCoins(viewTemp, txundo, pindexPrev->nHeight+1, pblock->nTime))
311                 continue;
312
313             // push changes from the second layer cache to the first one
314             viewTemp.Flush();
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 (fDebug && GetBoolArg("-printpriority"))
352             printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
353
354         if (!fProofOfStake)
355             pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
356
357         // Fill in header
358         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
359         pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
360         pblock->nTime          = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
361         if (!fProofOfStake)
362             pblock->UpdateTime(pindexPrev);
363         pblock->nNonce         = 0;
364     }
365
366     return pblock.release();
367 }
368
369
370 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
371 {
372     // Update nExtraNonce
373     static uint256 hashPrevBlock;
374     if (hashPrevBlock != pblock->hashPrevBlock)
375     {
376         nExtraNonce = 0;
377         hashPrevBlock = pblock->hashPrevBlock;
378     }
379     ++nExtraNonce;
380
381     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
382     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
383     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
384
385     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
386 }
387
388
389 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
390 {
391     //
392     // Pre-build hash buffers
393     //
394     struct
395     {
396         struct unnamed2
397         {
398             int nVersion;
399             uint256 hashPrevBlock;
400             uint256 hashMerkleRoot;
401             unsigned int nTime;
402             unsigned int nBits;
403             unsigned int nNonce;
404         }
405         block;
406         unsigned char pchPadding0[64];
407         uint256 hash1;
408         unsigned char pchPadding1[64];
409     }
410     tmp;
411     memset(&tmp, 0, sizeof(tmp));
412
413     tmp.block.nVersion       = pblock->nVersion;
414     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
415     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
416     tmp.block.nTime          = pblock->nTime;
417     tmp.block.nBits          = pblock->nBits;
418     tmp.block.nNonce         = pblock->nNonce;
419
420     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
421     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
422
423     // Byte swap all the input buffer
424     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
425         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
426
427     // Precalc the first half of the first hash, which stays constant
428     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
429
430     memcpy(pdata, &tmp.block, 128);
431     memcpy(phash1, &tmp.hash1, 64);
432 }
433
434
435 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
436 {
437     uint256 hashBlock = pblock->GetHash();
438     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
439
440     if(!pblock->IsProofOfWork())
441         return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
442
443     if (hashBlock > hashTarget)
444         return error("CheckWork() : proof-of-work not meeting target");
445
446     //// debug print
447     printf("CheckWork() : new proof-of-work block found  \n  hash: %s  \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
448     pblock->print();
449     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
450
451     // Found a solution
452     {
453         LOCK(cs_main);
454         if (pblock->hashPrevBlock != hashBestChain)
455             return error("CheckWork() : generated block is stale");
456
457         // Remove key from key pool
458         reservekey.KeepKey();
459
460         // Track how many getdata requests this block gets
461         {
462             LOCK(wallet.cs_wallet);
463             wallet.mapRequestCount[hashBlock] = 0;
464         }
465
466         // Process this block the same as if we had received it from another node
467         if (!ProcessBlock(NULL, pblock))
468             return error("CheckWork() : ProcessBlock, block not accepted");
469     }
470
471     return true;
472 }
473
474 bool CheckStake(CBlock* pblock, CWallet& wallet)
475 {
476     uint256 proofHash = 0, hashTarget = 0;
477     uint256 hashBlock = pblock->GetHash();
478
479     if(!pblock->IsProofOfStake())
480         return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
481
482     // verify hash target and signature of coinstake tx
483     if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
484         return error("CheckStake() : proof-of-stake checking failed");
485
486     //// debug print
487     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());
488     pblock->print();
489     printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
490
491     // Found a solution
492     {
493         LOCK(cs_main);
494         if (pblock->hashPrevBlock != hashBestChain)
495             return error("CheckStake() : generated block is stale");
496
497         // Track how many getdata requests this block gets
498         {
499             LOCK(wallet.cs_wallet);
500             wallet.mapRequestCount[hashBlock] = 0;
501         }
502
503         // Process this block the same as if we had received it from another node
504         if (!ProcessBlock(NULL, pblock))
505             return error("CheckStake() : ProcessBlock, block not accepted");
506     }
507
508     return true;
509 }
510
511 void StakeMiner(CWallet *pwallet)
512 {
513     SetThreadPriority(THREAD_PRIORITY_LOWEST);
514
515     // Make this thread recognisable as the mining thread
516     RenameThread("novacoin-miner");
517
518     // Each thread has its own counter
519     unsigned int nExtraNonce = 0;
520
521     while (true)
522     {
523         if (fShutdown)
524             return;
525
526         while (pwallet->IsLocked())
527         {
528             strMintWarning = strMintMessage;
529             Sleep(1000);
530             if (fShutdown)
531                 return;
532         }
533
534         while (vNodes.empty() || IsInitialBlockDownload())
535         {
536             Sleep(1000);
537             if (fShutdown)
538                 return;
539         }
540
541         strMintWarning = "";
542
543         //
544         // Create new block
545         //
546         CBlockIndex* pindexPrev = pindexBest;
547
548         auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
549         if (!pblock.get())
550             return;
551         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
552
553         // Trying to sign a block
554         if (pblock->SignBlock(*pwallet))
555         {
556             strMintWarning = _("Stake generation: new block found!");
557             SetThreadPriority(THREAD_PRIORITY_NORMAL);
558             CheckStake(pblock.get(), *pwallet);
559             SetThreadPriority(THREAD_PRIORITY_LOWEST);
560             Sleep(500);
561         }
562         else
563             Sleep(nMinerSleep);
564
565         continue;
566     }
567 }