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