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.
13 //////////////////////////////////////////////////////////////////////////////
18 string strMintMessage = "Stake miner suspended due to locked wallet.";
19 string strMintWarning;
21 extern unsigned int nMinerSleep;
23 int static FormatHashBlocks(void* pbuffer, unsigned int len)
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);
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;
38 static const unsigned int pSHA256InitState[8] =
39 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
41 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
44 unsigned char data[64];
48 for (int i = 0; i < 16; i++)
49 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
51 for (int i = 0; i < 8; i++)
52 ctx.h[i] = ((uint32_t*)pinit)[i];
54 SHA256_Update(&ctx, data, sizeof(data));
55 for (int i = 0; i < 8; i++)
56 ((uint32_t*)pstate)[i] = ctx.h[i];
59 // Some explaining would be appreciated
64 set<uint256> setDependsOn;
68 COrphan(CTransaction* ptxIn)
71 dPriority = dFeePerKb = 0;
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());
84 uint64 nLastBlockTx = 0;
85 uint64 nLastBlockSize = 0;
86 int64 nLastCoinStakeSearchInterval = 0;
88 // We want to sort transactions by priority and fee, so:
89 typedef boost::tuple<double, double, CTransaction*> TxPriority;
90 class TxPriorityCompare
94 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
95 bool operator()(const TxPriority& a, const TxPriority& b)
99 if (a.get<1>() == b.get<1>())
100 return a.get<0>() < b.get<0>();
101 return a.get<1>() < b.get<1>();
105 if (a.get<0>() == b.get<0>())
106 return a.get<1>() < b.get<1>();
107 return a.get<0>() < b.get<0>();
112 // CreateNewBlock: create new block (without proof-of-work/proof-of-stake)
113 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
116 auto_ptr<CBlock> pblock(new CBlock());
120 // Create coinbase tx
123 txNew.vin[0].prevout.SetNull();
124 txNew.vout.resize(1);
128 CReserveKey reservekey(pwallet);
129 txNew.vout[0].scriptPubKey.SetDestination(reservekey.GetReservedKey().GetID());
132 txNew.vout[0].SetEmpty();
134 // Add our coinbase tx as first transaction
135 pblock->vtx.push_back(txNew);
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));
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);
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);
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);
161 CBlockIndex* pindexPrev = pindexBest;
163 pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake);
165 // Collect memory pool transactions into the block
168 LOCK2(cs_main, mempool.cs);
169 CBlockIndex* pindexPrev = pindexBest;
172 // Priority order to process transactions
173 list<COrphan> vOrphan; // list memory doesn't move
174 map<uint256, vector<COrphan*> > mapDependers;
176 // This vector will be sorted into a priority queue:
177 vector<TxPriority> vecPriority;
178 vecPriority.reserve(mempool.mapTx.size());
179 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
181 CTransaction& tx = (*mi).second;
182 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
185 COrphan* porphan = NULL;
186 double dPriority = 0;
188 bool fMissingInputs = false;
189 BOOST_FOREACH(const CTxIn& txin, tx.vin)
191 // Read prev transaction
194 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
196 // This should never happen; all transactions in the memory
197 // pool should connect to either transactions in the chain
198 // or other transactions in the memory pool.
199 if (!mempool.mapTx.count(txin.prevout.hash))
201 printf("ERROR: mempool transaction missing input\n");
202 if (fDebug) assert("mempool transaction missing input" == 0);
203 fMissingInputs = true;
209 // Has to wait for dependencies
212 // Use list for automatic deletion
213 vOrphan.push_back(COrphan(&tx));
214 porphan = &vOrphan.back();
216 mapDependers[txin.prevout.hash].push_back(porphan);
217 porphan->setDependsOn.insert(txin.prevout.hash);
218 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
221 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
222 nTotalIn += nValueIn;
224 int nConf = txindex.GetDepthInMainChain();
225 dPriority += (double)nValueIn * nConf;
227 if (fMissingInputs) continue;
229 // Priority is sum(valuein * age) / txsize
230 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
231 dPriority /= nTxSize;
233 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
234 // client code rounds up the size to the nearest 1K. That's good, because it gives an
235 // incentive to create smaller transactions.
236 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
240 porphan->dPriority = dPriority;
241 porphan->dFeePerKb = dFeePerKb;
244 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
247 // Collect transactions into block
248 map<uint256, CTxIndex> mapTestPool;
249 uint64 nBlockSize = 1000;
251 int nBlockSigOps = 100;
252 bool fSortedByFee = (nBlockPrioritySize <= 0);
254 TxPriorityCompare comparer(fSortedByFee);
255 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
257 while (!vecPriority.empty())
259 // Take highest priority transaction off the priority queue:
260 double dPriority = vecPriority.front().get<0>();
261 double dFeePerKb = vecPriority.front().get<1>();
262 CTransaction& tx = *(vecPriority.front().get<2>());
264 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
265 vecPriority.pop_back();
268 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
269 if (nBlockSize + nTxSize >= nBlockMaxSize)
272 // Legacy limits on sigOps:
273 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
274 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
278 if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime))
281 // Simplify transaction fee - allow free = false
282 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
284 // Skip free transactions if we're past the minimum block size:
285 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
288 // Prioritize by fee once past the priority size or we run out of high-priority
291 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
294 comparer = TxPriorityCompare(fSortedByFee);
295 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
298 // Connecting shouldn't fail due to dependency on other memory pool transactions
299 // because we're already processing them in order of dependency
300 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
303 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
306 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
307 if (nTxFees < nMinFee)
310 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
311 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
314 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
316 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
317 swap(mapTestPool, mapTestPoolTmp);
320 pblock->vtx.push_back(tx);
321 nBlockSize += nTxSize;
323 nBlockSigOps += nTxSigOps;
326 if (fDebug && GetBoolArg("-printpriority"))
328 printf("priority %.1f feeperkb %.1f txid %s\n",
329 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
332 // Add transactions that depend on this one to the priority queue
333 uint256 hash = tx.GetHash();
334 if (mapDependers.count(hash))
336 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
338 if (!porphan->setDependsOn.empty())
340 porphan->setDependsOn.erase(hash);
341 if (porphan->setDependsOn.empty())
343 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
344 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
351 nLastBlockTx = nBlockTx;
352 nLastBlockSize = nBlockSize;
354 if (fDebug && GetBoolArg("-printpriority"))
355 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
358 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
361 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
362 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
363 pblock->nTime = max(pblock->GetBlockTime(), PastDrift(pindexPrev->GetBlockTime()));
365 pblock->UpdateTime(pindexPrev);
369 return pblock.release();
373 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
375 // Update nExtraNonce
376 static uint256 hashPrevBlock;
377 if (hashPrevBlock != pblock->hashPrevBlock)
380 hashPrevBlock = pblock->hashPrevBlock;
384 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
385 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
386 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
388 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
392 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
395 // Pre-build hash buffers
402 uint256 hashPrevBlock;
403 uint256 hashMerkleRoot;
409 unsigned char pchPadding0[64];
411 unsigned char pchPadding1[64];
414 memset(&tmp, 0, sizeof(tmp));
416 tmp.block.nVersion = pblock->nVersion;
417 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
418 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
419 tmp.block.nTime = pblock->nTime;
420 tmp.block.nBits = pblock->nBits;
421 tmp.block.nNonce = pblock->nNonce;
423 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
424 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
426 // Byte swap all the input buffer
427 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
428 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
430 // Precalc the first half of the first hash, which stays constant
431 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
433 memcpy(pdata, &tmp.block, 128);
434 memcpy(phash1, &tmp.hash1, 64);
438 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
440 uint256 hashBlock = pblock->GetHash();
441 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
443 if(!pblock->IsProofOfWork())
444 return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str());
446 if (hashBlock > hashTarget)
447 return error("CheckWork() : proof-of-work not meeting target");
450 printf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str());
452 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
457 if (pblock->hashPrevBlock != hashBestChain)
458 return error("CheckWork() : generated block is stale");
460 // Remove key from key pool
461 reservekey.KeepKey();
463 // Track how many getdata requests this block gets
465 LOCK(wallet.cs_wallet);
466 wallet.mapRequestCount[hashBlock] = 0;
469 // Process this block the same as if we had received it from another node
470 if (!ProcessBlock(NULL, pblock))
471 return error("CheckWork() : ProcessBlock, block not accepted");
477 bool CheckStake(CBlock* pblock, CWallet& wallet)
479 uint256 proofHash = 0, hashTarget = 0;
480 uint256 hashBlock = pblock->GetHash();
482 if(!pblock->IsProofOfStake())
483 return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str());
485 // verify hash target and signature of coinstake tx
486 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, proofHash, hashTarget))
487 return error("CheckStake() : proof-of-stake checking failed");
490 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());
492 printf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str());
497 if (pblock->hashPrevBlock != hashBestChain)
498 return error("CheckStake() : generated block is stale");
500 // Track how many getdata requests this block gets
502 LOCK(wallet.cs_wallet);
503 wallet.mapRequestCount[hashBlock] = 0;
506 // Process this block the same as if we had received it from another node
507 if (!ProcessBlock(NULL, pblock))
508 return error("CheckStake() : ProcessBlock, block not accepted");
514 void StakeMiner(CWallet *pwallet)
516 SetThreadPriority(THREAD_PRIORITY_LOWEST);
518 // Make this thread recognisable as the mining thread
519 RenameThread("novacoin-miner");
521 // Each thread has its own counter
522 unsigned int nExtraNonce = 0;
529 while (pwallet->IsLocked())
531 strMintWarning = strMintMessage;
537 while (vNodes.empty() || IsInitialBlockDownload())
549 CBlockIndex* pindexPrev = pindexBest;
551 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true));
554 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
556 // Trying to sign a block
557 if (pblock->SignBlock(*pwallet))
559 strMintWarning = _("Stake generation: new block found!");
560 SetThreadPriority(THREAD_PRIORITY_NORMAL);
561 CheckStake(pblock.get(), *pwallet);
562 SetThreadPriority(THREAD_PRIORITY_LOWEST);