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()); | |
f3ffa3d2 SB |
337 | // Add fees |
338 | txNew.vout[0].nValue += nFees; | |
b867e409 | 339 | txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; |
f3ffa3d2 | 340 | |
4949004d | 341 | pblock->vtx[0] = txNew; |
d247a5d1 JG |
342 | pblocktemplate->vTxFees[0] = -nFees; |
343 | ||
8e165d57 JG |
344 | // Randomise nonce |
345 | arith_uint256 nonce = UintToArith256(GetRandHash()); | |
346 | // Clear the top and bottom 16 bits (for local use as thread flags and counters) | |
347 | nonce <<= 32; | |
348 | nonce >>= 16; | |
349 | pblock->nNonce = ArithToUint256(nonce); | |
350 | ||
d247a5d1 JG |
351 | // Fill in header |
352 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
a8d384ae | 353 | pblock->hashReserved = uint256(); |
bebe7282 | 354 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); |
4f5e03db | 355 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
fdda3c50 | 356 | pblock->nSolution.clear(); |
d247a5d1 JG |
357 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
358 | ||
d247a5d1 | 359 | CValidationState state; |
34ad681a | 360 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) |
af805d53 | 361 | { |
362 | fprintf(stderr,"testblockvalidity failed\n"); | |
34ad681a | 363 | //throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
af805d53 | 364 | } |
d247a5d1 JG |
365 | } |
366 | ||
367 | return pblocktemplate.release(); | |
368 | } | |
369 | ||
d247a5d1 JG |
370 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
371 | { | |
372 | // Update nExtraNonce | |
373 | static uint256 hashPrevBlock; | |
374 | if (hashPrevBlock != pblock->hashPrevBlock) | |
375 | { | |
376 | nExtraNonce = 0; | |
377 | hashPrevBlock = pblock->hashPrevBlock; | |
378 | } | |
379 | ++nExtraNonce; | |
380 | unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 | |
4949004d PW |
381 | CMutableTransaction txCoinbase(pblock->vtx[0]); |
382 | txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
383 | assert(txCoinbase.vin[0].scriptSig.size() <= 100); | |
d247a5d1 | 384 | |
4949004d | 385 | pblock->vtx[0] = txCoinbase; |
d247a5d1 JG |
386 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
387 | } | |
388 | ||
4a85e067 | 389 | #ifdef ENABLE_WALLET |
acfa0333 WL |
390 | ////////////////////////////////////////////////////////////////////////////// |
391 | // | |
392 | // Internal miner | |
393 | // | |
a2a3945e | 394 | extern int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY; |
998397aa | 395 | extern std::string NOTARY_PUBKEY; |
acfa0333 | 396 | |
48265f3c | 397 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) |
acfa0333 | 398 | { |
c95fd5e0 | 399 | CPubKey pubkey; CScript scriptPubKey; |
fa9f2271 | 400 | if (!reservekey.GetReservedKey(pubkey)) |
401 | return NULL; | |
402 | scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
7bfc207a | 403 | if ( USE_EXTERNAL_PUBKEY != 0 ) |
998397aa | 404 | { |
7bfc207a | 405 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 406 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
998397aa | 407 | } |
48265f3c | 408 | return CreateNewBlock(scriptPubKey); |
acfa0333 WL |
409 | } |
410 | ||
269d8ba0 | 411 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
d247a5d1 | 412 | { |
81212588 | 413 | LogPrintf("%s\n", pblock->ToString()); |
7d9d134b | 414 | LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue)); |
d247a5d1 JG |
415 | |
416 | // Found a solution | |
417 | { | |
418 | LOCK(cs_main); | |
4c6d41b8 | 419 | if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash()) |
fdda3c50 | 420 | return error("ZcashMiner: generated block is stale"); |
18e72167 | 421 | } |
d247a5d1 | 422 | |
18e72167 | 423 | // Remove key from key pool |
998397aa | 424 | if ( IS_KOMODO_NOTARY == 0 ) |
425 | reservekey.KeepKey(); | |
d247a5d1 | 426 | |
18e72167 PW |
427 | // Track how many getdata requests this block gets |
428 | { | |
429 | LOCK(wallet.cs_wallet); | |
430 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 JG |
431 | } |
432 | ||
18e72167 PW |
433 | // Process this block the same as if we had received it from another node |
434 | CValidationState state; | |
304892fc | 435 | if (!ProcessNewBlock(state, NULL, pblock, true, NULL)) |
fdda3c50 | 436 | return error("ZcashMiner: ProcessNewBlock, block not accepted"); |
18e72167 | 437 | |
d247a5d1 JG |
438 | return true; |
439 | } | |
440 | ||
62b70c88 | 441 | extern uint8_t NOTARY_PUBKEY33[33]; |
442 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33); | |
443 | ||
d247a5d1 JG |
444 | void static BitcoinMiner(CWallet *pwallet) |
445 | { | |
fdda3c50 | 446 | LogPrintf("ZcashMiner started\n"); |
d247a5d1 | 447 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
fdda3c50 | 448 | RenameThread("zcash-miner"); |
bebe7282 | 449 | const CChainParams& chainparams = Params(); |
d247a5d1 JG |
450 | |
451 | // Each thread has its own key and counter | |
452 | CReserveKey reservekey(pwallet); | |
453 | unsigned int nExtraNonce = 0; | |
454 | ||
e9574728 JG |
455 | unsigned int n = chainparams.EquihashN(); |
456 | unsigned int k = chainparams.EquihashK(); | |
fdda3c50 | 457 | |
5a360a5c JG |
458 | std::mutex m_cs; |
459 | bool cancelSolver = false; | |
460 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
461 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { | |
462 | std::lock_guard<std::mutex> lock{m_cs}; | |
463 | cancelSolver = true; | |
464 | } | |
465 | ); | |
466 | ||
0655fac0 | 467 | try { |
e725f1cb | 468 | while (true) |
469 | { | |
470 | if (chainparams.MiningRequiresPeers()) | |
471 | { | |
0655fac0 PK |
472 | // Busy-wait for the network to come online so we don't waste time mining |
473 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
e725f1cb | 474 | fprintf(stderr,"Wait for peers...\n"); |
bba7c249 GM |
475 | do { |
476 | bool fvNodesEmpty; | |
477 | { | |
478 | LOCK(cs_vNodes); | |
479 | fvNodesEmpty = vNodes.empty(); | |
480 | } | |
481 | if (!fvNodesEmpty && !IsInitialBlockDownload()) | |
482 | break; | |
0655fac0 | 483 | MilliSleep(1000); |
bba7c249 | 484 | } while (true); |
e725f1cb | 485 | fprintf(stderr,"Found peers\n"); |
0655fac0 | 486 | } |
7bfc207a | 487 | //fprintf(stderr,"create new block\n"); |
0655fac0 PK |
488 | // |
489 | // Create new block | |
490 | // | |
491 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
48265f3c | 492 | CBlockIndex* pindexPrev = chainActive.Tip(); |
0655fac0 | 493 | |
4dddc096 | 494 | unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey)); |
0655fac0 | 495 | if (!pblocktemplate.get()) |
6c37f7fd | 496 | { |
fdda3c50 | 497 | LogPrintf("Error in ZcashMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
0655fac0 | 498 | return; |
6c37f7fd | 499 | } |
0655fac0 PK |
500 | CBlock *pblock = &pblocktemplate->block; |
501 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); | |
502 | ||
fdda3c50 | 503 | LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(), |
0655fac0 PK |
504 | ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); |
505 | ||
506 | // | |
507 | // Search | |
508 | // | |
695216ac | 509 | int32_t notaryid; |
0655fac0 | 510 | int64_t nStart = GetTime(); |
fdafadd0 | 511 | if ( komodo_chosennotary(¬aryid,pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 ) |
5203fc4b | 512 | { |
fdafadd0 | 513 | fprintf(stderr,"I am the chosen one for ht.%d\n",pindexPrev->nHeight+1); |
5203fc4b | 514 | } |
48265f3c | 515 | arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); |
fdda3c50 | 516 | |
e725f1cb | 517 | while (true) |
518 | { | |
7213c0b1 JG |
519 | // Hash state |
520 | crypto_generichash_blake2b_state state; | |
e9574728 | 521 | EhInitialiseState(n, k, state); |
fdda3c50 | 522 | |
7213c0b1 JG |
523 | // I = the block header minus nonce and solution. |
524 | CEquihashInput I{*pblock}; | |
525 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
526 | ss << I; | |
fdda3c50 | 527 | |
7213c0b1 JG |
528 | // H(I||... |
529 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
fdda3c50 | 530 | |
8e165d57 JG |
531 | // H(I||V||... |
532 | crypto_generichash_blake2b_state curr_state; | |
533 | curr_state = state; | |
534 | crypto_generichash_blake2b_update(&curr_state, | |
535 | pblock->nNonce.begin(), | |
536 | pblock->nNonce.size()); | |
537 | ||
538 | // (x_1, x_2, ...) = A(I, V, n, k) | |
539 | LogPrint("pow", "Running Equihash solver with nNonce = %s\n", | |
540 | pblock->nNonce.ToString()); | |
8e165d57 | 541 | |
5be6abbf | 542 | std::function<bool(std::vector<unsigned char>)> validBlock = |
51eb5273 | 543 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
5be6abbf | 544 | (std::vector<unsigned char> soln) { |
51eb5273 JG |
545 | // Write the solution to the hash and compute the result. |
546 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 JG |
547 | pblock->nSolution = soln; |
548 | ||
549 | if (UintToArith256(pblock->GetHash()) > hashTarget) { | |
51eb5273 | 550 | return false; |
8e165d57 | 551 | } |
48265f3c | 552 | |
8e165d57 JG |
553 | // Found a solution |
554 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
555 | LogPrintf("ZcashMiner:\n"); | |
556 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
5a360a5c JG |
557 | if (ProcessBlockFound(pblock, *pwallet, reservekey)) { |
558 | // Ignore chain updates caused by us | |
559 | std::lock_guard<std::mutex> lock{m_cs}; | |
560 | cancelSolver = false; | |
561 | } | |
8e165d57 | 562 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
48265f3c | 563 | |
8e165d57 JG |
564 | // In regression test mode, stop mining after a block is found. |
565 | if (chainparams.MineBlocksOnDemand()) | |
566 | throw boost::thread_interrupted(); | |
48265f3c | 567 | |
51eb5273 JG |
568 | return true; |
569 | }; | |
570 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
571 | std::lock_guard<std::mutex> lock{m_cs}; | |
572 | return cancelSolver; | |
573 | }; | |
574 | try { | |
575 | // If we find a valid block, we rebuild | |
576 | if (EhOptimisedSolve(n, k, curr_state, validBlock, cancelled)) | |
577 | break; | |
578 | } catch (EhSolverCancelledException&) { | |
579 | LogPrint("pow", "Equihash solver cancelled\n"); | |
580 | std::lock_guard<std::mutex> lock{m_cs}; | |
581 | cancelSolver = false; | |
48265f3c | 582 | } |
d247a5d1 | 583 | |
0655fac0 PK |
584 | // Check for stop or if block needs to be rebuilt |
585 | boost::this_thread::interruption_point(); | |
586 | // Regtest mode doesn't require peers | |
bebe7282 | 587 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
0655fac0 | 588 | break; |
8e165d57 | 589 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
0655fac0 PK |
590 | break; |
591 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
592 | break; | |
593 | if (pindexPrev != chainActive.Tip()) | |
594 | break; | |
595 | ||
8e165d57 JG |
596 | // Update nNonce and nTime |
597 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
bebe7282 JT |
598 | UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); |
599 | if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) | |
48265f3c WL |
600 | { |
601 | // Changing pblock->nTime can change work required on testnet: | |
602 | hashTarget.SetCompact(pblock->nBits); | |
603 | } | |
d247a5d1 JG |
604 | } |
605 | } | |
0655fac0 | 606 | } |
27df4123 | 607 | catch (const boost::thread_interrupted&) |
d247a5d1 | 608 | { |
fdda3c50 | 609 | LogPrintf("ZcashMiner terminated\n"); |
d247a5d1 JG |
610 | throw; |
611 | } | |
bba7c249 GM |
612 | catch (const std::runtime_error &e) |
613 | { | |
fdda3c50 | 614 | LogPrintf("ZcashMiner runtime error: %s\n", e.what()); |
bba7c249 GM |
615 | return; |
616 | } | |
5a360a5c | 617 | c.disconnect(); |
d247a5d1 JG |
618 | } |
619 | ||
c8b74258 | 620 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
d247a5d1 JG |
621 | { |
622 | static boost::thread_group* minerThreads = NULL; | |
623 | ||
d247a5d1 | 624 | if (nThreads < 0) { |
2595b9ac | 625 | // In regtest threads defaults to 1 |
626 | if (Params().DefaultMinerThreads()) | |
627 | nThreads = Params().DefaultMinerThreads(); | |
d247a5d1 JG |
628 | else |
629 | nThreads = boost::thread::hardware_concurrency(); | |
630 | } | |
631 | ||
632 | if (minerThreads != NULL) | |
633 | { | |
634 | minerThreads->interrupt_all(); | |
635 | delete minerThreads; | |
636 | minerThreads = NULL; | |
637 | } | |
638 | ||
639 | if (nThreads == 0 || !fGenerate) | |
640 | return; | |
641 | ||
642 | minerThreads = new boost::thread_group(); | |
643 | for (int i = 0; i < nThreads; i++) | |
644 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
645 | } | |
646 | ||
0655fac0 | 647 | #endif // ENABLE_WALLET |