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