]>
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" |
20c3ac51 | 14 | #include "importcoin.h" |
691161d4 | 15 | #include "consensus/consensus.h" |
be126699 | 16 | #include "consensus/upgrades.h" |
da29ecbc | 17 | #include "consensus/validation.h" |
8e8b6d70 JG |
18 | #ifdef ENABLE_MINING |
19 | #include "crypto/equihash.h" | |
42181656 | 20 | #include "crypto/verus_hash.h" |
8e8b6d70 | 21 | #endif |
85aab2a0 | 22 | #include "hash.h" |
42181656 | 23 | |
d247a5d1 | 24 | #include "main.h" |
a6df7ab5 | 25 | #include "metrics.h" |
51ed9ec9 | 26 | #include "net.h" |
df852d2b | 27 | #include "pow.h" |
bebe7282 | 28 | #include "primitives/transaction.h" |
8e165d57 | 29 | #include "random.h" |
22c4272b | 30 | #include "timedata.h" |
8e8b6d70 | 31 | #include "ui_interface.h" |
ad49c256 WL |
32 | #include "util.h" |
33 | #include "utilmoneystr.h" | |
df840de5 | 34 | #ifdef ENABLE_WALLET |
50c72f23 | 35 | #include "wallet/wallet.h" |
df840de5 | 36 | #endif |
09eb201b | 37 | |
fdda3c50 JG |
38 | #include "sodium.h" |
39 | ||
ad49c256 | 40 | #include <boost/thread.hpp> |
a3c26c2e | 41 | #include <boost/tuple/tuple.hpp> |
8e8b6d70 JG |
42 | #ifdef ENABLE_MINING |
43 | #include <functional> | |
44 | #endif | |
5a360a5c | 45 | #include <mutex> |
ad49c256 | 46 | |
09eb201b | 47 | using namespace std; |
7b4737c8 | 48 | |
d247a5d1 JG |
49 | ////////////////////////////////////////////////////////////////////////////// |
50 | // | |
51 | // BitcoinMiner | |
52 | // | |
53 | ||
c6cb21d1 GA |
54 | // |
55 | // Unconfirmed transactions in the memory pool often depend on other | |
56 | // transactions in the memory pool. When we select transactions from the | |
57 | // pool, we select by highest priority or fee rate, so we might consider | |
58 | // transactions that depend on transactions that aren't yet in the block. | |
59 | // The COrphan class keeps track of these 'temporary orphans' while | |
60 | // CreateBlock is figuring out which transactions to include. | |
61 | // | |
d247a5d1 JG |
62 | class COrphan |
63 | { | |
64 | public: | |
4d707d51 | 65 | const CTransaction* ptx; |
d247a5d1 | 66 | set<uint256> setDependsOn; |
c6cb21d1 | 67 | CFeeRate feeRate; |
02bec4b2 | 68 | double dPriority; |
e9e70b95 | 69 | |
c6cb21d1 | 70 | COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) |
d247a5d1 | 71 | { |
d247a5d1 | 72 | } |
d247a5d1 JG |
73 | }; |
74 | ||
51ed9ec9 BD |
75 | uint64_t nLastBlockTx = 0; |
76 | uint64_t nLastBlockSize = 0; | |
d247a5d1 | 77 | |
c6cb21d1 GA |
78 | // We want to sort transactions by priority and fee rate, so: |
79 | typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority; | |
d247a5d1 JG |
80 | class TxPriorityCompare |
81 | { | |
82 | bool byFee; | |
e9e70b95 | 83 | |
d247a5d1 JG |
84 | public: |
85 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
e9e70b95 | 86 | |
d247a5d1 JG |
87 | bool operator()(const TxPriority& a, const TxPriority& b) |
88 | { | |
89 | if (byFee) | |
90 | { | |
91 | if (a.get<1>() == b.get<1>()) | |
92 | return a.get<0>() < b.get<0>(); | |
93 | return a.get<1>() < b.get<1>(); | |
94 | } | |
95 | else | |
96 | { | |
97 | if (a.get<0>() == b.get<0>()) | |
98 | return a.get<1>() < b.get<1>(); | |
99 | return a.get<0>() < b.get<0>(); | |
100 | } | |
101 | } | |
102 | }; | |
103 | ||
bebe7282 | 104 | void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
22c4272b | 105 | { |
4972b74b | 106 | pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); |
22c4272b | 107 | } |
108 | ||
5416af1d | 109 | #include "komodo_defs.h" |
110 | ||
69767347 | 111 | extern CCriticalSection cs_metrics; |
6e78d3df | 112 | extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE; |
48d800c2 | 113 | extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED; |
42181656 | 114 | extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[]; |
115 | extern const char *ASSETCHAINS_ALGORITHMS[]; | |
5296a850 | 116 | extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[]; |
7c130297 | 117 | extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; |
d9f176ac | 118 | extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY; |
292809f7 | 119 | void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len); |
d9f176ac | 120 | |
94a465a6 | 121 | extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; |
f24b36ca | 122 | uint32_t Mining_start,Mining_height; |
28a62b60 | 123 | int32_t My_notaryid = -1; |
8683bd8d | 124 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); |
b4810651 | 125 | int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); |
d63fdb34 | 126 | int32_t komodo_baseid(char *origbase); |
3bc88f14 | 127 | int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); |
29bd53a1 | 128 | int64_t komodo_block_unlocktime(uint32_t nHeight); |
18443f69 | 129 | uint64_t komodo_commission(const CBlock *block); |
d231a6a7 | 130 | 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); |
5034d1c1 | 131 | int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig); |
496f1fd2 | 132 | int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33); |
7652ed92 | 133 | |
5034d1c1 | 134 | CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake) |
d247a5d1 | 135 | { |
8626f666 | 136 | CScript scriptPubKeyIn(_scriptPubKeyIn); |
9339a0cb | 137 | uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params(); |
2a6a442a | 138 | //fprintf(stderr,"create new block\n"); |
17929553 | 139 | // Create new block |
16593898 | 140 | if ( gpucount < 0 ) |
141 | gpucount = KOMODO_MAXGPUCOUNT; | |
08c58194 | 142 | std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); |
d247a5d1 | 143 | if(!pblocktemplate.get()) |
1b5b89ba | 144 | { |
145 | fprintf(stderr,"pblocktemplate.get() failure\n"); | |
d247a5d1 | 146 | return NULL; |
1b5b89ba | 147 | } |
d247a5d1 | 148 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience |
97a337f7 | 149 | // -regtest only: allow overriding block.nVersion with |
dbca89b7 GA |
150 | // -blockversion=N to test forking scenarios |
151 | if (Params().MineBlocksOnDemand()) | |
152 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); | |
e9e70b95 | 153 | |
4949004d PW |
154 | // Add dummy coinbase tx as first transaction |
155 | pblock->vtx.push_back(CTransaction()); | |
d247a5d1 JG |
156 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
157 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
e9e70b95 | 158 | |
d247a5d1 | 159 | // Largest block you're willing to create: |
ad898b40 | 160 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
161 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
162 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
e9e70b95 | 163 | |
d247a5d1 JG |
164 | // How much of the block should be dedicated to high-priority transactions, |
165 | // included regardless of the fees they pay | |
166 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
167 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
e9e70b95 | 168 | |
d247a5d1 JG |
169 | // Minimum block size you want to create; block will be filled with free transactions |
170 | // until there are no more or the block reaches this size: | |
037b4f14 | 171 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 | 172 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
e9e70b95 | 173 | |
d247a5d1 | 174 | // Collect memory pool transactions into the block |
a372168e | 175 | CAmount nFees = 0; |
562852ab | 176 | CBlockIndex* pindexPrev = 0; |
d247a5d1 JG |
177 | { |
178 | LOCK2(cs_main, mempool.cs); | |
562852ab | 179 | pindexPrev = chainActive.LastTip(); |
b867e409 | 180 | const int nHeight = pindexPrev->nHeight + 1; |
be126699 | 181 | uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus()); |
a0dd01bc | 182 | |
a1d3c6fb | 183 | const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); |
a0dd01bc | 184 | uint32_t proposedTime = GetAdjustedTime(); |
185 | if (proposedTime == nMedianTimePast) | |
186 | { | |
187 | // too fast or stuck, this addresses the too fast issue, while moving | |
188 | // forward as quickly as possible | |
189 | for (int i; i < 100; i++) | |
190 | { | |
191 | proposedTime = GetAdjustedTime(); | |
192 | if (proposedTime == nMedianTimePast) | |
193 | MilliSleep(10); | |
194 | } | |
195 | } | |
196 | pblock->nTime = GetAdjustedTime(); | |
197 | ||
7c70438d | 198 | CCoinsViewCache view(pcoinsTip); |
f9155fec | 199 | uint32_t expired; uint64_t commission; |
6ff77181 | 200 | |
d247a5d1 JG |
201 | // Priority order to process transactions |
202 | list<COrphan> vOrphan; // list memory doesn't move | |
203 | map<uint256, vector<COrphan*> > mapDependers; | |
204 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
e9e70b95 | 205 | |
d247a5d1 JG |
206 | // This vector will be sorted into a priority queue: |
207 | vector<TxPriority> vecPriority; | |
208 | vecPriority.reserve(mempool.mapTx.size()); | |
e328fa32 | 209 | for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); |
4d707d51 | 210 | mi != mempool.mapTx.end(); ++mi) |
d247a5d1 | 211 | { |
e328fa32 | 212 | const CTransaction& tx = mi->GetTx(); |
e9e70b95 | 213 | |
a1d3c6fb | 214 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) |
e9e70b95 | 215 | ? nMedianTimePast |
216 | : pblock->GetBlockTime(); | |
217 | ||
9bb37bf0 | 218 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) |
61f8caf2 | 219 | { |
51376f3c | 220 | //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight)); |
14aa6cc0 | 221 | continue; |
61f8caf2 | 222 | } |
161f617d | 223 | if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) |
6ff77181 | 224 | { |
64b45b71 | 225 | //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime); |
d247a5d1 | 226 | continue; |
14aa6cc0 | 227 | } |
d247a5d1 JG |
228 | COrphan* porphan = NULL; |
229 | double dPriority = 0; | |
a372168e | 230 | CAmount nTotalIn = 0; |
d247a5d1 | 231 | bool fMissingInputs = false; |
0cb91a8d | 232 | if (tx.IsCoinImport()) |
d247a5d1 | 233 | { |
0cb91a8d SS |
234 | CAmount nValueIn = GetCoinImportValue(tx); |
235 | nTotalIn += nValueIn; | |
236 | dPriority += (double)nValueIn * 1000; // flat multiplier | |
237 | } else { | |
238 | BOOST_FOREACH(const CTxIn& txin, tx.vin) | |
d247a5d1 | 239 | { |
0cb91a8d SS |
240 | // Read prev transaction |
241 | if (!view.HaveCoins(txin.prevout.hash)) | |
d247a5d1 | 242 | { |
0cb91a8d SS |
243 | // This should never happen; all transactions in the memory |
244 | // pool should connect to either transactions in the chain | |
245 | // or other transactions in the memory pool. | |
246 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
247 | { | |
248 | LogPrintf("ERROR: mempool transaction missing input\n"); | |
249 | if (fDebug) assert("mempool transaction missing input" == 0); | |
250 | fMissingInputs = true; | |
251 | if (porphan) | |
252 | vOrphan.pop_back(); | |
253 | break; | |
254 | } | |
255 | ||
256 | // Has to wait for dependencies | |
257 | if (!porphan) | |
258 | { | |
259 | // Use list for automatic deletion | |
260 | vOrphan.push_back(COrphan(&tx)); | |
261 | porphan = &vOrphan.back(); | |
262 | } | |
263 | mapDependers[txin.prevout.hash].push_back(porphan); | |
264 | porphan->setDependsOn.insert(txin.prevout.hash); | |
265 | nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue; | |
266 | continue; | |
d247a5d1 | 267 | } |
0cb91a8d SS |
268 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
269 | assert(coins); | |
270 | ||
271 | CAmount nValueIn = coins->vout[txin.prevout.n].nValue; | |
272 | nTotalIn += nValueIn; | |
273 | ||
274 | int nConf = nHeight - coins->nHeight; | |
275 | ||
276 | dPriority += (double)nValueIn * nConf; | |
d247a5d1 | 277 | } |
0cb91a8d | 278 | nTotalIn += tx.GetJoinSplitValueIn(); |
d247a5d1 | 279 | } |
0cb91a8d | 280 | |
d247a5d1 | 281 | if (fMissingInputs) continue; |
e9e70b95 | 282 | |
d6eb2599 | 283 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 284 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 285 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
e9e70b95 | 286 | |
805344dc | 287 | uint256 hash = tx.GetHash(); |
2a72d459 | 288 | mempool.ApplyDeltas(hash, dPriority, nTotalIn); |
e9e70b95 | 289 | |
c6cb21d1 | 290 | CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize); |
e9e70b95 | 291 | |
d247a5d1 JG |
292 | if (porphan) |
293 | { | |
294 | porphan->dPriority = dPriority; | |
c6cb21d1 | 295 | porphan->feeRate = feeRate; |
d247a5d1 JG |
296 | } |
297 | else | |
e328fa32 | 298 | vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); |
d247a5d1 | 299 | } |
e9e70b95 | 300 | |
d247a5d1 | 301 | // Collect transactions into block |
51ed9ec9 BD |
302 | uint64_t nBlockSize = 1000; |
303 | uint64_t nBlockTx = 0; | |
355ca565 | 304 | int64_t interest; |
d247a5d1 JG |
305 | int nBlockSigOps = 100; |
306 | bool fSortedByFee = (nBlockPrioritySize <= 0); | |
e9e70b95 | 307 | |
d247a5d1 JG |
308 | TxPriorityCompare comparer(fSortedByFee); |
309 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
e9e70b95 | 310 | |
d247a5d1 JG |
311 | while (!vecPriority.empty()) |
312 | { | |
313 | // Take highest priority transaction off the priority queue: | |
314 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 315 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 316 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
e9e70b95 | 317 | |
d247a5d1 JG |
318 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); |
319 | vecPriority.pop_back(); | |
e9e70b95 | 320 | |
d247a5d1 JG |
321 | // Size limits |
322 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
01fda4c1 | 323 | if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx |
61f8caf2 | 324 | { |
51376f3c | 325 | //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize); |
d247a5d1 | 326 | continue; |
61f8caf2 | 327 | } |
e9e70b95 | 328 | |
d247a5d1 JG |
329 | // Legacy limits on sigOps: |
330 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
a4a40a38 | 331 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 332 | { |
51376f3c | 333 | //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
d247a5d1 | 334 | continue; |
61f8caf2 | 335 | } |
d247a5d1 | 336 | // Skip free transactions if we're past the minimum block size: |
805344dc | 337 | const uint256& hash = tx.GetHash(); |
2a72d459 | 338 | double dPriorityDelta = 0; |
a372168e | 339 | CAmount nFeeDelta = 0; |
2a72d459 | 340 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 341 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
61f8caf2 | 342 | { |
51376f3c | 343 | //fprintf(stderr,"fee rate skip\n"); |
d247a5d1 | 344 | continue; |
61f8caf2 | 345 | } |
2a72d459 | 346 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
347 | // transactions: |
348 | if (!fSortedByFee && | |
349 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
350 | { | |
351 | fSortedByFee = true; | |
352 | comparer = TxPriorityCompare(fSortedByFee); | |
353 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
354 | } | |
e9e70b95 | 355 | |
d247a5d1 | 356 | if (!view.HaveInputs(tx)) |
61f8caf2 | 357 | { |
51376f3c | 358 | //fprintf(stderr,"dont have inputs\n"); |
d247a5d1 | 359 | continue; |
61f8caf2 | 360 | } |
37ad6886 | 361 | CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->nHeight,&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); |
e9e70b95 | 362 | |
d247a5d1 | 363 | nTxSigOps += GetP2SHSigOpCount(tx, view); |
a4a40a38 | 364 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 365 | { |
51376f3c | 366 | //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
d247a5d1 | 367 | continue; |
61f8caf2 | 368 | } |
68f7d1d7 PT |
369 | // Note that flags: we don't want to set mempool/IsStandard() |
370 | // policy here, but we still have to ensure that the block we | |
371 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 372 | CValidationState state; |
6514771a | 373 | PrecomputedTransactionData txdata(tx); |
be126699 | 374 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) |
61f8caf2 | 375 | { |
51376f3c | 376 | //fprintf(stderr,"context failure\n"); |
d247a5d1 | 377 | continue; |
61f8caf2 | 378 | } |
8cb98d91 | 379 | UpdateCoins(tx, view, nHeight); |
e9e70b95 | 380 | |
d247a5d1 JG |
381 | // Added |
382 | pblock->vtx.push_back(tx); | |
383 | pblocktemplate->vTxFees.push_back(nTxFees); | |
384 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
385 | nBlockSize += nTxSize; | |
386 | ++nBlockTx; | |
387 | nBlockSigOps += nTxSigOps; | |
388 | nFees += nTxFees; | |
e9e70b95 | 389 | |
d247a5d1 JG |
390 | if (fPrintPriority) |
391 | { | |
3f0813b3 | 392 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 | 393 | } |
e9e70b95 | 394 | |
d247a5d1 JG |
395 | // Add transactions that depend on this one to the priority queue |
396 | if (mapDependers.count(hash)) | |
397 | { | |
398 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
399 | { | |
400 | if (!porphan->setDependsOn.empty()) | |
401 | { | |
402 | porphan->setDependsOn.erase(hash); | |
403 | if (porphan->setDependsOn.empty()) | |
404 | { | |
c6cb21d1 | 405 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
406 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
407 | } | |
408 | } | |
409 | } | |
410 | } | |
411 | } | |
e9e70b95 | 412 | |
d247a5d1 JG |
413 | nLastBlockTx = nBlockTx; |
414 | nLastBlockSize = nBlockSize; | |
d07308d2 | 415 | blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); |
9a0f2798 | 416 | //pblock->nTime = blocktime + 1; |
135fa24e | 417 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
418 | ||
7dbeae5d | 419 | //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits); |
135fa24e | 420 | if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake ) |
a4a40a38 | 421 | { |
1f722359 | 422 | uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr; |
d231a6a7 | 423 | CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
1f722359 | 424 | |
cfb55edb | 425 | //if ( blocktime > pindexPrev->GetMedianTimePast()+60 ) |
426 | // blocktime = pindexPrev->GetMedianTimePast() + 60; | |
1f722359 MT |
427 | if (ASSETCHAINS_LWMAPOS != 0) |
428 | { | |
429 | uint32_t nBitsPOS; | |
430 | arith_uint256 posHash; | |
17d0160a | 431 | |
5034d1c1 | 432 | siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig); |
1f722359 | 433 | blocktime = GetAdjustedTime(); |
cd230e37 MT |
434 | |
435 | // change the scriptPubKeyIn to the same output script exactly as the staking transaction | |
436 | if (siglen > 0) | |
437 | scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey); | |
1f722359 MT |
438 | } |
439 | else | |
440 | { | |
5034d1c1 | 441 | siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig); |
1f722359 MT |
442 | } |
443 | ||
444 | if ( siglen > 0 ) | |
a4a40a38 | 445 | { |
66b4e563 | 446 | CAmount txfees = 0; |
86131275 | 447 | //if ( (int32_t)chainActive.LastTip()->nHeight+1 > 100 && GetAdjustedTime() < blocktime-157 ) |
0debf37f | 448 | // return(0); |
a4a40a38 | 449 | pblock->vtx.push_back(txStaked); |
a4a40a38 | 450 | pblocktemplate->vTxFees.push_back(txfees); |
d231a6a7 | 451 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked)); |
a4a40a38 | 452 | nFees += txfees; |
9339a0cb | 453 | pblock->nTime = blocktime; |
86131275 | 454 | //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->nHeight+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13))); |
9464ac21 | 455 | } else return(0); //fprintf(stderr,"no utxos eligible for staking\n"); |
a4a40a38 | 456 | } |
e9e70b95 | 457 | |
f3ffa3d2 | 458 | // Create coinbase tx |
072099d7 | 459 | CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight); |
f3ffa3d2 SB |
460 | txNew.vin.resize(1); |
461 | txNew.vin[0].prevout.SetNull(); | |
abb90a89 MT |
462 | txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; |
463 | ||
d581f229 | 464 | txNew.vout.resize(1); |
f3ffa3d2 | 465 | txNew.vout[0].scriptPubKey = scriptPubKeyIn; |
abb90a89 | 466 | txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus()) + nFees; |
9bb37bf0 | 467 | txNew.nExpiryHeight = 0; |
48d800c2 | 468 | txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); |
abb90a89 | 469 | |
e0bc68e6 | 470 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
471 | txNew.vout[0].nValue += 5000; | |
5034d1c1 | 472 | |
29bd53a1 | 473 | // check if coinbase transactions must be time locked at current subsidy and prepend the time lock |
a0dd01bc | 474 | // to transaction if so, cast for GTE operator |
475 | if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE) | |
abb90a89 MT |
476 | { |
477 | int32_t opretlen, p2shlen, scriptlen; | |
29bd53a1 | 478 | CScriptExt opretScript = CScriptExt(); |
abb90a89 MT |
479 | |
480 | txNew.vout.resize(2); | |
481 | ||
29bd53a1 MT |
482 | // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins |
483 | // protected only by the time lock rather than 100% inaccessible | |
484 | opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight)); | |
485 | if (!scriptPubKeyIn.IsPayToScriptHash()) | |
486 | opretScript += scriptPubKeyIn; | |
abb90a89 | 487 | |
29bd53a1 MT |
488 | txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript)); |
489 | txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK); | |
abb90a89 | 490 | txNew.vout[1].nValue = 0; |
48d800c2 | 491 | } // timelocks and commissions are currently incompatible due to validation complexity of the combination |
5034d1c1 | 492 | else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) |
c9b1071d | 493 | { |
c000c9ca | 494 | int32_t i; uint8_t *ptr; |
9ed1be03 | 495 | txNew.vout.resize(2); |
496 | txNew.vout[1].nValue = commission; | |
497 | txNew.vout[1].scriptPubKey.resize(35); | |
498 | ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data(); | |
c000c9ca | 499 | ptr[0] = 33; |
500 | for (i=0; i<33; i++) | |
501 | ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i]; | |
502 | ptr[34] = OP_CHECKSIG; | |
146d2aa2 | 503 | //printf("autocreate commision vout\n"); |
c9b1071d | 504 | } |
48d800c2 | 505 | |
4949004d | 506 | pblock->vtx[0] = txNew; |
d247a5d1 | 507 | pblocktemplate->vTxFees[0] = -nFees; |
48d800c2 | 508 | |
1fae37f6 MT |
509 | // if not Verus stake, setup nonce, otherwise, leave it alone |
510 | if (!isStake || ASSETCHAINS_LWMAPOS == 0) | |
511 | { | |
512 | // Randomise nonce | |
513 | arith_uint256 nonce = UintToArith256(GetRandHash()); | |
48d800c2 | 514 | |
1fae37f6 MT |
515 | // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters) |
516 | nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO]; | |
517 | nonce >>= 16; | |
518 | pblock->nNonce = ArithToUint256(nonce); | |
519 | } | |
e9e70b95 | 520 | |
d247a5d1 JG |
521 | // Fill in header |
522 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
a8d384ae | 523 | pblock->hashReserved = uint256(); |
0c8fa56a MT |
524 | |
525 | // all Verus PoS chains need this data in the block at all times | |
526 | if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 ) | |
9a0f2798 | 527 | { |
528 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
1fae37f6 | 529 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
9a0f2798 | 530 | } |
fdda3c50 | 531 | pblock->nSolution.clear(); |
d247a5d1 | 532 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
4d068367 | 533 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
af805d53 | 534 | { |
28a62b60 | 535 | uint32_t r; |
496f1fd2 | 536 | CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
fa04bcf3 | 537 | if ( pblock->nTime < pindexPrev->nTime+60 ) |
538 | pblock->nTime = pindexPrev->nTime + 60; | |
16593898 | 539 | if ( gpucount < 33 ) |
28a62b60 | 540 | { |
55566f16 | 541 | uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals; |
28a62b60 | 542 | memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid); |
543 | memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height); | |
544 | memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock); | |
9a146fef | 545 | vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n); |
55566f16 | 546 | memcpy(&r,&randvals,sizeof(r)); |
547 | pblock->nTime += (r % (33 - gpucount)*(33 - gpucount)); | |
28a62b60 | 548 | } |
a893e994 | 549 | if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 ) |
496f1fd2 | 550 | { |
2d79309f | 551 | CAmount txfees = 5000; |
496f1fd2 | 552 | pblock->vtx.push_back(txNotary); |
553 | pblocktemplate->vTxFees.push_back(txfees); | |
554 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary)); | |
555 | nFees += txfees; | |
2d79309f | 556 | pblocktemplate->vTxFees[0] = -nFees; |
c881e52b | 557 | //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees; |
f31815fc | 558 | //fprintf(stderr,"added notaryvin\n"); |
0857c3d5 | 559 | } |
560 | else | |
561 | { | |
562 | fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n"); | |
563 | return(0); | |
564 | } | |
707b061c | 565 | } |
809f2e25 | 566 | else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) |
af805d53 | 567 | { |
8fc79ac9 | 568 | CValidationState state; |
809f2e25 | 569 | //fprintf(stderr,"check validity\n"); |
570 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks | |
8fc79ac9 | 571 | { |
572 | //static uint32_t counter; | |
573 | //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) | |
574 | // fprintf(stderr,"warning: miner testblockvalidity failed\n"); | |
809f2e25 | 575 | fprintf(stderr,"invalid\n"); |
8fc79ac9 | 576 | return(0); |
577 | } | |
809f2e25 | 578 | //fprintf(stderr,"valid\n"); |
af805d53 | 579 | } |
d247a5d1 | 580 | } |
809f2e25 | 581 | /* skip checking validity outside of lock. if inside lock and CC contract is being validated, can deadlock. |
582 | if ( ASSETCHAINS_CC != 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) | |
581409cb | 583 | { |
584 | CValidationState state; | |
2a6a442a | 585 | //fprintf(stderr,"check validity\n"); |
586 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks | |
af805d53 | 587 | { |
581409cb | 588 | //static uint32_t counter; |
589 | //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) | |
590 | // fprintf(stderr,"warning: miner testblockvalidity failed\n"); | |
591 | fprintf(stderr,"invalid\n"); | |
592 | return(0); | |
af805d53 | 593 | } |
2a6a442a | 594 | //fprintf(stderr,"valid\n"); |
809f2e25 | 595 | }*/ |
2a6a442a | 596 | //fprintf(stderr,"done new block\n"); |
17929553 | 597 | |
d247a5d1 JG |
598 | return pblocktemplate.release(); |
599 | } | |
32b915c9 | 600 | |
1a31463b | 601 | /* |
e9e70b95 | 602 | #ifdef ENABLE_WALLET |
603 | boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey) | |
604 | #else | |
605 | boost::optional<CScript> GetMinerScriptPubKey() | |
606 | #endif | |
607 | { | |
608 | CKeyID keyID; | |
609 | CBitcoinAddress addr; | |
610 | if (addr.SetString(GetArg("-mineraddress", ""))) { | |
611 | addr.GetKeyID(keyID); | |
612 | } else { | |
613 | #ifdef ENABLE_WALLET | |
614 | CPubKey pubkey; | |
615 | if (!reservekey.GetReservedKey(pubkey)) { | |
616 | return boost::optional<CScript>(); | |
617 | } | |
618 | keyID = pubkey.GetID(); | |
619 | #else | |
620 | return boost::optional<CScript>(); | |
621 | #endif | |
622 | } | |
623 | ||
624 | CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
625 | return scriptPubKey; | |
626 | } | |
627 | ||
628 | #ifdef ENABLE_WALLET | |
629 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) | |
630 | { | |
631 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey); | |
632 | #else | |
633 | CBlockTemplate* CreateNewBlockWithKey() | |
634 | { | |
635 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(); | |
636 | #endif | |
637 | ||
638 | if (!scriptPubKey) { | |
639 | return NULL; | |
640 | } | |
641 | return CreateNewBlock(*scriptPubKey); | |
642 | }*/ | |
acfa0333 | 643 | |
c1de826f JG |
644 | ////////////////////////////////////////////////////////////////////////////// |
645 | // | |
646 | // Internal miner | |
647 | // | |
648 | ||
2cc0a252 | 649 | #ifdef ENABLE_MINING |
c1de826f | 650 | |
d247a5d1 JG |
651 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
652 | { | |
653 | // Update nExtraNonce | |
654 | static uint256 hashPrevBlock; | |
655 | if (hashPrevBlock != pblock->hashPrevBlock) | |
656 | { | |
657 | nExtraNonce = 0; | |
658 | hashPrevBlock = pblock->hashPrevBlock; | |
659 | } | |
660 | ++nExtraNonce; | |
661 | unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 | |
4949004d PW |
662 | CMutableTransaction txCoinbase(pblock->vtx[0]); |
663 | txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
664 | assert(txCoinbase.vin[0].scriptSig.size() <= 100); | |
e9e70b95 | 665 | |
4949004d | 666 | pblock->vtx[0] = txCoinbase; |
d247a5d1 JG |
667 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
668 | } | |
669 | ||
4a85e067 | 670 | #ifdef ENABLE_WALLET |
acfa0333 WL |
671 | ////////////////////////////////////////////////////////////////////////////// |
672 | // | |
673 | // Internal miner | |
674 | // | |
acfa0333 | 675 | |
5034d1c1 | 676 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake) |
acfa0333 | 677 | { |
f6c647ed | 678 | CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i; |
d9f176ac | 679 | if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 ) |
680 | { | |
681 | scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG; | |
682 | } | |
683 | else if ( USE_EXTERNAL_PUBKEY != 0 ) | |
998397aa | 684 | { |
7bfc207a | 685 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 686 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 687 | } |
688 | else | |
689 | { | |
690 | if (!reservekey.GetReservedKey(pubkey)) | |
1b5b89ba | 691 | { |
f6c647ed | 692 | return NULL; |
1b5b89ba | 693 | } |
f6c647ed | 694 | scriptPubKey.resize(35); |
f66f65ec | 695 | ptr = (uint8_t *)pubkey.begin(); |
f6c647ed | 696 | script = (uint8_t *)scriptPubKey.data(); |
697 | script[0] = 33; | |
698 | for (i=0; i<33; i++) | |
699 | script[i+1] = ptr[i]; | |
700 | script[34] = OP_CHECKSIG; | |
701 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
702 | } | |
5034d1c1 | 703 | return CreateNewBlock(scriptPubKey, gpucount, isStake); |
acfa0333 WL |
704 | } |
705 | ||
395f10cf | 706 | void komodo_broadcast(CBlock *pblock,int32_t limit) |
707 | { | |
708 | int32_t n = 1; | |
709 | //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
710 | { | |
711 | LOCK(cs_vNodes); | |
712 | BOOST_FOREACH(CNode* pnode, vNodes) | |
713 | { | |
714 | if ( pnode->hSocket == INVALID_SOCKET ) | |
715 | continue; | |
716 | if ( (rand() % n) == 0 ) | |
717 | { | |
718 | pnode->PushMessage("block", *pblock); | |
719 | if ( n++ > limit ) | |
720 | break; | |
721 | } | |
722 | } | |
723 | } | |
724 | //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
725 | } | |
945f015d | 726 | |
269d8ba0 | 727 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
8e8b6d70 JG |
728 | #else |
729 | static bool ProcessBlockFound(CBlock* pblock) | |
730 | #endif // ENABLE_WALLET | |
d247a5d1 | 731 | { |
81212588 | 732 | LogPrintf("%s\n", pblock->ToString()); |
86131275 | 733 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->nHeight+1); |
e9e70b95 | 734 | |
d247a5d1 JG |
735 | // Found a solution |
736 | { | |
194ad5b8 | 737 | //LOCK(cs_main); |
86131275 | 738 | if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash()) |
ba8419c7 | 739 | { |
740 | uint256 hash; int32_t i; | |
741 | hash = pblock->hashPrevBlock; | |
92266e99 | 742 | for (i=31; i>=0; i--) |
ba8419c7 | 743 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 744 | fprintf(stderr," <- prev (stale)\n"); |
86131275 | 745 | hash = chainActive.LastTip()->GetBlockHash(); |
92266e99 | 746 | for (i=31; i>=0; i--) |
ba8419c7 | 747 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 748 | fprintf(stderr," <- chainTip (stale)\n"); |
e9e70b95 | 749 | |
2e500f50 | 750 | return error("KomodoMiner: generated block is stale"); |
ba8419c7 | 751 | } |
18e72167 | 752 | } |
e9e70b95 | 753 | |
8e8b6d70 | 754 | #ifdef ENABLE_WALLET |
18e72167 | 755 | // Remove key from key pool |
998397aa | 756 | if ( IS_KOMODO_NOTARY == 0 ) |
945f015d | 757 | { |
758 | if (GetArg("-mineraddress", "").empty()) { | |
759 | // Remove key from key pool | |
760 | reservekey.KeepKey(); | |
761 | } | |
8e8b6d70 | 762 | } |
18e72167 | 763 | // Track how many getdata requests this block gets |
438ba9c1 | 764 | //if ( 0 ) |
18e72167 | 765 | { |
d1bc3a75 | 766 | //fprintf(stderr,"lock cs_wallet\n"); |
18e72167 PW |
767 | LOCK(wallet.cs_wallet); |
768 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 | 769 | } |
8e8b6d70 | 770 | #endif |
d1bc3a75 | 771 | //fprintf(stderr,"process new block\n"); |
194ad5b8 | 772 | |
18e72167 PW |
773 | // Process this block the same as if we had received it from another node |
774 | CValidationState state; | |
37ad6886 | 775 | if (!ProcessNewBlock(1,chainActive.LastTip()->nHeight+1,state, NULL, pblock, true, NULL)) |
2e500f50 | 776 | return error("KomodoMiner: ProcessNewBlock, block not accepted"); |
e9e70b95 | 777 | |
d793f94b | 778 | TrackMinedBlock(pblock->GetHash()); |
395f10cf | 779 | komodo_broadcast(pblock,16); |
d247a5d1 JG |
780 | return true; |
781 | } | |
782 | ||
078f6af1 | 783 | int32_t komodo_baseid(char *origbase); |
a30dd993 | 784 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); |
13691369 | 785 | arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); |
8ee93080 | 786 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
99ba67a0 | 787 | extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC; |
8b51b9e4 | 788 | int32_t roundrobin_delay; |
18443f69 | 789 | arith_uint256 HASHTarget,HASHTarget_POW; |
078f6af1 | 790 | |
5642c96c | 791 | // wait for peers to connect |
b45d65b4 | 792 | int32_t waitForPeers(const CChainParams &chainparams) |
5642c96c | 793 | { |
794 | if (chainparams.MiningRequiresPeers()) | |
795 | { | |
3da69a31 MT |
796 | bool fvNodesEmpty; |
797 | { | |
798 | LOCK(cs_vNodes); | |
799 | fvNodesEmpty = vNodes.empty(); | |
800 | } | |
6d84700d | 801 | if (fvNodesEmpty || !IsInSync()) |
3da69a31 MT |
802 | { |
803 | do { | |
64d6048f | 804 | if (fvNodesEmpty) |
805 | MilliSleep(1000 + rand() % 4000); | |
3da69a31 MT |
806 | { |
807 | LOCK(cs_vNodes); | |
808 | fvNodesEmpty = vNodes.empty(); | |
809 | } | |
bca01f86 | 810 | } while (fvNodesEmpty || !IsInSync()); |
0ba20651 | 811 | MilliSleep(100 + rand() % 400); |
3da69a31 | 812 | } |
5642c96c | 813 | } |
814 | } | |
815 | ||
42181656 | 816 | #ifdef ENABLE_WALLET |
d7e6718d MT |
817 | CBlockIndex *get_chainactive(int32_t height) |
818 | { | |
3c40a9a6 | 819 | if ( chainActive.LastTip() != 0 ) |
d7e6718d | 820 | { |
3c40a9a6 MT |
821 | if ( height <= chainActive.LastTip()->nHeight ) |
822 | { | |
823 | LOCK(cs_main); | |
d7e6718d | 824 | return(chainActive[height]); |
3c40a9a6 | 825 | } |
d7e6718d MT |
826 | // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->nHeight); |
827 | } | |
828 | //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); | |
829 | return(0); | |
830 | } | |
831 | ||
135fa24e | 832 | /* |
833 | * A separate thread to stake, while the miner threads mine. | |
834 | */ | |
835 | void static VerusStaker(CWallet *pwallet) | |
836 | { | |
837 | LogPrintf("Verus staker thread started\n"); | |
838 | RenameThread("verus-staker"); | |
839 | ||
840 | const CChainParams& chainparams = Params(); | |
841 | ||
842 | // Each thread has its own key | |
843 | CReserveKey reservekey(pwallet); | |
844 | ||
845 | // Each thread has its own counter | |
846 | unsigned int nExtraNonce = 0; | |
847 | std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>(); | |
848 | solnPlaceholder.resize(Eh200_9.SolutionWidth); | |
849 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; | |
850 | ||
851 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 && | |
852 | { | |
853 | sleep(1); | |
854 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
855 | break; | |
856 | } | |
857 | ||
858 | // try a nice clean peer connection to start | |
bf9c36f4 MT |
859 | CBlockIndex *pindexPrev, *pindexCur; |
860 | do { | |
861 | pindexPrev = chainActive.LastTip(); | |
862 | MilliSleep(5000 + rand() % 5000); | |
863 | waitForPeers(chainparams); | |
864 | pindexCur = chainActive.LastTip(); | |
865 | } while (pindexPrev != pindexCur); | |
c132b91a | 866 | |
135fa24e | 867 | try { |
135fa24e | 868 | while (true) |
869 | { | |
135fa24e | 870 | waitForPeers(chainparams); |
4ca6678c MT |
871 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
872 | printf("Staking height %d for %s\n", pindexPrev->nHeight + 1, ASSETCHAINS_SYMBOL); | |
135fa24e | 873 | |
874 | // Create new block | |
875 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
135fa24e | 876 | if ( Mining_height != pindexPrev->nHeight+1 ) |
877 | { | |
878 | Mining_height = pindexPrev->nHeight+1; | |
879 | Mining_start = (uint32_t)time(NULL); | |
880 | } | |
881 | ||
1fae37f6 MT |
882 | // Check for stop or if block needs to be rebuilt |
883 | boost::this_thread::interruption_point(); | |
884 | ||
135fa24e | 885 | // try to stake a block |
1fae37f6 MT |
886 | CBlockTemplate *ptr = NULL; |
887 | if (Mining_height > VERUS_MIN_STAKEAGE) | |
5034d1c1 | 888 | ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true); |
135fa24e | 889 | |
890 | if ( ptr == 0 ) | |
891 | { | |
1fae37f6 | 892 | // wait to try another staking block until after the tip moves again |
37ad6886 MT |
893 | while ( chainActive.LastTip() == pindexPrev ) |
894 | sleep(1); | |
135fa24e | 895 | continue; |
896 | } | |
897 | ||
898 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
899 | if (!pblocktemplate.get()) | |
900 | { | |
901 | if (GetArg("-mineraddress", "").empty()) { | |
1fae37f6 | 902 | LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
135fa24e | 903 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
904 | } else { | |
905 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
1fae37f6 | 906 | LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
135fa24e | 907 | } |
908 | return; | |
909 | } | |
910 | ||
911 | CBlock *pblock = &pblocktemplate->block; | |
1fae37f6 | 912 | LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
135fa24e | 913 | // |
914 | // Search | |
915 | // | |
1fae37f6 MT |
916 | int64_t nStart = GetTime(); |
917 | ||
52670b72 MT |
918 | // take up the necessary space for alignment |
919 | pblock->nSolution = solnPlaceholder; | |
920 | ||
1fae37f6 MT |
921 | // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree |
922 | unsigned int nExtraNonce = 0; | |
923 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); | |
135fa24e | 924 | |
1fae37f6 MT |
925 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
926 | { | |
927 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
928 | { | |
929 | fprintf(stderr,"no nodes, attempting reconnect\n"); | |
930 | continue; | |
931 | } | |
932 | } | |
933 | ||
934 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
935 | { | |
936 | fprintf(stderr,"timeout, retrying\n"); | |
937 | continue; | |
938 | } | |
135fa24e | 939 | |
37ad6886 | 940 | if ( pindexPrev != chainActive.LastTip() ) |
135fa24e | 941 | { |
37ad6886 | 942 | printf("Block %d added to chain\n", chainActive.LastTip()->nHeight); |
135fa24e | 943 | MilliSleep(250); |
944 | continue; | |
945 | } | |
946 | ||
1fae37f6 MT |
947 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
948 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
135fa24e | 949 | |
1fae37f6 | 950 | uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits)); |
135fa24e | 951 | |
b9956efc MT |
952 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); |
953 | ||
954 | UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); | |
955 | ||
956 | ProcessBlockFound(pblock, *pwallet, reservekey); | |
957 | ||
1fae37f6 MT |
958 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
959 | LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
960 | printf("Found block %d \n", Mining_height ); | |
961 | printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
b9956efc MT |
962 | arith_uint256 post; |
963 | post.SetCompact(pblock->GetVerusPOSTarget()); | |
d7e6718d MT |
964 | pindexPrev = get_chainactive(Mining_height - 100); |
965 | printf(" hash: %s \ntarget: %s\n", | |
966 | CTransaction::_GetVerusPOSHash(&(pblock->nNonce), pblock->vtx[pblock->vtx.size()-1].vin[0].prevout.hash, 0, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), pblock->vtx[pblock->vtx.size()-1].vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str()); | |
1fae37f6 MT |
967 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
968 | printf("- timelocked until block %i\n", unlockTime); | |
969 | else | |
970 | printf("\n"); | |
135fa24e | 971 | |
1fae37f6 MT |
972 | // Check for stop or if block needs to be rebuilt |
973 | boost::this_thread::interruption_point(); | |
135fa24e | 974 | |
bf9c36f4 | 975 | sleep(3); |
3da69a31 | 976 | |
1fae37f6 MT |
977 | // In regression test mode, stop mining after a block is found. |
978 | if (chainparams.MineBlocksOnDemand()) { | |
979 | throw boost::thread_interrupted(); | |
135fa24e | 980 | } |
981 | } | |
982 | } | |
983 | catch (const boost::thread_interrupted&) | |
984 | { | |
135fa24e | 985 | LogPrintf("VerusStaker terminated\n"); |
986 | throw; | |
987 | } | |
988 | catch (const std::runtime_error &e) | |
989 | { | |
135fa24e | 990 | LogPrintf("VerusStaker runtime error: %s\n", e.what()); |
991 | return; | |
992 | } | |
135fa24e | 993 | } |
994 | ||
42181656 | 995 | void static BitcoinMiner_noeq(CWallet *pwallet) |
996 | #else | |
997 | void static BitcoinMiner_noeq() | |
998 | #endif | |
999 | { | |
05f6e633 | 1000 | LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
05f6e633 | 1001 | RenameThread("verushash-miner"); |
42181656 | 1002 | |
1003 | #ifdef ENABLE_WALLET | |
1004 | // Each thread has its own key | |
1005 | CReserveKey reservekey(pwallet); | |
1006 | #endif | |
1007 | ||
2910478b | 1008 | const CChainParams& chainparams = Params(); |
42181656 | 1009 | // Each thread has its own counter |
1010 | unsigned int nExtraNonce = 0; | |
1011 | std::vector<unsigned char> solnPlaceholder = std::vector<unsigned char>(); | |
1012 | solnPlaceholder.resize(Eh200_9.SolutionWidth); | |
42181656 | 1013 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
1014 | ||
1015 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 && | |
1016 | { | |
1017 | sleep(1); | |
1018 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
1019 | break; | |
1020 | } | |
9f3e2213 | 1021 | |
3da69a31 MT |
1022 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
1023 | ||
5642c96c | 1024 | // try a nice clean peer connection to start |
c132b91a | 1025 | CBlockIndex *pindexPrev, *pindexCur; |
9f3e2213 | 1026 | do { |
37ad6886 | 1027 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 1028 | MilliSleep(5000 + rand() % 5000); |
bf9c36f4 | 1029 | waitForPeers(chainparams); |
37ad6886 | 1030 | pindexCur = chainActive.LastTip(); |
c132b91a | 1031 | } while (pindexPrev != pindexCur); |
6176a421 | 1032 | |
dbe656fe MT |
1033 | // this will not stop printing more than once in all cases, but it will allow us to print in all cases |
1034 | // and print duplicates rarely without having to synchronize | |
1035 | static CBlockIndex *lastChainTipPrinted; | |
9f3e2213 | 1036 | |
42181656 | 1037 | miningTimer.start(); |
1038 | ||
1039 | try { | |
dbe656fe | 1040 | printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 1041 | while (true) |
1042 | { | |
68334c8d | 1043 | miningTimer.stop(); |
1044 | waitForPeers(chainparams); | |
dfcf8255 | 1045 | |
37ad6886 | 1046 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 1047 | sleep(1); |
dfcf8255 MT |
1048 | |
1049 | // prevent forking on startup before the diff algorithm kicks in | |
37ad6886 | 1050 | if (pindexPrev->nHeight < 50 || pindexPrev != chainActive.LastTip()) |
dfcf8255 MT |
1051 | { |
1052 | do { | |
37ad6886 | 1053 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 1054 | MilliSleep(5000 + rand() % 5000); |
37ad6886 | 1055 | } while (pindexPrev != chainActive.LastTip()); |
dfcf8255 | 1056 | } |
42181656 | 1057 | |
1058 | // Create new block | |
1059 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
42181656 | 1060 | if ( Mining_height != pindexPrev->nHeight+1 ) |
1061 | { | |
1062 | Mining_height = pindexPrev->nHeight+1; | |
1063 | Mining_start = (uint32_t)time(NULL); | |
1064 | } | |
1065 | ||
dbe656fe MT |
1066 | if (lastChainTipPrinted != pindexPrev) |
1067 | { | |
1068 | printf("Mining height %d\n", Mining_height); | |
1069 | lastChainTipPrinted = pindexPrev; | |
1070 | } | |
1071 | ||
1072 | miningTimer.start(); | |
42181656 | 1073 | |
1074 | #ifdef ENABLE_WALLET | |
5034d1c1 | 1075 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0); |
42181656 | 1076 | #else |
1077 | CBlockTemplate *ptr = CreateNewBlockWithKey(); | |
1078 | #endif | |
1079 | if ( ptr == 0 ) | |
1080 | { | |
1081 | static uint32_t counter; | |
1082 | if ( counter++ < 100 ) | |
1083 | fprintf(stderr,"created illegal block, retry\n"); | |
1084 | continue; | |
1085 | } | |
dbe656fe | 1086 | |
42181656 | 1087 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
1088 | if (!pblocktemplate.get()) | |
1089 | { | |
1090 | if (GetArg("-mineraddress", "").empty()) { | |
05f6e633 | 1091 | LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
1092 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
42181656 | 1093 | } else { |
1094 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
05f6e633 | 1095 | LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
42181656 | 1096 | } |
1097 | return; | |
1098 | } | |
1099 | CBlock *pblock = &pblocktemplate->block; | |
1100 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) | |
1101 | { | |
1102 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) | |
1103 | { | |
1104 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1105 | { | |
1106 | static uint32_t counter; | |
1107 | if ( counter++ < 10 ) | |
1108 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
1109 | sleep(10); | |
1110 | continue; | |
1111 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
1112 | } | |
1113 | } | |
1114 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); | |
1115 | LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], | |
1116 | pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); | |
1117 | // | |
1118 | // Search | |
1119 | // | |
1120 | uint32_t savebits; int64_t nStart = GetTime(); | |
1121 | ||
1122 | pblock->nSolution = solnPlaceholder; | |
1123 | savebits = pblock->nBits; | |
1124 | arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); | |
1125 | arith_uint256 mask(ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO]); | |
1126 | ||
1127 | Mining_start = 0; | |
ef70c5b2 | 1128 | |
37ad6886 | 1129 | if ( pindexPrev != chainActive.LastTip() ) |
05f6e633 | 1130 | { |
37ad6886 | 1131 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 1132 | { |
37ad6886 | 1133 | lastChainTipPrinted = chainActive.LastTip(); |
dbe656fe MT |
1134 | printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); |
1135 | } | |
6176a421 | 1136 | MilliSleep(250); |
05f6e633 | 1137 | continue; |
1138 | } | |
ef70c5b2 | 1139 | |
135fa24e | 1140 | if ( ASSETCHAINS_STAKED != 0 ) |
1141 | { | |
1142 | int32_t percPoS,z; | |
1143 | hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED); | |
1144 | for (z=31; z>=0; z--) | |
1145 | fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); | |
1146 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
1147 | } | |
1148 | ||
42181656 | 1149 | while (true) |
1150 | { | |
dbe656fe MT |
1151 | arith_uint256 arNonce = UintToArith256(pblock->nNonce); |
1152 | ||
4dcb64c0 | 1153 | CVerusHashWriter ss = CVerusHashWriter(SER_GETHASH, PROTOCOL_VERSION); |
20ab1c91 | 1154 | ss << *((CBlockHeader *)pblock); |
4dcb64c0 MT |
1155 | int64_t *extraPtr = ss.xI64p(); |
1156 | CVerusHash &vh = ss.GetState(); | |
1157 | uint256 hashResult = uint256(); | |
1158 | vh.ClearExtra(); | |
69767347 | 1159 | int64_t i, count = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1; |
4dcb64c0 MT |
1160 | int64_t hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
1161 | ||
69767347 MT |
1162 | // for speed check NONCEMASK at a time |
1163 | for (i = 0; i < count; i++) | |
42181656 | 1164 | { |
4dcb64c0 MT |
1165 | *extraPtr = i; |
1166 | vh.ExtraHash((unsigned char *)&hashResult); | |
42181656 | 1167 | |
4dcb64c0 | 1168 | if ( UintToArith256(hashResult) <= hashTarget ) |
42181656 | 1169 | { |
4dcb64c0 MT |
1170 | if (pblock->nSolution.size() != 1344) |
1171 | { | |
1172 | LogPrintf("ERROR: Block solution is not 1344 bytes as it should be"); | |
1173 | sleep(5); | |
1174 | break; | |
1175 | } | |
1176 | ||
42181656 | 1177 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
1178 | ||
4dcb64c0 MT |
1179 | *((int64_t *)&(pblock->nSolution.data()[pblock->nSolution.size() - 15])) = i; |
1180 | ||
ef70c5b2 | 1181 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
1182 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
1183 | ||
135fa24e | 1184 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 1185 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); |
14d104e9 | 1186 | printf("Found block %d \n", Mining_height ); |
a62041d9 | 1187 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); |
ef70c5b2 | 1188 | printf(" hash: %s \ntarget: %s\n", pblock->GetHash().GetHex().c_str(), hashTarget.GetHex().c_str()); |
1189 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) | |
1190 | printf("- timelocked until block %i\n", unlockTime); | |
1191 | else | |
1192 | printf("\n"); | |
42181656 | 1193 | #ifdef ENABLE_WALLET |
1194 | ProcessBlockFound(pblock, *pwallet, reservekey); | |
1195 | #else | |
1196 | ProcessBlockFound(pblock)); | |
1197 | #endif | |
1198 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
42181656 | 1199 | break; |
1200 | } | |
dbe656fe | 1201 | // check periodically if we're stale |
4dcb64c0 | 1202 | if (!--hashesToGo) |
42181656 | 1203 | { |
37ad6886 | 1204 | if ( pindexPrev != chainActive.LastTip() ) |
ef70c5b2 | 1205 | { |
37ad6886 | 1206 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 1207 | { |
37ad6886 | 1208 | lastChainTipPrinted = chainActive.LastTip(); |
dbe656fe MT |
1209 | printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); |
1210 | } | |
ef70c5b2 | 1211 | break; |
1212 | } | |
4dcb64c0 | 1213 | hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
42181656 | 1214 | } |
1215 | } | |
1216 | ||
69767347 MT |
1217 | { |
1218 | LOCK(cs_metrics); | |
1219 | nHashCount += i; | |
1220 | } | |
1221 | ||
42181656 | 1222 | // Check for stop or if block needs to be rebuilt |
1223 | boost::this_thread::interruption_point(); | |
1224 | ||
1225 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
1226 | { | |
1227 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1228 | { | |
ef70c5b2 | 1229 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
42181656 | 1230 | break; |
1231 | } | |
1232 | } | |
1233 | ||
dbe656fe | 1234 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
42181656 | 1235 | { |
dbe656fe | 1236 | fprintf(stderr,"timeout, retrying\n"); |
42181656 | 1237 | break; |
1238 | } | |
1239 | ||
37ad6886 | 1240 | if ( pindexPrev != chainActive.LastTip() ) |
42181656 | 1241 | { |
37ad6886 | 1242 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 1243 | { |
37ad6886 | 1244 | lastChainTipPrinted = chainActive.LastTip(); |
dbe656fe MT |
1245 | printf("Block %d added to chain\n", lastChainTipPrinted->nHeight); |
1246 | } | |
42181656 | 1247 | break; |
1248 | } | |
1249 | ||
52cf66e1 | 1250 | #ifdef _WIN32 |
4dcb64c0 | 1251 | printf("%llu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576); |
52cf66e1 | 1252 | #else |
4dcb64c0 | 1253 | printf("%lu mega hashes complete - working\n", (ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] + 1) / 1048576); |
52cf66e1 | 1254 | #endif |
4dcb64c0 | 1255 | break; |
42181656 | 1256 | } |
1257 | } | |
1258 | } | |
1259 | catch (const boost::thread_interrupted&) | |
1260 | { | |
1261 | miningTimer.stop(); | |
5034d1c1 | 1262 | LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 1263 | throw; |
1264 | } | |
1265 | catch (const std::runtime_error &e) | |
1266 | { | |
1267 | miningTimer.stop(); | |
5034d1c1 | 1268 | LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what()); |
42181656 | 1269 | return; |
1270 | } | |
1271 | miningTimer.stop(); | |
1272 | } | |
1273 | ||
8e8b6d70 | 1274 | #ifdef ENABLE_WALLET |
d247a5d1 | 1275 | void static BitcoinMiner(CWallet *pwallet) |
8e8b6d70 JG |
1276 | #else |
1277 | void static BitcoinMiner() | |
1278 | #endif | |
d247a5d1 | 1279 | { |
2e500f50 | 1280 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 1281 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 1282 | RenameThread("komodo-miner"); |
bebe7282 | 1283 | const CChainParams& chainparams = Params(); |
e9e70b95 | 1284 | |
8e8b6d70 JG |
1285 | #ifdef ENABLE_WALLET |
1286 | // Each thread has its own key | |
d247a5d1 | 1287 | CReserveKey reservekey(pwallet); |
8e8b6d70 | 1288 | #endif |
e9e70b95 | 1289 | |
8e8b6d70 | 1290 | // Each thread has its own counter |
d247a5d1 | 1291 | unsigned int nExtraNonce = 0; |
e9e70b95 | 1292 | |
e9574728 JG |
1293 | unsigned int n = chainparams.EquihashN(); |
1294 | unsigned int k = chainparams.EquihashK(); | |
16593898 | 1295 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1; |
99ba67a0 | 1296 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) |
755ead98 | 1297 | { |
1298 | sleep(1); | |
4e624c04 | 1299 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
1300 | break; | |
755ead98 | 1301 | } |
32b0978b | 1302 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
1303 | komodo_chosennotary(¬aryid,chainActive.LastTip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); | |
28a62b60 | 1304 | if ( notaryid != My_notaryid ) |
1305 | My_notaryid = notaryid; | |
755ead98 | 1306 | std::string solver; |
e1e65cef | 1307 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
e9e70b95 | 1308 | solver = "tromp"; |
e1e65cef | 1309 | //else solver = "default"; |
5f0009b2 | 1310 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 1311 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 1312 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 1313 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
1314 | std::mutex m_cs; |
1315 | bool cancelSolver = false; | |
1316 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
e9e70b95 | 1317 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { |
1318 | std::lock_guard<std::mutex> lock{m_cs}; | |
1319 | cancelSolver = true; | |
1320 | } | |
1321 | ); | |
07be8f7e | 1322 | miningTimer.start(); |
e9e70b95 | 1323 | |
0655fac0 | 1324 | try { |
ad84148d | 1325 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 1326 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 1327 | while (true) |
1328 | { | |
86131275 | 1329 | if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->nHeight != 235300 && |
e725f1cb | 1330 | { |
86131275 | 1331 | //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->nHeight < 100 ) |
a96fd7b5 | 1332 | // break; |
0655fac0 PK |
1333 | // Busy-wait for the network to come online so we don't waste time mining |
1334 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
07be8f7e | 1335 | miningTimer.stop(); |
bba7c249 GM |
1336 | do { |
1337 | bool fvNodesEmpty; | |
1338 | { | |
373668be | 1339 | //LOCK(cs_vNodes); |
bba7c249 GM |
1340 | fvNodesEmpty = vNodes.empty(); |
1341 | } | |
269fe243 | 1342 | if (!fvNodesEmpty )//&& !IsInitialBlockDownload()) |
bba7c249 | 1343 | break; |
6e78d3df | 1344 | MilliSleep(15000); |
ad84148d | 1345 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
e9e70b95 | 1346 | |
bba7c249 | 1347 | } while (true); |
ad84148d | 1348 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
07be8f7e | 1349 | miningTimer.start(); |
0655fac0 | 1350 | } |
0655fac0 PK |
1351 | // |
1352 | // Create new block | |
1353 | // | |
1354 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
86131275 | 1355 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
4940066c | 1356 | if ( Mining_height != pindexPrev->nHeight+1 ) |
1357 | { | |
1358 | Mining_height = pindexPrev->nHeight+1; | |
1359 | Mining_start = (uint32_t)time(NULL); | |
1360 | } | |
8e9ef91c | 1361 | if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) |
2825c0b5 | 1362 | { |
40304479 | 1363 | //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
5a7fd132 | 1364 | //sleep(3); |
2825c0b5 | 1365 | } |
135fa24e | 1366 | |
8e8b6d70 | 1367 | #ifdef ENABLE_WALLET |
135fa24e | 1368 | // notaries always default to staking |
5034d1c1 | 1369 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->nHeight+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); |
8e8b6d70 | 1370 | #else |
945f015d | 1371 | CBlockTemplate *ptr = CreateNewBlockWithKey(); |
8e8b6d70 | 1372 | #endif |
08d0b73c | 1373 | if ( ptr == 0 ) |
1374 | { | |
d0f7ead0 | 1375 | static uint32_t counter; |
5bb3d0fe | 1376 | if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) |
1b5b89ba | 1377 | fprintf(stderr,"created illegal block, retry\n"); |
8fc79ac9 | 1378 | sleep(1); |
d0f7ead0 | 1379 | continue; |
08d0b73c | 1380 | } |
2a6a442a | 1381 | //fprintf(stderr,"get template\n"); |
08d0b73c | 1382 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
0655fac0 | 1383 | if (!pblocktemplate.get()) |
6c37f7fd | 1384 | { |
8e8b6d70 | 1385 | if (GetArg("-mineraddress", "").empty()) { |
945f015d | 1386 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
8e8b6d70 JG |
1387 | } else { |
1388 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
945f015d | 1389 | LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n"); |
8e8b6d70 | 1390 | } |
0655fac0 | 1391 | return; |
6c37f7fd | 1392 | } |
0655fac0 | 1393 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 1394 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
1395 | { | |
42181656 | 1396 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) |
16c7bf6b | 1397 | { |
8683bd8d | 1398 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
1399 | { | |
1400 | static uint32_t counter; | |
1401 | if ( counter++ < 10 ) | |
1402 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
1403 | sleep(10); | |
1404 | continue; | |
1405 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
1406 | } | |
16c7bf6b | 1407 | } |
0655fac0 | 1408 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2a6a442a | 1409 | //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size()); |
2e500f50 | 1410 | 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 |
1411 | // |
1412 | // Search | |
1413 | // | |
2ba9de01 | 1414 | uint8_t pubkeys[66][33]; arith_uint256 bnMaxPoSdiff; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); |
d5614a76 | 1415 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
404391b5 | 1416 | savebits = pblock->nBits; |
d5614a76 | 1417 | HASHTarget = arith_uint256().SetCompact(savebits); |
f0100e72 | 1418 | roundrobin_delay = ROUNDROBIN_DELAY; |
3e7e3109 | 1419 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 ) |
5203fc4b | 1420 | { |
fda5f849 | 1421 | j = 65; |
67df454d | 1422 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) |
fb6c7505 | 1423 | { |
4fff8a63 | 1424 | int32_t dispflag = 0; |
ef70c5b2 | 1425 | if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) |
4fff8a63 | 1426 | dispflag = 1; |
a30dd993 | 1427 | komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight); |
29e60e48 | 1428 | if ( nonzpkeys > 0 ) |
1429 | { | |
ccb71a6e | 1430 | for (i=0; i<33; i++) |
1431 | if( pubkeys[0][i] != 0 ) | |
1432 | break; | |
1433 | if ( i == 33 ) | |
1434 | externalflag = 1; | |
1435 | else externalflag = 0; | |
4d068367 | 1436 | if ( IS_KOMODO_NOTARY != 0 ) |
b176c125 | 1437 | { |
345e545e | 1438 | for (i=1; i<66; i++) |
1439 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
1440 | break; | |
6494f040 | 1441 | if ( externalflag == 0 && i != 66 && mids[i] >= 0 ) |
1442 | printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]); | |
2c7ad758 | 1443 | for (j=gpucount=0; j<65; j++) |
1444 | { | |
4fff8a63 | 1445 | if ( dispflag != 0 ) |
e4a383e3 | 1446 | { |
1447 | if ( mids[j] >= 0 ) | |
1448 | fprintf(stderr,"%d ",mids[j]); | |
1449 | else fprintf(stderr,"GPU "); | |
1450 | } | |
2c7ad758 | 1451 | if ( mids[j] == -1 ) |
1452 | gpucount++; | |
1453 | } | |
4fff8a63 | 1454 | if ( dispflag != 0 ) |
16593898 | 1455 | fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL)); |
b176c125 | 1456 | } |
29e60e48 | 1457 | for (j=0; j<65; j++) |
1458 | if ( mids[j] == notaryid ) | |
1459 | break; | |
49b49585 | 1460 | if ( j == 65 ) |
1461 | KOMODO_LASTMINED = 0; | |
965f0f7e | 1462 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 1463 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 1464 | { |
88287857 | 1465 | HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); |
fda5f849 | 1466 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1); |
1467 | } //else fprintf(stderr,"duplicate at j.%d\n",j); | |
fb6c7505 | 1468 | } else Mining_start = 0; |
d7d27bb3 | 1469 | } else Mining_start = 0; |
2ba9de01 | 1470 | if ( ASSETCHAINS_STAKED != 0 ) |
e725f1cb | 1471 | { |
ed3d0a05 | 1472 | int32_t percPoS,z; bool fNegative,fOverflow; |
18443f69 | 1473 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
f108acf9 | 1474 | HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); |
f2c1ac06 | 1475 | if ( ASSETCHAINS_STAKED < 100 ) |
1476 | { | |
1477 | for (z=31; z>=0; z--) | |
1478 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); | |
1479 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
1480 | } | |
deba7f20 | 1481 | } |
e725f1cb | 1482 | while (true) |
1483 | { | |
99ba67a0 | 1484 | if ( KOMODO_INSYNC == 0 ) |
1485 | { | |
e9d56b2c | 1486 | fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); |
1487 | if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) | |
a02c45db | 1488 | KOMODO_INSYNC = 1; |
99ba67a0 | 1489 | sleep(3); |
1490 | } | |
7213c0b1 | 1491 | // Hash state |
8c22eb46 | 1492 | KOMODO_CHOSEN_ONE = 0; |
42181656 | 1493 | |
7213c0b1 | 1494 | crypto_generichash_blake2b_state state; |
e9574728 | 1495 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
1496 | // I = the block header minus nonce and solution. |
1497 | CEquihashInput I{*pblock}; | |
1498 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
1499 | ss << I; | |
7213c0b1 JG |
1500 | // H(I||... |
1501 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
1502 | // H(I||V||... |
1503 | crypto_generichash_blake2b_state curr_state; | |
1504 | curr_state = state; | |
7a4c01c9 | 1505 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 1506 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 1507 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
18443f69 | 1508 | arith_uint256 hashTarget; |
6e78d3df | 1509 | if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 ) |
18443f69 | 1510 | hashTarget = HASHTarget_POW; |
1511 | else hashTarget = HASHTarget; | |
5be6abbf | 1512 | std::function<bool(std::vector<unsigned char>)> validBlock = |
8e8b6d70 | 1513 | #ifdef ENABLE_WALLET |
e9e70b95 | 1514 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 1515 | #else |
e9e70b95 | 1516 | [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 1517 | #endif |
e9e70b95 | 1518 | (std::vector<unsigned char> soln) { |
c21c6306 | 1519 | int32_t z; arith_uint256 h; CBlock B; |
51eb5273 JG |
1520 | // Write the solution to the hash and compute the result. |
1521 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 1522 | pblock->nSolution = soln; |
e7d59bbc | 1523 | solutionTargetChecks.increment(); |
eff2c3a3 | 1524 | B = *pblock; |
1525 | h = UintToArith256(B.GetHash()); | |
eff2c3a3 | 1526 | /*for (z=31; z>=16; z--) |
02c30aac | 1527 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); |
aea2d1aa | 1528 | fprintf(stderr," mined "); |
1529 | for (z=31; z>=16; z--) | |
18443f69 | 1530 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); |
aea2d1aa | 1531 | fprintf(stderr," hashTarget "); |
1532 | for (z=31; z>=16; z--) | |
18443f69 | 1533 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); |
eff2c3a3 | 1534 | fprintf(stderr," POW\n");*/ |
265f4e96 | 1535 | if ( h > hashTarget ) |
40df8d84 | 1536 | { |
6e78d3df | 1537 | //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 ) |
afa90f17 | 1538 | // sleep(1); |
265f4e96 | 1539 | return false; |
40df8d84 | 1540 | } |
41e9c815 | 1541 | if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() ) |
d7d27bb3 | 1542 | { |
45ee62cb | 1543 | //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime())); |
596b05ba | 1544 | while ( GetAdjustedTime() < B.nTime-2 ) |
8e9ef91c | 1545 | { |
eb1ba5a0 | 1546 | sleep(1); |
86131275 | 1547 | if ( chainActive.LastTip()->nHeight >= Mining_height ) |
4cc387ec | 1548 | { |
1549 | fprintf(stderr,"new block arrived\n"); | |
1550 | return(false); | |
1551 | } | |
8e9ef91c | 1552 | } |
eb1ba5a0 | 1553 | } |
8e9ef91c | 1554 | if ( ASSETCHAINS_STAKED == 0 ) |
d7d27bb3 | 1555 | { |
4d068367 | 1556 | if ( IS_KOMODO_NOTARY != 0 ) |
8e9ef91c | 1557 | { |
26810a26 | 1558 | int32_t r; |
9703f8a0 | 1559 | if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 ) |
596b05ba | 1560 | MilliSleep((rand() % (r * 1000)) + 1000); |
ef70c5b2 | 1561 | } |
e5430f52 | 1562 | } |
8e9ef91c | 1563 | else |
d7d27bb3 | 1564 | { |
0c35569b | 1565 | while ( B.nTime-57 > GetAdjustedTime() ) |
deba7f20 | 1566 | { |
afa90f17 | 1567 | sleep(1); |
86131275 | 1568 | if ( chainActive.LastTip()->nHeight >= Mining_height ) |
afa90f17 | 1569 | return(false); |
68d0354d | 1570 | } |
4d068367 | 1571 | uint256 tmp = B.GetHash(); |
1572 | int32_t z; for (z=31; z>=0; z--) | |
1573 | fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); | |
01e50e73 | 1574 | fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height); |
d7d27bb3 | 1575 | } |
8fc79ac9 | 1576 | CValidationState state; |
86131275 | 1577 | if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false)) |
d2d3c766 | 1578 | { |
8fc79ac9 | 1579 | h = UintToArith256(B.GetHash()); |
1580 | for (z=31; z>=0; z--) | |
1581 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); | |
1582 | fprintf(stderr," Invalid block mined, try again\n"); | |
1583 | return(false); | |
d2d3c766 | 1584 | } |
b3183e3e | 1585 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
1586 | // Found a solution |
1587 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 1588 | LogPrintf("KomodoMiner:\n"); |
eff2c3a3 | 1589 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); |
8e8b6d70 | 1590 | #ifdef ENABLE_WALLET |
eff2c3a3 | 1591 | if (ProcessBlockFound(&B, *pwallet, reservekey)) { |
8e8b6d70 | 1592 | #else |
eff2c3a3 | 1593 | if (ProcessBlockFound(&B)) { |
8e8b6d70 | 1594 | #endif |
e9e70b95 | 1595 | // Ignore chain updates caused by us |
1596 | std::lock_guard<std::mutex> lock{m_cs}; | |
1597 | cancelSolver = false; | |
1598 | } | |
1599 | KOMODO_CHOSEN_ONE = 0; | |
1600 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
1601 | // In regression test mode, stop mining after a block is found. | |
1602 | if (chainparams.MineBlocksOnDemand()) { | |
1603 | // Increment here because throwing skips the call below | |
1604 | ehSolverRuns.increment(); | |
1605 | throw boost::thread_interrupted(); | |
1606 | } | |
e9e70b95 | 1607 | return true; |
1608 | }; | |
1609 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
a6a0d913 | 1610 | std::lock_guard<std::mutex> lock{m_cs}; |
e9e70b95 | 1611 | return cancelSolver; |
1612 | }; | |
1613 | ||
1614 | // TODO: factor this out into a function with the same API for each solver. | |
1615 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { | |
1616 | // Create solver and initialize it. | |
1617 | equi eq(1); | |
1618 | eq.setstate(&curr_state); | |
1619 | ||
1620 | // Initialization done, start algo driver. | |
1621 | eq.digit0(0); | |
c7aaab7a | 1622 | eq.xfull = eq.bfull = eq.hfull = 0; |
e9e70b95 | 1623 | eq.showbsizes(0); |
1624 | for (u32 r = 1; r < WK; r++) { | |
1625 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
1626 | eq.xfull = eq.bfull = eq.hfull = 0; | |
1627 | eq.showbsizes(r); | |
c7aaab7a | 1628 | } |
e9e70b95 | 1629 | eq.digitK(0); |
1630 | ehSolverRuns.increment(); | |
1631 | ||
1632 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
1633 | for (size_t s = 0; s < eq.nsols; s++) { | |
1634 | LogPrint("pow", "Checking solution %d\n", s+1); | |
1635 | std::vector<eh_index> index_vector(PROOFSIZE); | |
1636 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
1637 | index_vector[i] = eq.sols[s][i]; | |
1638 | } | |
1639 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
1640 | ||
1641 | if (validBlock(sol_char)) { | |
1642 | // If we find a POW solution, do not try other solutions | |
1643 | // because they become invalid as we created a new block in blockchain. | |
1644 | break; | |
1645 | } | |
1646 | } | |
1647 | } else { | |
1648 | try { | |
1649 | // If we find a valid block, we rebuild | |
1650 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); | |
1651 | ehSolverRuns.increment(); | |
1652 | if (found) { | |
997ddd92 | 1653 | int32_t i; uint256 hash = pblock->GetHash(); |
e9e70b95 | 1654 | for (i=0; i<32; i++) |
1655 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
1656 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
1657 | FOUND_BLOCK = 1; | |
1658 | KOMODO_MAYBEMINED = Mining_height; | |
1659 | break; | |
1660 | } | |
1661 | } catch (EhSolverCancelledException&) { | |
1662 | LogPrint("pow", "Equihash solver cancelled\n"); | |
1663 | std::lock_guard<std::mutex> lock{m_cs}; | |
1664 | cancelSolver = false; | |
c7aaab7a DH |
1665 | } |
1666 | } | |
e9e70b95 | 1667 | |
1668 | // Check for stop or if block needs to be rebuilt | |
1669 | boost::this_thread::interruption_point(); | |
1670 | // Regtest mode doesn't require peers | |
1671 | if ( FOUND_BLOCK != 0 ) | |
1672 | { | |
1673 | FOUND_BLOCK = 0; | |
1674 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
1675 | //sleep(2000); | |
1676 | } | |
1677 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
1678 | { | |
1679 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1680 | { | |
1681 | fprintf(stderr,"no nodes, break\n"); | |
c7aaab7a | 1682 | break; |
a6df7ab5 | 1683 | } |
c7aaab7a | 1684 | } |
997ddd92 | 1685 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
10694486 | 1686 | { |
e9e70b95 | 1687 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
1688 | fprintf(stderr,"0xffff, break\n"); | |
d90cef0b | 1689 | break; |
10694486 | 1690 | } |
e9e70b95 | 1691 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
1692 | { | |
1693 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
1694 | fprintf(stderr,"timeout, break\n"); | |
1695 | break; | |
1696 | } | |
86131275 | 1697 | if ( pindexPrev != chainActive.LastTip() ) |
e9e70b95 | 1698 | { |
1699 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
1700 | fprintf(stderr,"Tip advanced, break\n"); | |
1701 | break; | |
1702 | } | |
1703 | // Update nNonce and nTime | |
1704 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
1705 | pblock->nBits = savebits; | |
18dd6a3b | 1706 | /*if ( NOTARY_PUBKEY33[0] == 0 ) |
e9e70b95 | 1707 | { |
f8f740a9 | 1708 | int32_t percPoS; |
23fc88bb | 1709 | UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); |
1710 | if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) | |
1711 | { | |
1712 | // Changing pblock->nTime can change work required on testnet: | |
1713 | HASHTarget.SetCompact(pblock->nBits); | |
18443f69 | 1714 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
23fc88bb | 1715 | } |
18dd6a3b | 1716 | }*/ |
48265f3c | 1717 | } |
d247a5d1 JG |
1718 | } |
1719 | } | |
e9e70b95 | 1720 | catch (const boost::thread_interrupted&) |
1721 | { | |
1722 | miningTimer.stop(); | |
1723 | c.disconnect(); | |
1724 | LogPrintf("KomodoMiner terminated\n"); | |
1725 | throw; | |
1726 | } | |
1727 | catch (const std::runtime_error &e) | |
1728 | { | |
1729 | miningTimer.stop(); | |
1730 | c.disconnect(); | |
1731 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); | |
1732 | return; | |
1733 | } | |
07be8f7e | 1734 | miningTimer.stop(); |
5e9b555f | 1735 | c.disconnect(); |
bba7c249 | 1736 | } |
e9e70b95 | 1737 | |
8e8b6d70 | 1738 | #ifdef ENABLE_WALLET |
e9e70b95 | 1739 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
8e8b6d70 | 1740 | #else |
e9e70b95 | 1741 | void GenerateBitcoins(bool fGenerate, int nThreads) |
8e8b6d70 | 1742 | #endif |
d247a5d1 | 1743 | { |
e9e70b95 | 1744 | static boost::thread_group* minerThreads = NULL; |
1745 | ||
1746 | if (nThreads < 0) | |
1747 | nThreads = GetNumCores(); | |
1748 | ||
1749 | if (minerThreads != NULL) | |
1750 | { | |
1751 | minerThreads->interrupt_all(); | |
1752 | delete minerThreads; | |
1753 | minerThreads = NULL; | |
1754 | } | |
135fa24e | 1755 | |
afaeb54b | 1756 | //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate); |
5034d1c1 | 1757 | if ( nThreads == 0 && ASSETCHAINS_STAKED ) |
3a446d9f | 1758 | nThreads = 1; |
5034d1c1 | 1759 | |
1f722359 | 1760 | if ((nThreads == 0 && ASSETCHAINS_LWMAPOS == 0) || !fGenerate) |
e9e70b95 | 1761 | return; |
135fa24e | 1762 | |
e9e70b95 | 1763 | minerThreads = new boost::thread_group(); |
135fa24e | 1764 | |
1765 | #ifdef ENABLE_WALLET | |
1f722359 | 1766 | if (ASSETCHAINS_LWMAPOS != 0) |
135fa24e | 1767 | { |
1768 | minerThreads->create_thread(boost::bind(&VerusStaker, pwallet)); | |
1769 | } | |
1770 | #endif | |
1771 | ||
e9e70b95 | 1772 | for (int i = 0; i < nThreads; i++) { |
135fa24e | 1773 | |
8e8b6d70 | 1774 | #ifdef ENABLE_WALLET |
135fa24e | 1775 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
1776 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
1777 | else | |
1778 | minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet)); | |
8e8b6d70 | 1779 | #else |
135fa24e | 1780 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
1781 | minerThreads->create_thread(&BitcoinMiner); | |
1782 | else | |
1783 | minerThreads->create_thread(&BitcoinMiner_noeq); | |
8e8b6d70 | 1784 | #endif |
e9e70b95 | 1785 | } |
8e8b6d70 | 1786 | } |
e9e70b95 | 1787 | |
2cc0a252 | 1788 | #endif // ENABLE_MINING |