]>
Commit | Line | Data |
---|---|---|
d247a5d1 | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
f914f1a7 | 2 | // Copyright (c) 2009-2014 The Bitcoin Core developers |
78253fcb | 3 | // Distributed under the MIT software license, see the accompanying |
d247a5d1 JG |
4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5 | ||
d247a5d1 | 6 | #include "miner.h" |
51ed9ec9 | 7 | |
eda37330 | 8 | #include "amount.h" |
d2270111 | 9 | #include "primitives/transaction.h" |
85aab2a0 | 10 | #include "hash.h" |
d247a5d1 | 11 | #include "main.h" |
51ed9ec9 | 12 | #include "net.h" |
df852d2b | 13 | #include "pow.h" |
22c4272b | 14 | #include "timedata.h" |
ad49c256 WL |
15 | #include "util.h" |
16 | #include "utilmoneystr.h" | |
df840de5 | 17 | #ifdef ENABLE_WALLET |
50c72f23 | 18 | #include "wallet/wallet.h" |
df840de5 | 19 | #endif |
09eb201b | 20 | |
ad49c256 | 21 | #include <boost/thread.hpp> |
a3c26c2e | 22 | #include <boost/tuple/tuple.hpp> |
ad49c256 | 23 | |
09eb201b | 24 | using namespace std; |
7b4737c8 | 25 | |
d247a5d1 JG |
26 | ////////////////////////////////////////////////////////////////////////////// |
27 | // | |
28 | // BitcoinMiner | |
29 | // | |
30 | ||
c6cb21d1 GA |
31 | // |
32 | // Unconfirmed transactions in the memory pool often depend on other | |
33 | // transactions in the memory pool. When we select transactions from the | |
34 | // pool, we select by highest priority or fee rate, so we might consider | |
35 | // transactions that depend on transactions that aren't yet in the block. | |
36 | // The COrphan class keeps track of these 'temporary orphans' while | |
37 | // CreateBlock is figuring out which transactions to include. | |
38 | // | |
d247a5d1 JG |
39 | class COrphan |
40 | { | |
41 | public: | |
4d707d51 | 42 | const CTransaction* ptx; |
d247a5d1 | 43 | set<uint256> setDependsOn; |
c6cb21d1 | 44 | CFeeRate feeRate; |
02bec4b2 | 45 | double dPriority; |
d247a5d1 | 46 | |
c6cb21d1 | 47 | COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) |
d247a5d1 | 48 | { |
d247a5d1 | 49 | } |
d247a5d1 JG |
50 | }; |
51 | ||
51ed9ec9 BD |
52 | uint64_t nLastBlockTx = 0; |
53 | uint64_t nLastBlockSize = 0; | |
d247a5d1 | 54 | |
c6cb21d1 GA |
55 | // We want to sort transactions by priority and fee rate, so: |
56 | typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority; | |
d247a5d1 JG |
57 | class TxPriorityCompare |
58 | { | |
59 | bool byFee; | |
0655fac0 | 60 | |
d247a5d1 JG |
61 | public: |
62 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
0655fac0 | 63 | |
d247a5d1 JG |
64 | bool operator()(const TxPriority& a, const TxPriority& b) |
65 | { | |
66 | if (byFee) | |
67 | { | |
68 | if (a.get<1>() == b.get<1>()) | |
69 | return a.get<0>() < b.get<0>(); | |
70 | return a.get<1>() < b.get<1>(); | |
71 | } | |
72 | else | |
73 | { | |
74 | if (a.get<0>() == b.get<0>()) | |
75 | return a.get<1>() < b.get<1>(); | |
76 | return a.get<0>() < b.get<0>(); | |
77 | } | |
78 | } | |
79 | }; | |
80 | ||
22c4272b | 81 | void UpdateTime(CBlockHeader* pblock, const CBlockIndex* pindexPrev) |
82 | { | |
83 | pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); | |
84 | ||
85 | // Updating time can change work required on testnet: | |
86 | if (Params().AllowMinDifficultyBlocks()) | |
d698ef69 | 87 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
22c4272b | 88 | } |
89 | ||
48265f3c | 90 | CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) |
d247a5d1 JG |
91 | { |
92 | // Create new block | |
93 | auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); | |
94 | if(!pblocktemplate.get()) | |
95 | return NULL; | |
96 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience | |
97 | ||
dbca89b7 GA |
98 | // -regtest only: allow overriding block.nVersion with |
99 | // -blockversion=N to test forking scenarios | |
100 | if (Params().MineBlocksOnDemand()) | |
101 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); | |
102 | ||
d247a5d1 | 103 | // Create coinbase tx |
4949004d | 104 | CMutableTransaction txNew; |
d247a5d1 JG |
105 | txNew.vin.resize(1); |
106 | txNew.vin[0].prevout.SetNull(); | |
107 | txNew.vout.resize(1); | |
7e170189 | 108 | txNew.vout[0].scriptPubKey = scriptPubKeyIn; |
d247a5d1 | 109 | |
4949004d PW |
110 | // Add dummy coinbase tx as first transaction |
111 | pblock->vtx.push_back(CTransaction()); | |
d247a5d1 JG |
112 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
113 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
114 | ||
115 | // Largest block you're willing to create: | |
ad898b40 | 116 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
117 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
118 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
119 | ||
120 | // How much of the block should be dedicated to high-priority transactions, | |
121 | // included regardless of the fees they pay | |
122 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
123 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
124 | ||
125 | // Minimum block size you want to create; block will be filled with free transactions | |
126 | // until there are no more or the block reaches this size: | |
037b4f14 | 127 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 JG |
128 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
129 | ||
130 | // Collect memory pool transactions into the block | |
a372168e | 131 | CAmount nFees = 0; |
0655fac0 | 132 | |
d247a5d1 JG |
133 | { |
134 | LOCK2(cs_main, mempool.cs); | |
48265f3c | 135 | CBlockIndex* pindexPrev = chainActive.Tip(); |
b867e409 | 136 | const int nHeight = pindexPrev->nHeight + 1; |
7c70438d | 137 | CCoinsViewCache view(pcoinsTip); |
d247a5d1 JG |
138 | |
139 | // Priority order to process transactions | |
140 | list<COrphan> vOrphan; // list memory doesn't move | |
141 | map<uint256, vector<COrphan*> > mapDependers; | |
142 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
143 | ||
144 | // This vector will be sorted into a priority queue: | |
145 | vector<TxPriority> vecPriority; | |
146 | vecPriority.reserve(mempool.mapTx.size()); | |
4d707d51 GA |
147 | for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin(); |
148 | mi != mempool.mapTx.end(); ++mi) | |
d247a5d1 | 149 | { |
4d707d51 | 150 | const CTransaction& tx = mi->second.GetTx(); |
b867e409 | 151 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight)) |
d247a5d1 JG |
152 | continue; |
153 | ||
154 | COrphan* porphan = NULL; | |
155 | double dPriority = 0; | |
a372168e | 156 | CAmount nTotalIn = 0; |
d247a5d1 JG |
157 | bool fMissingInputs = false; |
158 | BOOST_FOREACH(const CTxIn& txin, tx.vin) | |
159 | { | |
160 | // Read prev transaction | |
161 | if (!view.HaveCoins(txin.prevout.hash)) | |
162 | { | |
163 | // This should never happen; all transactions in the memory | |
164 | // pool should connect to either transactions in the chain | |
165 | // or other transactions in the memory pool. | |
166 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
167 | { | |
881a85a2 | 168 | LogPrintf("ERROR: mempool transaction missing input\n"); |
d247a5d1 JG |
169 | if (fDebug) assert("mempool transaction missing input" == 0); |
170 | fMissingInputs = true; | |
171 | if (porphan) | |
172 | vOrphan.pop_back(); | |
173 | break; | |
174 | } | |
175 | ||
176 | // Has to wait for dependencies | |
177 | if (!porphan) | |
178 | { | |
179 | // Use list for automatic deletion | |
180 | vOrphan.push_back(COrphan(&tx)); | |
181 | porphan = &vOrphan.back(); | |
182 | } | |
183 | mapDependers[txin.prevout.hash].push_back(porphan); | |
184 | porphan->setDependsOn.insert(txin.prevout.hash); | |
4d707d51 | 185 | nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue; |
d247a5d1 JG |
186 | continue; |
187 | } | |
629d75fa PW |
188 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
189 | assert(coins); | |
d247a5d1 | 190 | |
a372168e | 191 | CAmount nValueIn = coins->vout[txin.prevout.n].nValue; |
d247a5d1 JG |
192 | nTotalIn += nValueIn; |
193 | ||
b867e409 | 194 | int nConf = nHeight - coins->nHeight; |
d247a5d1 JG |
195 | |
196 | dPriority += (double)nValueIn * nConf; | |
197 | } | |
198 | if (fMissingInputs) continue; | |
199 | ||
d6eb2599 | 200 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 201 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 202 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
d247a5d1 | 203 | |
2a72d459 LD |
204 | uint256 hash = tx.GetHash(); |
205 | mempool.ApplyDeltas(hash, dPriority, nTotalIn); | |
206 | ||
c6cb21d1 | 207 | CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize); |
d247a5d1 JG |
208 | |
209 | if (porphan) | |
210 | { | |
211 | porphan->dPriority = dPriority; | |
c6cb21d1 | 212 | porphan->feeRate = feeRate; |
d247a5d1 JG |
213 | } |
214 | else | |
c6cb21d1 | 215 | vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx())); |
d247a5d1 JG |
216 | } |
217 | ||
218 | // Collect transactions into block | |
51ed9ec9 BD |
219 | uint64_t nBlockSize = 1000; |
220 | uint64_t nBlockTx = 0; | |
d247a5d1 JG |
221 | int nBlockSigOps = 100; |
222 | bool fSortedByFee = (nBlockPrioritySize <= 0); | |
223 | ||
224 | TxPriorityCompare comparer(fSortedByFee); | |
225 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
226 | ||
227 | while (!vecPriority.empty()) | |
228 | { | |
229 | // Take highest priority transaction off the priority queue: | |
230 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 231 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 232 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
d247a5d1 JG |
233 | |
234 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
235 | vecPriority.pop_back(); | |
236 | ||
237 | // Size limits | |
238 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
239 | if (nBlockSize + nTxSize >= nBlockMaxSize) | |
240 | continue; | |
241 | ||
242 | // Legacy limits on sigOps: | |
243 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
244 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) | |
245 | continue; | |
246 | ||
247 | // Skip free transactions if we're past the minimum block size: | |
2a72d459 LD |
248 | const uint256& hash = tx.GetHash(); |
249 | double dPriorityDelta = 0; | |
a372168e | 250 | CAmount nFeeDelta = 0; |
2a72d459 | 251 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 252 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
d247a5d1 JG |
253 | continue; |
254 | ||
2a72d459 | 255 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
256 | // transactions: |
257 | if (!fSortedByFee && | |
258 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
259 | { | |
260 | fSortedByFee = true; | |
261 | comparer = TxPriorityCompare(fSortedByFee); | |
262 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
263 | } | |
264 | ||
265 | if (!view.HaveInputs(tx)) | |
266 | continue; | |
267 | ||
a372168e | 268 | CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut(); |
d247a5d1 JG |
269 | |
270 | nTxSigOps += GetP2SHSigOpCount(tx, view); | |
271 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) | |
272 | continue; | |
273 | ||
68f7d1d7 PT |
274 | // Note that flags: we don't want to set mempool/IsStandard() |
275 | // policy here, but we still have to ensure that the block we | |
276 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 277 | CValidationState state; |
e790c370 | 278 | if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) |
d247a5d1 JG |
279 | continue; |
280 | ||
d7621ccf | 281 | UpdateCoins(tx, state, view, nHeight); |
d247a5d1 JG |
282 | |
283 | // Added | |
284 | pblock->vtx.push_back(tx); | |
285 | pblocktemplate->vTxFees.push_back(nTxFees); | |
286 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
287 | nBlockSize += nTxSize; | |
288 | ++nBlockTx; | |
289 | nBlockSigOps += nTxSigOps; | |
290 | nFees += nTxFees; | |
291 | ||
292 | if (fPrintPriority) | |
293 | { | |
c6cb21d1 | 294 | LogPrintf("priority %.1f fee %s txid %s\n", |
0655fac0 | 295 | dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 JG |
296 | } |
297 | ||
298 | // Add transactions that depend on this one to the priority queue | |
299 | if (mapDependers.count(hash)) | |
300 | { | |
301 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
302 | { | |
303 | if (!porphan->setDependsOn.empty()) | |
304 | { | |
305 | porphan->setDependsOn.erase(hash); | |
306 | if (porphan->setDependsOn.empty()) | |
307 | { | |
c6cb21d1 | 308 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
309 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
310 | } | |
311 | } | |
312 | } | |
313 | } | |
314 | } | |
315 | ||
316 | nLastBlockTx = nBlockTx; | |
317 | nLastBlockSize = nBlockSize; | |
f48742c2 | 318 | LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize); |
d247a5d1 | 319 | |
4949004d | 320 | // Compute final coinbase transaction. |
b867e409 LD |
321 | txNew.vout[0].nValue = GetBlockValue(nHeight, nFees); |
322 | txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; | |
4949004d | 323 | pblock->vtx[0] = txNew; |
d247a5d1 JG |
324 | pblocktemplate->vTxFees[0] = -nFees; |
325 | ||
326 | // Fill in header | |
327 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
c2c02f3f | 328 | UpdateTime(pblock, pindexPrev); |
d698ef69 | 329 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
d247a5d1 | 330 | pblock->nNonce = 0; |
d247a5d1 JG |
331 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
332 | ||
d247a5d1 | 333 | CValidationState state; |
df08a626 | 334 | if (!TestBlockValidity(state, *pblock, pindexPrev, false, false)) |
5262fde0 | 335 | throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
d247a5d1 JG |
336 | } |
337 | ||
338 | return pblocktemplate.release(); | |
339 | } | |
340 | ||
d247a5d1 JG |
341 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
342 | { | |
343 | // Update nExtraNonce | |
344 | static uint256 hashPrevBlock; | |
345 | if (hashPrevBlock != pblock->hashPrevBlock) | |
346 | { | |
347 | nExtraNonce = 0; | |
348 | hashPrevBlock = pblock->hashPrevBlock; | |
349 | } | |
350 | ++nExtraNonce; | |
351 | unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 | |
4949004d PW |
352 | CMutableTransaction txCoinbase(pblock->vtx[0]); |
353 | txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
354 | assert(txCoinbase.vin[0].scriptSig.size() <= 100); | |
d247a5d1 | 355 | |
4949004d | 356 | pblock->vtx[0] = txCoinbase; |
d247a5d1 JG |
357 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
358 | } | |
359 | ||
4a85e067 | 360 | #ifdef ENABLE_WALLET |
acfa0333 WL |
361 | ////////////////////////////////////////////////////////////////////////////// |
362 | // | |
363 | // Internal miner | |
364 | // | |
acfa0333 WL |
365 | |
366 | // | |
367 | // ScanHash scans nonces looking for a hash with at least some zero bits. | |
48265f3c WL |
368 | // The nonce is usually preserved between calls, but periodically or if the |
369 | // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at | |
370 | // zero. | |
acfa0333 | 371 | // |
48265f3c | 372 | bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash) |
0655fac0 | 373 | { |
48265f3c WL |
374 | // Write the first 76 bytes of the block header to a double-SHA256 state. |
375 | CHash256 hasher; | |
376 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
377 | ss << *pblock; | |
378 | assert(ss.size() == 80); | |
379 | hasher.Write((unsigned char*)&ss[0], 76); | |
380 | ||
0655fac0 | 381 | while (true) { |
48265f3c WL |
382 | nNonce++; |
383 | ||
384 | // Write the last 4 bytes of the block header (the nonce) to a copy of | |
385 | // the double-SHA256 state, and compute the result. | |
386 | CHash256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash); | |
acfa0333 WL |
387 | |
388 | // Return the nonce if the hash has at least some zero bits, | |
389 | // caller will check if it has enough to reach the target | |
85aab2a0 PW |
390 | if (((uint16_t*)phash)[15] == 0) |
391 | return true; | |
acfa0333 | 392 | |
48265f3c WL |
393 | // If nothing found after trying for a while, return -1 |
394 | if ((nNonce & 0xfff) == 0) | |
0cc0d8d6 | 395 | return false; |
acfa0333 WL |
396 | } |
397 | } | |
398 | ||
48265f3c | 399 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) |
acfa0333 WL |
400 | { |
401 | CPubKey pubkey; | |
402 | if (!reservekey.GetReservedKey(pubkey)) | |
403 | return NULL; | |
404 | ||
e9ca4280 | 405 | CScript scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; |
48265f3c | 406 | return CreateNewBlock(scriptPubKey); |
acfa0333 WL |
407 | } |
408 | ||
269d8ba0 | 409 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
d247a5d1 | 410 | { |
81212588 | 411 | LogPrintf("%s\n", pblock->ToString()); |
7d9d134b | 412 | LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue)); |
d247a5d1 JG |
413 | |
414 | // Found a solution | |
415 | { | |
416 | LOCK(cs_main); | |
4c6d41b8 | 417 | if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash()) |
5262fde0 | 418 | return error("BitcoinMiner: generated block is stale"); |
18e72167 | 419 | } |
d247a5d1 | 420 | |
18e72167 PW |
421 | // Remove key from key pool |
422 | reservekey.KeepKey(); | |
d247a5d1 | 423 | |
18e72167 PW |
424 | // Track how many getdata requests this block gets |
425 | { | |
426 | LOCK(wallet.cs_wallet); | |
427 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 JG |
428 | } |
429 | ||
18e72167 PW |
430 | // Process this block the same as if we had received it from another node |
431 | CValidationState state; | |
1bea2bbd | 432 | if (!ProcessNewBlock(state, NULL, pblock)) |
5262fde0 | 433 | return error("BitcoinMiner: ProcessNewBlock, block not accepted"); |
18e72167 | 434 | |
d247a5d1 JG |
435 | return true; |
436 | } | |
437 | ||
438 | void static BitcoinMiner(CWallet *pwallet) | |
439 | { | |
881a85a2 | 440 | LogPrintf("BitcoinMiner started\n"); |
d247a5d1 JG |
441 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
442 | RenameThread("bitcoin-miner"); | |
443 | ||
444 | // Each thread has its own key and counter | |
445 | CReserveKey reservekey(pwallet); | |
446 | unsigned int nExtraNonce = 0; | |
447 | ||
0655fac0 PK |
448 | try { |
449 | while (true) { | |
450 | if (Params().MiningRequiresPeers()) { | |
451 | // Busy-wait for the network to come online so we don't waste time mining | |
452 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
453 | while (vNodes.empty()) | |
454 | MilliSleep(1000); | |
455 | } | |
d247a5d1 | 456 | |
0655fac0 PK |
457 | // |
458 | // Create new block | |
459 | // | |
460 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
48265f3c | 461 | CBlockIndex* pindexPrev = chainActive.Tip(); |
0655fac0 | 462 | |
48265f3c | 463 | auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey)); |
0655fac0 | 464 | if (!pblocktemplate.get()) |
6c37f7fd WL |
465 | { |
466 | LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); | |
0655fac0 | 467 | return; |
6c37f7fd | 468 | } |
0655fac0 PK |
469 | CBlock *pblock = &pblocktemplate->block; |
470 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); | |
471 | ||
472 | LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(), | |
473 | ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); | |
474 | ||
475 | // | |
476 | // Search | |
477 | // | |
478 | int64_t nStart = GetTime(); | |
48265f3c WL |
479 | arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); |
480 | uint256 hash; | |
481 | uint32_t nNonce = 0; | |
0655fac0 | 482 | while (true) { |
0655fac0 | 483 | // Check if something found |
48265f3c WL |
484 | if (ScanHash(pblock, nNonce, &hash)) |
485 | { | |
486 | if (UintToArith256(hash) <= hashTarget) | |
487 | { | |
488 | // Found a solution | |
489 | pblock->nNonce = nNonce; | |
490 | assert(hash == pblock->GetHash()); | |
491 | ||
492 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
493 | LogPrintf("BitcoinMiner:\n"); | |
494 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex()); | |
495 | ProcessBlockFound(pblock, *pwallet, reservekey); | |
496 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
497 | ||
498 | // In regression test mode, stop mining after a block is found. | |
499 | if (Params().MineBlocksOnDemand()) | |
500 | throw boost::thread_interrupted(); | |
501 | ||
502 | break; | |
503 | } | |
504 | } | |
d247a5d1 | 505 | |
0655fac0 PK |
506 | // Check for stop or if block needs to be rebuilt |
507 | boost::this_thread::interruption_point(); | |
508 | // Regtest mode doesn't require peers | |
509 | if (vNodes.empty() && Params().MiningRequiresPeers()) | |
510 | break; | |
48265f3c | 511 | if (nNonce >= 0xffff0000) |
0655fac0 PK |
512 | break; |
513 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
514 | break; | |
515 | if (pindexPrev != chainActive.Tip()) | |
516 | break; | |
517 | ||
48265f3c WL |
518 | // Update nTime every few seconds |
519 | UpdateTime(pblock, pindexPrev); | |
520 | if (Params().AllowMinDifficultyBlocks()) | |
521 | { | |
522 | // Changing pblock->nTime can change work required on testnet: | |
523 | hashTarget.SetCompact(pblock->nBits); | |
524 | } | |
d247a5d1 JG |
525 | } |
526 | } | |
0655fac0 | 527 | } |
27df4123 | 528 | catch (const boost::thread_interrupted&) |
d247a5d1 | 529 | { |
881a85a2 | 530 | LogPrintf("BitcoinMiner terminated\n"); |
d247a5d1 JG |
531 | throw; |
532 | } | |
533 | } | |
534 | ||
c8b74258 | 535 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
d247a5d1 JG |
536 | { |
537 | static boost::thread_group* minerThreads = NULL; | |
538 | ||
d247a5d1 | 539 | if (nThreads < 0) { |
2595b9ac | 540 | // In regtest threads defaults to 1 |
541 | if (Params().DefaultMinerThreads()) | |
542 | nThreads = Params().DefaultMinerThreads(); | |
d247a5d1 JG |
543 | else |
544 | nThreads = boost::thread::hardware_concurrency(); | |
545 | } | |
546 | ||
547 | if (minerThreads != NULL) | |
548 | { | |
549 | minerThreads->interrupt_all(); | |
550 | delete minerThreads; | |
551 | minerThreads = NULL; | |
552 | } | |
553 | ||
554 | if (nThreads == 0 || !fGenerate) | |
555 | return; | |
556 | ||
557 | minerThreads = new boost::thread_group(); | |
558 | for (int i = 0; i < nThreads; i++) | |
559 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
560 | } | |
561 | ||
0655fac0 | 562 | #endif // ENABLE_WALLET |