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