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