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