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