]>
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 |
c55d5f09 | 102 | #define KOMODO_ELECTION_GAP 2000 |
a3197ff2 | 103 | #define ROUNDROBIN_DELAY 60 |
16c7bf6b | 104 | extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE; |
f24b36ca | 105 | extern char ASSETCHAINS_SYMBOL[16]; |
106 | extern std::string NOTARY_PUBKEY; | |
107 | extern uint8_t NOTARY_PUBKEY33[33]; | |
108 | uint32_t Mining_start,Mining_height; | |
109 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33); | |
110 | int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]); | |
1e81ccb7 | 111 | int32_t komodo_pax_opreturn(uint8_t *opret,int32_t maxsize); |
9cc05f24 | 112 | uint64_t komodo_paxtotal(); |
d63fdb34 | 113 | int32_t komodo_baseid(char *origbase); |
654dfaaf | 114 | int32_t komodo_is_issuer(); |
635dd34d | 115 | int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo); |
48a3cd18 | 116 | int32_t komodo_isrealtime(int32_t *kmdheightp); |
3bc88f14 | 117 | int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); |
7652ed92 | 118 | |
48265f3c | 119 | CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) |
d247a5d1 | 120 | { |
ab918767 | 121 | uint64_t deposits; int32_t isrealtime,kmdheight; const CChainParams& chainparams = Params(); |
d247a5d1 | 122 | // Create new block |
4dddc096 | 123 | unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); |
d247a5d1 | 124 | if(!pblocktemplate.get()) |
1b5b89ba | 125 | { |
126 | fprintf(stderr,"pblocktemplate.get() failure\n"); | |
d247a5d1 | 127 | return NULL; |
1b5b89ba | 128 | } |
d247a5d1 | 129 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience |
4b6162f0 | 130 | if ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT ) |
a5e36fdd | 131 | { |
48a3cd18 | 132 | isrealtime = komodo_isrealtime(&kmdheight); |
3da07d2e | 133 | deposits = komodo_paxtotal(); |
5ba0ce9d | 134 | while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 ) |
ec7ad5f6 | 135 | { |
79562bf3 | 136 | deposits = komodo_paxtotal(); |
16c7bf6b | 137 | if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) ) |
79562bf3 | 138 | { |
bbaa688c | 139 | //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight); |
79562bf3 | 140 | } |
2bec17cb | 141 | else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) ) |
4a21ccd2 | 142 | { |
eb928486 | 143 | fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND); |
79562bf3 | 144 | break; |
4a21ccd2 | 145 | } |
6fd0ae11 | 146 | sleep(10); |
ec7ad5f6 | 147 | } |
f24b36ca | 148 | KOMODO_ON_DEMAND = 0; |
16cd9f2d | 149 | if ( 0 && deposits != 0 ) |
79562bf3 | 150 | 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()); |
a5e36fdd | 151 | } |
dbca89b7 GA |
152 | // -regtest only: allow overriding block.nVersion with |
153 | // -blockversion=N to test forking scenarios | |
154 | if (Params().MineBlocksOnDemand()) | |
155 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); | |
156 | ||
4949004d PW |
157 | // Add dummy coinbase tx as first transaction |
158 | pblock->vtx.push_back(CTransaction()); | |
d247a5d1 JG |
159 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
160 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
161 | ||
162 | // Largest block you're willing to create: | |
ad898b40 | 163 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
164 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
165 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
166 | ||
167 | // How much of the block should be dedicated to high-priority transactions, | |
168 | // included regardless of the fees they pay | |
169 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
170 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
171 | ||
172 | // Minimum block size you want to create; block will be filled with free transactions | |
173 | // until there are no more or the block reaches this size: | |
037b4f14 | 174 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 JG |
175 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
176 | ||
177 | // Collect memory pool transactions into the block | |
a372168e | 178 | CAmount nFees = 0; |
0655fac0 | 179 | |
d247a5d1 JG |
180 | { |
181 | LOCK2(cs_main, mempool.cs); | |
48265f3c | 182 | CBlockIndex* pindexPrev = chainActive.Tip(); |
b867e409 | 183 | const int nHeight = pindexPrev->nHeight + 1; |
75a4d512 | 184 | pblock->nTime = GetAdjustedTime(); |
a1d3c6fb | 185 | const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); |
7c70438d | 186 | CCoinsViewCache view(pcoinsTip); |
0a4ad821 | 187 | uint32_t expired; |
6ff77181 | 188 | |
d247a5d1 JG |
189 | // Priority order to process transactions |
190 | list<COrphan> vOrphan; // list memory doesn't move | |
191 | map<uint256, vector<COrphan*> > mapDependers; | |
192 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
193 | ||
194 | // This vector will be sorted into a priority queue: | |
195 | vector<TxPriority> vecPriority; | |
196 | vecPriority.reserve(mempool.mapTx.size()); | |
4d707d51 GA |
197 | for (map<uint256, CTxMemPoolEntry>::iterator mi = mempool.mapTx.begin(); |
198 | mi != mempool.mapTx.end(); ++mi) | |
d247a5d1 | 199 | { |
4d707d51 | 200 | const CTransaction& tx = mi->second.GetTx(); |
a1d3c6fb MF |
201 | |
202 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) | |
203 | ? nMedianTimePast | |
204 | : pblock->GetBlockTime(); | |
205 | ||
14aa6cc0 | 206 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff)) |
207 | continue; | |
bbaa0f9d | 208 | if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,2) < 0 ) |
6ff77181 | 209 | { |
14aa6cc0 | 210 | fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n"); |
d247a5d1 | 211 | continue; |
14aa6cc0 | 212 | } |
d247a5d1 JG |
213 | COrphan* porphan = NULL; |
214 | double dPriority = 0; | |
a372168e | 215 | CAmount nTotalIn = 0; |
d247a5d1 JG |
216 | bool fMissingInputs = false; |
217 | BOOST_FOREACH(const CTxIn& txin, tx.vin) | |
218 | { | |
219 | // Read prev transaction | |
220 | if (!view.HaveCoins(txin.prevout.hash)) | |
221 | { | |
222 | // This should never happen; all transactions in the memory | |
223 | // pool should connect to either transactions in the chain | |
224 | // or other transactions in the memory pool. | |
225 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
226 | { | |
881a85a2 | 227 | LogPrintf("ERROR: mempool transaction missing input\n"); |
d247a5d1 JG |
228 | if (fDebug) assert("mempool transaction missing input" == 0); |
229 | fMissingInputs = true; | |
230 | if (porphan) | |
231 | vOrphan.pop_back(); | |
232 | break; | |
233 | } | |
234 | ||
235 | // Has to wait for dependencies | |
236 | if (!porphan) | |
237 | { | |
238 | // Use list for automatic deletion | |
239 | vOrphan.push_back(COrphan(&tx)); | |
240 | porphan = &vOrphan.back(); | |
241 | } | |
242 | mapDependers[txin.prevout.hash].push_back(porphan); | |
243 | porphan->setDependsOn.insert(txin.prevout.hash); | |
4d707d51 | 244 | nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue; |
d247a5d1 JG |
245 | continue; |
246 | } | |
629d75fa PW |
247 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
248 | assert(coins); | |
d247a5d1 | 249 | |
a372168e | 250 | CAmount nValueIn = coins->vout[txin.prevout.n].nValue; |
d247a5d1 JG |
251 | nTotalIn += nValueIn; |
252 | ||
b867e409 | 253 | int nConf = nHeight - coins->nHeight; |
d247a5d1 JG |
254 | |
255 | dPriority += (double)nValueIn * nConf; | |
256 | } | |
2b2bc69e SB |
257 | nTotalIn += tx.GetJoinSplitValueIn(); |
258 | ||
d247a5d1 JG |
259 | if (fMissingInputs) continue; |
260 | ||
d6eb2599 | 261 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 262 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 263 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
d247a5d1 | 264 | |
805344dc | 265 | uint256 hash = tx.GetHash(); |
2a72d459 LD |
266 | mempool.ApplyDeltas(hash, dPriority, nTotalIn); |
267 | ||
c6cb21d1 | 268 | CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize); |
d247a5d1 JG |
269 | |
270 | if (porphan) | |
271 | { | |
272 | porphan->dPriority = dPriority; | |
c6cb21d1 | 273 | porphan->feeRate = feeRate; |
d247a5d1 JG |
274 | } |
275 | else | |
c6cb21d1 | 276 | vecPriority.push_back(TxPriority(dPriority, feeRate, &mi->second.GetTx())); |
d247a5d1 JG |
277 | } |
278 | ||
279 | // Collect transactions into block | |
51ed9ec9 BD |
280 | uint64_t nBlockSize = 1000; |
281 | uint64_t nBlockTx = 0; | |
355ca565 | 282 | int64_t interest; |
d247a5d1 JG |
283 | int nBlockSigOps = 100; |
284 | bool fSortedByFee = (nBlockPrioritySize <= 0); | |
285 | ||
286 | TxPriorityCompare comparer(fSortedByFee); | |
287 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
288 | ||
289 | while (!vecPriority.empty()) | |
290 | { | |
291 | // Take highest priority transaction off the priority queue: | |
292 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 293 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 294 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
d247a5d1 JG |
295 | |
296 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
297 | vecPriority.pop_back(); | |
298 | ||
299 | // Size limits | |
300 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
301 | if (nBlockSize + nTxSize >= nBlockMaxSize) | |
302 | continue; | |
303 | ||
304 | // Legacy limits on sigOps: | |
305 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
306 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) | |
307 | continue; | |
308 | ||
309 | // Skip free transactions if we're past the minimum block size: | |
805344dc | 310 | const uint256& hash = tx.GetHash(); |
2a72d459 | 311 | double dPriorityDelta = 0; |
a372168e | 312 | CAmount nFeeDelta = 0; |
2a72d459 | 313 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 314 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
d247a5d1 JG |
315 | continue; |
316 | ||
2a72d459 | 317 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
318 | // transactions: |
319 | if (!fSortedByFee && | |
320 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
321 | { | |
322 | fSortedByFee = true; | |
323 | comparer = TxPriorityCompare(fSortedByFee); | |
324 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
325 | } | |
326 | ||
327 | if (!view.HaveInputs(tx)) | |
328 | continue; | |
329 | ||
17878015 | 330 | CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut(); |
d247a5d1 JG |
331 | |
332 | nTxSigOps += GetP2SHSigOpCount(tx, view); | |
333 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) | |
334 | continue; | |
335 | ||
68f7d1d7 PT |
336 | // Note that flags: we don't want to set mempool/IsStandard() |
337 | // policy here, but we still have to ensure that the block we | |
338 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 339 | CValidationState state; |
c0dde76d | 340 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus())) |
d247a5d1 JG |
341 | continue; |
342 | ||
d7621ccf | 343 | UpdateCoins(tx, state, view, nHeight); |
d247a5d1 JG |
344 | |
345 | // Added | |
346 | pblock->vtx.push_back(tx); | |
347 | pblocktemplate->vTxFees.push_back(nTxFees); | |
348 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
349 | nBlockSize += nTxSize; | |
350 | ++nBlockTx; | |
351 | nBlockSigOps += nTxSigOps; | |
352 | nFees += nTxFees; | |
353 | ||
354 | if (fPrintPriority) | |
355 | { | |
3f0813b3 | 356 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 JG |
357 | } |
358 | ||
359 | // Add transactions that depend on this one to the priority queue | |
360 | if (mapDependers.count(hash)) | |
361 | { | |
362 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
363 | { | |
364 | if (!porphan->setDependsOn.empty()) | |
365 | { | |
366 | porphan->setDependsOn.erase(hash); | |
367 | if (porphan->setDependsOn.empty()) | |
368 | { | |
c6cb21d1 | 369 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
370 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
371 | } | |
372 | } | |
373 | } | |
374 | } | |
375 | } | |
376 | ||
377 | nLastBlockTx = nBlockTx; | |
378 | nLastBlockSize = nBlockSize; | |
f48742c2 | 379 | LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize); |
d247a5d1 | 380 | |
f3ffa3d2 SB |
381 | // Create coinbase tx |
382 | CMutableTransaction txNew; | |
cad0d1ca | 383 | //txNew.nLockTime = (uint32_t)time(NULL) - 60; |
f3ffa3d2 SB |
384 | txNew.vin.resize(1); |
385 | txNew.vin[0].prevout.SetNull(); | |
d581f229 | 386 | txNew.vout.resize(1); |
f3ffa3d2 | 387 | txNew.vout[0].scriptPubKey = scriptPubKeyIn; |
c9b1071d | 388 | txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()); |
f3ffa3d2 SB |
389 | // Add fees |
390 | txNew.vout[0].nValue += nFees; | |
b867e409 | 391 | txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; |
c9b1071d | 392 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
393 | { | |
394 | int32_t i,opretlen; uint8_t opret[256],*ptr; | |
44caf46a | 395 | if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 ) |
c9b1071d | 396 | { |
44caf46a | 397 | if ( (opretlen= komodo_pax_opreturn(opret,sizeof(opret))) > 0 ) // have pricefeed |
d9a9d562 | 398 | { |
399 | txNew.vout.resize(2); | |
400 | txNew.vout[1].scriptPubKey.resize(opretlen); | |
401 | ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data(); | |
402 | for (i=0; i<opretlen; i++) | |
403 | ptr[i] = opret[i]; | |
404 | txNew.vout[1].nValue = 0; | |
405 | //fprintf(stderr,"opretlen.%d\n",opretlen); | |
406 | } | |
d581f229 | 407 | } |
c9b1071d | 408 | } |
654dfaaf | 409 | else if ( komodo_is_issuer() != 0 ) |
c9b1071d | 410 | { |
7322eaa0 | 411 | komodo_gateway_deposits(&txNew,ASSETCHAINS_SYMBOL,0); |
1ecb8541 | 412 | if ( txNew.vout.size() > 1 ) |
4a21ccd2 | 413 | fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); |
c9b1071d | 414 | } |
8f3aa743 | 415 | |
4949004d | 416 | pblock->vtx[0] = txNew; |
d247a5d1 | 417 | pblocktemplate->vTxFees[0] = -nFees; |
8e165d57 JG |
418 | // Randomise nonce |
419 | arith_uint256 nonce = UintToArith256(GetRandHash()); | |
420 | // Clear the top and bottom 16 bits (for local use as thread flags and counters) | |
421 | nonce <<= 32; | |
422 | nonce >>= 16; | |
423 | pblock->nNonce = ArithToUint256(nonce); | |
424 | ||
d247a5d1 JG |
425 | // Fill in header |
426 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
a8d384ae | 427 | pblock->hashReserved = uint256(); |
b366cab9 | 428 | //UpdateTime(pblock, Params().GetConsensus(), pindexPrev); |
4f5e03db | 429 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
fdda3c50 | 430 | pblock->nSolution.clear(); |
d247a5d1 JG |
431 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
432 | ||
c583e2a9 | 433 | CValidationState state; |
0af2786d | 434 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) |
af805d53 | 435 | { |
d0f7ead0 | 436 | static uint32_t counter; |
437 | if ( counter++ < 100 ) | |
d4190a2a | 438 | fprintf(stderr,"warning: testblockvalidity failed\n"); |
14aa6cc0 | 439 | return(0); |
af805d53 | 440 | } |
d247a5d1 JG |
441 | } |
442 | ||
443 | return pblocktemplate.release(); | |
444 | } | |
445 | ||
d247a5d1 JG |
446 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
447 | { | |
448 | // Update nExtraNonce | |
449 | static uint256 hashPrevBlock; | |
450 | if (hashPrevBlock != pblock->hashPrevBlock) | |
451 | { | |
452 | nExtraNonce = 0; | |
453 | hashPrevBlock = pblock->hashPrevBlock; | |
454 | } | |
455 | ++nExtraNonce; | |
456 | unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 | |
4949004d PW |
457 | CMutableTransaction txCoinbase(pblock->vtx[0]); |
458 | txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
459 | assert(txCoinbase.vin[0].scriptSig.size() <= 100); | |
d247a5d1 | 460 | |
4949004d | 461 | pblock->vtx[0] = txCoinbase; |
d247a5d1 JG |
462 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
463 | } | |
464 | ||
4a85e067 | 465 | #ifdef ENABLE_WALLET |
acfa0333 WL |
466 | ////////////////////////////////////////////////////////////////////////////// |
467 | // | |
468 | // Internal miner | |
469 | // | |
c142de7e | 470 | int8_t komodo_minerid(int32_t height,uint8_t *pubkey33); |
acfa0333 | 471 | |
48265f3c | 472 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) |
acfa0333 | 473 | { |
f6c647ed | 474 | CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i; |
7bfc207a | 475 | if ( USE_EXTERNAL_PUBKEY != 0 ) |
998397aa | 476 | { |
7bfc207a | 477 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 478 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 479 | } |
480 | else | |
481 | { | |
482 | if (!reservekey.GetReservedKey(pubkey)) | |
1b5b89ba | 483 | { |
f6c647ed | 484 | return NULL; |
1b5b89ba | 485 | } |
f6c647ed | 486 | scriptPubKey.resize(35); |
f66f65ec | 487 | ptr = (uint8_t *)pubkey.begin(); |
f6c647ed | 488 | script = (uint8_t *)scriptPubKey.data(); |
489 | script[0] = 33; | |
490 | for (i=0; i<33; i++) | |
491 | script[i+1] = ptr[i]; | |
492 | script[34] = OP_CHECKSIG; | |
493 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
494 | } | |
bbaa688c | 495 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
5aab0392 | 496 | { |
497 | for (i=0; i<65; i++) | |
c142de7e | 498 | fprintf(stderr,"%d ",komodo_minerid(chainActive.Tip()->nHeight-i,0)); |
91b99766 | 499 | fprintf(stderr," minerids.special %d from ht.%d\n",komodo_is_special(chainActive.Tip()->nHeight+1,NOTARY_PUBKEY33),chainActive.Tip()->nHeight); |
5aab0392 | 500 | } |
48265f3c | 501 | return CreateNewBlock(scriptPubKey); |
acfa0333 WL |
502 | } |
503 | ||
269d8ba0 | 504 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
d247a5d1 | 505 | { |
81212588 | 506 | LogPrintf("%s\n", pblock->ToString()); |
35915149 | 507 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1); |
d247a5d1 JG |
508 | |
509 | // Found a solution | |
510 | { | |
511 | LOCK(cs_main); | |
4c6d41b8 | 512 | if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash()) |
ba8419c7 | 513 | { |
514 | uint256 hash; int32_t i; | |
515 | hash = pblock->hashPrevBlock; | |
92266e99 | 516 | for (i=31; i>=0; i--) |
ba8419c7 | 517 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 518 | fprintf(stderr," <- prev (stale)\n"); |
ba8419c7 | 519 | hash = chainActive.Tip()->GetBlockHash(); |
92266e99 | 520 | for (i=31; i>=0; i--) |
ba8419c7 | 521 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 522 | fprintf(stderr," <- chainTip (stale)\n"); |
ba8419c7 | 523 | |
2e500f50 | 524 | return error("KomodoMiner: generated block is stale"); |
ba8419c7 | 525 | } |
18e72167 | 526 | } |
d247a5d1 | 527 | |
18e72167 | 528 | // Remove key from key pool |
998397aa | 529 | if ( IS_KOMODO_NOTARY == 0 ) |
530 | reservekey.KeepKey(); | |
d247a5d1 | 531 | |
18e72167 PW |
532 | // Track how many getdata requests this block gets |
533 | { | |
534 | LOCK(wallet.cs_wallet); | |
535 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 JG |
536 | } |
537 | ||
18e72167 PW |
538 | // Process this block the same as if we had received it from another node |
539 | CValidationState state; | |
35915149 | 540 | if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) |
2e500f50 | 541 | return error("KomodoMiner: ProcessNewBlock, block not accepted"); |
18e72167 | 542 | |
d793f94b | 543 | TrackMinedBlock(pblock->GetHash()); |
a6df7ab5 | 544 | |
d247a5d1 JG |
545 | return true; |
546 | } | |
547 | ||
078f6af1 | 548 | int32_t komodo_baseid(char *origbase); |
8c654ec5 | 549 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); |
8ee93080 | 550 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
9152feb5 | 551 | extern int32_t KOMODO_LASTMINED; |
8b51b9e4 | 552 | int32_t roundrobin_delay; |
078f6af1 | 553 | |
d247a5d1 JG |
554 | void static BitcoinMiner(CWallet *pwallet) |
555 | { | |
2e500f50 | 556 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 557 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 558 | RenameThread("komodo-miner"); |
bebe7282 | 559 | const CChainParams& chainparams = Params(); |
d247a5d1 JG |
560 | |
561 | // Each thread has its own key and counter | |
562 | CReserveKey reservekey(pwallet); | |
563 | unsigned int nExtraNonce = 0; | |
564 | ||
e9574728 JG |
565 | unsigned int n = chainparams.EquihashN(); |
566 | unsigned int k = chainparams.EquihashK(); | |
755ead98 | 567 | int32_t notaryid = -1; |
e317db75 | 568 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 && |
755ead98 | 569 | { |
570 | sleep(1); | |
078f6af1 | 571 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
572 | break; | |
755ead98 | 573 | } |
1a8be0dc | 574 | komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33); |
fdda3c50 | 575 | |
755ead98 | 576 | std::string solver; |
e1e65cef | 577 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
755ead98 | 578 | solver = "tromp"; |
e1e65cef | 579 | //else solver = "default"; |
5f0009b2 | 580 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 581 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 582 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 583 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
584 | std::mutex m_cs; |
585 | bool cancelSolver = false; | |
586 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
587 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { | |
588 | std::lock_guard<std::mutex> lock{m_cs}; | |
589 | cancelSolver = true; | |
590 | } | |
591 | ); | |
592 | ||
0655fac0 | 593 | try { |
ad84148d | 594 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 595 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 596 | while (true) |
597 | { | |
2c70b583 | 598 | if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 && |
e725f1cb | 599 | { |
a96fd7b5 | 600 | //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 ) |
601 | // break; | |
0655fac0 PK |
602 | // Busy-wait for the network to come online so we don't waste time mining |
603 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
ad84148d | 604 | //fprintf(stderr,"Wait for peers...\n"); |
bba7c249 GM |
605 | do { |
606 | bool fvNodesEmpty; | |
607 | { | |
608 | LOCK(cs_vNodes); | |
609 | fvNodesEmpty = vNodes.empty(); | |
610 | } | |
269fe243 | 611 | if (!fvNodesEmpty )//&& !IsInitialBlockDownload()) |
bba7c249 | 612 | break; |
f8e367eb | 613 | MilliSleep(5000); |
ad84148d | 614 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
f8e367eb | 615 | |
bba7c249 | 616 | } while (true); |
ad84148d | 617 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
0655fac0 | 618 | } |
f70ced6a | 619 | /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT ) |
8fc7222d | 620 | { |
621 | fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight); | |
622 | sleep(3); | |
d82623d2 | 623 | }*/ |
0655fac0 PK |
624 | // |
625 | // Create new block | |
626 | // | |
627 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
48265f3c | 628 | CBlockIndex* pindexPrev = chainActive.Tip(); |
4940066c | 629 | if ( Mining_height != pindexPrev->nHeight+1 ) |
630 | { | |
631 | Mining_height = pindexPrev->nHeight+1; | |
632 | Mining_start = (uint32_t)time(NULL); | |
633 | } | |
1ecb8541 | 634 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
3a9746d2 | 635 | fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
08d0b73c | 636 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey); |
637 | if ( ptr == 0 ) | |
638 | { | |
d0f7ead0 | 639 | static uint32_t counter; |
640 | if ( counter++ < 100 ) | |
1b5b89ba | 641 | fprintf(stderr,"created illegal block, retry\n"); |
d0f7ead0 | 642 | continue; |
08d0b73c | 643 | } |
644 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
0655fac0 | 645 | if (!pblocktemplate.get()) |
6c37f7fd | 646 | { |
2e500f50 | 647 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
0655fac0 | 648 | return; |
6c37f7fd | 649 | } |
0655fac0 | 650 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 651 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
652 | { | |
83f1c673 | 653 | if ( pblock->vtx.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
16c7bf6b | 654 | { |
83c54f30 | 655 | static uint32_t counter; |
656 | if ( counter++ < 10 ) | |
657 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
16c7bf6b | 658 | sleep(10); |
659 | continue; | |
660 | } else fprintf(stderr,"vouts.%d mining.%d vs %d\n",(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
661 | } | |
0655fac0 | 662 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2e500f50 | 663 | LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
0655fac0 PK |
664 | // |
665 | // Search | |
666 | // | |
8b51b9e4 | 667 | uint8_t pubkeys[66][33]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); |
404391b5 | 668 | savebits = pblock->nBits; |
3505af19 | 669 | arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); |
f0100e72 | 670 | roundrobin_delay = ROUNDROBIN_DELAY; |
52c2553f | 671 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )//komodo_is_special(pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 ) |
5203fc4b | 672 | { |
fda5f849 | 673 | j = 65; |
5a471ba9 | 674 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 ) |
fb6c7505 | 675 | { |
8c654ec5 | 676 | komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight); |
29e60e48 | 677 | if ( nonzpkeys > 0 ) |
678 | { | |
ccb71a6e | 679 | for (i=0; i<33; i++) |
680 | if( pubkeys[0][i] != 0 ) | |
681 | break; | |
682 | if ( i == 33 ) | |
683 | externalflag = 1; | |
684 | else externalflag = 0; | |
49b49585 | 685 | if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) ) |
b176c125 | 686 | { |
345e545e | 687 | for (i=1; i<66; i++) |
688 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
689 | break; | |
ccb71a6e | 690 | if ( externalflag == 0 && i != 66 ) |
345e545e | 691 | printf("VIOLATION at %d\n",i); |
8958c5ba | 692 | for (i=0; i<66; i++) |
32f5c6fb | 693 | { break; |
8958c5ba | 694 | for (j=0; j<33; j++) |
695 | printf("%02x",pubkeys[i][j]); | |
696 | printf(" p%d -> %d\n",i,komodo_minerid(pindexPrev->nHeight-i,pubkeys[i])); | |
8c654ec5 | 697 | } |
2c7ad758 | 698 | for (j=gpucount=0; j<65; j++) |
699 | { | |
49b49585 | 700 | if ( mids[j] >= 0 || notaryid == 34 ) |
8fa91017 | 701 | fprintf(stderr,"%d ",mids[j]); |
702 | else fprintf(stderr,"GPU "); | |
2c7ad758 | 703 | if ( mids[j] == -1 ) |
704 | gpucount++; | |
705 | } | |
b000fa04 | 706 | if ( gpucount > j/2 ) |
f0100e72 | 707 | { |
dd98c02d | 708 | double delta; |
a85440ac | 709 | i = ((Mining_height + notaryid) % 64); |
b000fa04 | 710 | delta = sqrt((double)gpucount - j/2) / 2.; |
dd98c02d | 711 | roundrobin_delay += ((delta * i) / 64) - delta; |
67478d4a | 712 | //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64); |
f0100e72 | 713 | } |
714 | fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay); | |
b176c125 | 715 | } |
29e60e48 | 716 | for (j=0; j<65; j++) |
717 | if ( mids[j] == notaryid ) | |
718 | break; | |
49b49585 | 719 | if ( j == 65 ) |
720 | KOMODO_LASTMINED = 0; | |
965f0f7e | 721 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 722 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 723 | { |
724 | hashTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); | |
725 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1); | |
726 | } //else fprintf(stderr,"duplicate at j.%d\n",j); | |
fb6c7505 | 727 | } else Mining_start = 0; |
d7d27bb3 | 728 | } else Mining_start = 0; |
e725f1cb | 729 | while (true) |
730 | { | |
16c7bf6b | 731 | /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt |
16cd9f2d | 732 | { |
733 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
734 | sleep(10); | |
735 | break; | |
16c7bf6b | 736 | }*/ |
7213c0b1 | 737 | // Hash state |
8c22eb46 | 738 | KOMODO_CHOSEN_ONE = 0; |
7213c0b1 | 739 | crypto_generichash_blake2b_state state; |
e9574728 | 740 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
741 | // I = the block header minus nonce and solution. |
742 | CEquihashInput I{*pblock}; | |
743 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
744 | ss << I; | |
7213c0b1 JG |
745 | // H(I||... |
746 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
747 | // H(I||V||... |
748 | crypto_generichash_blake2b_state curr_state; | |
749 | curr_state = state; | |
7a4c01c9 | 750 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 751 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 752 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
6be3b162 | 753 | //fprintf(stderr,"running solver\n"); |
5be6abbf | 754 | std::function<bool(std::vector<unsigned char>)> validBlock = |
51eb5273 | 755 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
e5430f52 | 756 | (std::vector<unsigned char> soln) |
757 | { | |
51eb5273 JG |
758 | // Write the solution to the hash and compute the result. |
759 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 760 | pblock->nSolution = soln; |
e7d59bbc | 761 | solutionTargetChecks.increment(); |
7a4c01c9 | 762 | if ( UintToArith256(pblock->GetHash()) > hashTarget ) |
e5430f52 | 763 | { |
bd6ef155 | 764 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
7c3b0491 | 765 | // fprintf(stderr," missed target\n"); |
51eb5273 | 766 | return false; |
e5430f52 | 767 | } |
f0100e72 | 768 | if ( ASSETCHAINS_SYMBOL[0] == 0 && Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay ) |
d7d27bb3 | 769 | { |
f0100e72 | 770 | //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL))); |
771 | int32_t nseconds = Mining_start+roundrobin_delay-time(NULL); | |
52e87248 | 772 | if ( nseconds > 0 ) |
773 | sleep(nseconds); | |
320a2e35 | 774 | MilliSleep((rand() % 1700) + 1); |
d7d27bb3 | 775 | } |
b3183e3e | 776 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
777 | // Found a solution |
778 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 779 | LogPrintf("KomodoMiner:\n"); |
a6a0d913 | 780 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); |
5a360a5c | 781 | if (ProcessBlockFound(pblock, *pwallet, reservekey)) { |
a6a0d913 | 782 | // Ignore chain updates caused by us |
783 | std::lock_guard<std::mutex> lock{m_cs}; | |
5a360a5c JG |
784 | cancelSolver = false; |
785 | } | |
8c22eb46 | 786 | KOMODO_CHOSEN_ONE = 0; |
8e165d57 | 787 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
8e165d57 | 788 | // In regression test mode, stop mining after a block is found. |
a6df7ab5 JG |
789 | if (chainparams.MineBlocksOnDemand()) { |
790 | // Increment here because throwing skips the call below | |
791 | ehSolverRuns.increment(); | |
8e165d57 | 792 | throw boost::thread_interrupted(); |
a6df7ab5 | 793 | } |
b78471c2 | 794 | //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 ) |
795 | // sleep(1800); | |
51eb5273 JG |
796 | return true; |
797 | }; | |
798 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
799 | std::lock_guard<std::mutex> lock{m_cs}; | |
800 | return cancelSolver; | |
801 | }; | |
c7aaab7a | 802 | |
5f0009b2 | 803 | // TODO: factor this out into a function with the same API for each solver. |
e1e65cef | 804 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { |
c7aaab7a DH |
805 | // Create solver and initialize it. |
806 | equi eq(1); | |
807 | eq.setstate(&curr_state); | |
808 | ||
809 | // Intialization done, start algo driver. | |
810 | eq.digit0(0); | |
811 | eq.xfull = eq.bfull = eq.hfull = 0; | |
812 | eq.showbsizes(0); | |
813 | for (u32 r = 1; r < WK; r++) { | |
814 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
815 | eq.xfull = eq.bfull = eq.hfull = 0; | |
816 | eq.showbsizes(r); | |
817 | } | |
818 | eq.digitK(0); | |
a6df7ab5 | 819 | ehSolverRuns.increment(); |
c7aaab7a DH |
820 | |
821 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
822 | for (size_t s = 0; s < eq.nsols; s++) { | |
823 | LogPrint("pow", "Checking solution %d\n", s+1); | |
824 | std::vector<eh_index> index_vector(PROOFSIZE); | |
825 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
826 | index_vector[i] = eq.sols[s][i]; | |
827 | } | |
828 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
829 | ||
830 | if (validBlock(sol_char)) { | |
831 | // If we find a POW solution, do not try other solutions | |
832 | // because they become invalid as we created a new block in blockchain. | |
833 | break; | |
834 | } | |
835 | } | |
836 | } else { | |
837 | try { | |
838 | // If we find a valid block, we rebuild | |
a6df7ab5 JG |
839 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); |
840 | ehSolverRuns.increment(); | |
841 | if (found) { | |
a8aa4375 | 842 | int32_t i; uint256 hash = pblock->GetHash(); |
843 | for (i=0; i<32; i++) | |
844 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
845 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
b78471c2 | 846 | FOUND_BLOCK = 1; |
8ee93080 | 847 | KOMODO_MAYBEMINED = Mining_height; |
c7aaab7a | 848 | break; |
a6df7ab5 | 849 | } |
c7aaab7a DH |
850 | } catch (EhSolverCancelledException&) { |
851 | LogPrint("pow", "Equihash solver cancelled\n"); | |
852 | std::lock_guard<std::mutex> lock{m_cs}; | |
853 | cancelSolver = false; | |
854 | } | |
48265f3c | 855 | } |
d247a5d1 | 856 | |
0655fac0 PK |
857 | // Check for stop or if block needs to be rebuilt |
858 | boost::this_thread::interruption_point(); | |
859 | // Regtest mode doesn't require peers | |
b78471c2 | 860 | if ( FOUND_BLOCK != 0 ) |
861 | { | |
862 | FOUND_BLOCK = 0; | |
863 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
9152feb5 | 864 | //sleep(2000); |
b78471c2 | 865 | } |
bebe7282 | 866 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
e5430f52 | 867 | { |
f70ced6a | 868 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) |
10694486 | 869 | { |
bd6ef155 | 870 | fprintf(stderr,"no nodes, break\n"); |
d90cef0b | 871 | break; |
10694486 | 872 | } |
e5430f52 | 873 | } |
8e165d57 | 874 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
e5430f52 | 875 | { |
198286a5 | 876 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
10694486 | 877 | fprintf(stderr,"0xffff, break\n"); |
0655fac0 | 878 | break; |
e5430f52 | 879 | } |
0655fac0 | 880 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
e5430f52 | 881 | { |
6be3b162 | 882 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
10694486 | 883 | fprintf(stderr,"timeout, break\n"); |
0655fac0 | 884 | break; |
e5430f52 | 885 | } |
886 | if ( pindexPrev != chainActive.Tip() ) | |
887 | { | |
6be3b162 | 888 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
10694486 | 889 | fprintf(stderr,"Tip advanced, break\n"); |
0655fac0 | 890 | break; |
e5430f52 | 891 | } |
8e165d57 JG |
892 | // Update nNonce and nTime |
893 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
404391b5 | 894 | pblock->nBits = savebits; |
0af2786d | 895 | //UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); |
bebe7282 | 896 | if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) |
48265f3c WL |
897 | { |
898 | // Changing pblock->nTime can change work required on testnet: | |
899 | hashTarget.SetCompact(pblock->nBits); | |
900 | } | |
0af2786d | 901 | /*CValidationState tmpstate; |
c583e2a9 | 902 | if ( !TestBlockValidity(tmpstate, *pblock, pindexPrev, false, false)) |
14aa6cc0 | 903 | { |
904 | fprintf(stderr,"formerly valid mining block became invalid, likely due to tx expiration\n"); | |
905 | break; | |
0af2786d | 906 | }*/ |
d247a5d1 JG |
907 | } |
908 | } | |
0655fac0 | 909 | } |
27df4123 | 910 | catch (const boost::thread_interrupted&) |
d247a5d1 | 911 | { |
5e9b555f | 912 | c.disconnect(); |
2e500f50 | 913 | LogPrintf("KomodoMiner terminated\n"); |
d247a5d1 JG |
914 | throw; |
915 | } | |
bba7c249 GM |
916 | catch (const std::runtime_error &e) |
917 | { | |
5e9b555f | 918 | c.disconnect(); |
2e500f50 | 919 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); |
bba7c249 GM |
920 | return; |
921 | } | |
5a360a5c | 922 | c.disconnect(); |
d247a5d1 JG |
923 | } |
924 | ||
c8b74258 | 925 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
d247a5d1 JG |
926 | { |
927 | static boost::thread_group* minerThreads = NULL; | |
928 | ||
d247a5d1 | 929 | if (nThreads < 0) { |
2595b9ac | 930 | // In regtest threads defaults to 1 |
931 | if (Params().DefaultMinerThreads()) | |
932 | nThreads = Params().DefaultMinerThreads(); | |
d247a5d1 JG |
933 | else |
934 | nThreads = boost::thread::hardware_concurrency(); | |
935 | } | |
936 | ||
937 | if (minerThreads != NULL) | |
938 | { | |
939 | minerThreads->interrupt_all(); | |
940 | delete minerThreads; | |
941 | minerThreads = NULL; | |
942 | } | |
943 | ||
944 | if (nThreads == 0 || !fGenerate) | |
945 | return; | |
946 | ||
947 | minerThreads = new boost::thread_group(); | |
948 | for (int i = 0; i < nThreads; i++) | |
949 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
950 | } | |
951 | ||
0655fac0 | 952 | #endif // ENABLE_WALLET |