]>
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" |
bebe7282 | 12 | #include "chainparams.h" |
ca4a5f26 | 13 | #include "cc/StakeGuard.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" |
93bd00a0 | 23 | #include "key_io.h" |
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 | |
df756d24 MT |
38 | #include "zcash/Address.hpp" |
39 | #include "transaction_builder.h" | |
40 | ||
fdda3c50 JG |
41 | #include "sodium.h" |
42 | ||
ad49c256 | 43 | #include <boost/thread.hpp> |
a3c26c2e | 44 | #include <boost/tuple/tuple.hpp> |
8e8b6d70 JG |
45 | #ifdef ENABLE_MINING |
46 | #include <functional> | |
47 | #endif | |
5a360a5c | 48 | #include <mutex> |
ad49c256 | 49 | |
2299bd95 MT |
50 | #include "pbaas/pbaas.h" |
51 | #include "pbaas/notarization.h" | |
52 | ||
09eb201b | 53 | using namespace std; |
7b4737c8 | 54 | |
d247a5d1 JG |
55 | ////////////////////////////////////////////////////////////////////////////// |
56 | // | |
57 | // BitcoinMiner | |
58 | // | |
59 | ||
c6cb21d1 GA |
60 | // |
61 | // Unconfirmed transactions in the memory pool often depend on other | |
62 | // transactions in the memory pool. When we select transactions from the | |
63 | // pool, we select by highest priority or fee rate, so we might consider | |
64 | // transactions that depend on transactions that aren't yet in the block. | |
65 | // The COrphan class keeps track of these 'temporary orphans' while | |
66 | // CreateBlock is figuring out which transactions to include. | |
67 | // | |
d247a5d1 JG |
68 | class COrphan |
69 | { | |
70 | public: | |
4d707d51 | 71 | const CTransaction* ptx; |
d247a5d1 | 72 | set<uint256> setDependsOn; |
c6cb21d1 | 73 | CFeeRate feeRate; |
02bec4b2 | 74 | double dPriority; |
e9e70b95 | 75 | |
c6cb21d1 | 76 | COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) |
d247a5d1 | 77 | { |
d247a5d1 | 78 | } |
d247a5d1 JG |
79 | }; |
80 | ||
51ed9ec9 BD |
81 | uint64_t nLastBlockTx = 0; |
82 | uint64_t nLastBlockSize = 0; | |
d247a5d1 | 83 | |
c6cb21d1 GA |
84 | // We want to sort transactions by priority and fee rate, so: |
85 | typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority; | |
d247a5d1 JG |
86 | class TxPriorityCompare |
87 | { | |
88 | bool byFee; | |
e9e70b95 | 89 | |
d247a5d1 JG |
90 | public: |
91 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
e9e70b95 | 92 | |
d247a5d1 JG |
93 | bool operator()(const TxPriority& a, const TxPriority& b) |
94 | { | |
95 | if (byFee) | |
96 | { | |
97 | if (a.get<1>() == b.get<1>()) | |
98 | return a.get<0>() < b.get<0>(); | |
99 | return a.get<1>() < b.get<1>(); | |
100 | } | |
101 | else | |
102 | { | |
103 | if (a.get<0>() == b.get<0>()) | |
104 | return a.get<1>() < b.get<1>(); | |
105 | return a.get<0>() < b.get<0>(); | |
106 | } | |
107 | } | |
108 | }; | |
109 | ||
bebe7282 | 110 | void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
22c4272b | 111 | { |
112 | pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); | |
5ead4b17 JG |
113 | |
114 | // Updating time can change work required on testnet: | |
4c902704 | 115 | if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) { |
5ead4b17 | 116 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b86dc980 | 117 | } |
22c4272b | 118 | } |
119 | ||
5416af1d | 120 | #include "komodo_defs.h" |
121 | ||
69767347 | 122 | extern CCriticalSection cs_metrics; |
6e78d3df | 123 | 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 | 124 | extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED; |
5f63373e | 125 | extern bool VERUS_MINTBLOCKS; |
42181656 | 126 | extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[]; |
127 | extern const char *ASSETCHAINS_ALGORITHMS[]; | |
5296a850 | 128 | extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[]; |
7c130297 | 129 | extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; |
b2a98c42 MT |
130 | extern uint160 ASSETCHAINS_CHAINID; |
131 | extern uint160 VERUS_CHAINID; | |
d9f176ac | 132 | extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY; |
292809f7 | 133 | void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len); |
d9f176ac | 134 | |
94a465a6 | 135 | extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; |
f24b36ca | 136 | uint32_t Mining_start,Mining_height; |
28a62b60 | 137 | int32_t My_notaryid = -1; |
8683bd8d | 138 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); |
b4810651 | 139 | int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); |
d63fdb34 | 140 | int32_t komodo_baseid(char *origbase); |
3bc88f14 | 141 | int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); |
29bd53a1 | 142 | int64_t komodo_block_unlocktime(uint32_t nHeight); |
18443f69 | 143 | uint64_t komodo_commission(const CBlock *block); |
d231a6a7 | 144 | 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); |
06f41160 | 145 | int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk); |
496f1fd2 | 146 | int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33); |
7652ed92 | 147 | |
5034d1c1 | 148 | CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake) |
d247a5d1 | 149 | { |
8626f666 | 150 | CScript scriptPubKeyIn(_scriptPubKeyIn); |
06f41160 | 151 | |
152 | CPubKey pk = CPubKey(); | |
153 | std::vector<std::vector<unsigned char>> vAddrs; | |
154 | txnouttype txT; | |
155 | if (Solver(scriptPubKeyIn, txT, vAddrs)) | |
156 | { | |
157 | if (txT == TX_PUBKEY) | |
158 | pk = CPubKey(vAddrs[0]); | |
159 | } | |
160 | ||
9339a0cb | 161 | uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params(); |
2a6a442a | 162 | //fprintf(stderr,"create new block\n"); |
df756d24 | 163 | // Create new block |
16593898 | 164 | if ( gpucount < 0 ) |
165 | gpucount = KOMODO_MAXGPUCOUNT; | |
08c58194 | 166 | std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); |
d247a5d1 | 167 | if(!pblocktemplate.get()) |
1b5b89ba | 168 | { |
169 | fprintf(stderr,"pblocktemplate.get() failure\n"); | |
d247a5d1 | 170 | return NULL; |
1b5b89ba | 171 | } |
d247a5d1 | 172 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience |
12217420 | 173 | |
174 | // set version according to the current tip height, add solution if it is | |
175 | // VerusHash | |
176 | if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH) | |
177 | { | |
178 | pblock->nSolution.resize(Eh200_9.SolutionWidth); | |
179 | } | |
180 | else | |
181 | { | |
182 | pblock->nSolution.clear(); | |
183 | } | |
184 | pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1); | |
185 | ||
186 | // -regtest only: allow overriding block.nVersion with | |
dbca89b7 GA |
187 | // -blockversion=N to test forking scenarios |
188 | if (Params().MineBlocksOnDemand()) | |
189 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); | |
e9e70b95 | 190 | |
4949004d PW |
191 | // Add dummy coinbase tx as first transaction |
192 | pblock->vtx.push_back(CTransaction()); | |
d247a5d1 JG |
193 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
194 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
e9e70b95 | 195 | |
d247a5d1 | 196 | // Largest block you're willing to create: |
ad898b40 | 197 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
198 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
199 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
e9e70b95 | 200 | |
d247a5d1 JG |
201 | // How much of the block should be dedicated to high-priority transactions, |
202 | // included regardless of the fees they pay | |
203 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
204 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
e9e70b95 | 205 | |
d247a5d1 JG |
206 | // Minimum block size you want to create; block will be filled with free transactions |
207 | // until there are no more or the block reaches this size: | |
037b4f14 | 208 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 | 209 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
e9e70b95 | 210 | |
d247a5d1 | 211 | // Collect memory pool transactions into the block |
a372168e | 212 | CAmount nFees = 0; |
df756d24 MT |
213 | |
214 | // we will attempt to spend any cheats we see | |
215 | CTransaction cheatTx; | |
216 | boost::optional<CTransaction> cheatSpend; | |
217 | uint256 cbHash; | |
218 | ||
562852ab | 219 | CBlockIndex* pindexPrev = 0; |
d247a5d1 JG |
220 | { |
221 | LOCK2(cs_main, mempool.cs); | |
562852ab | 222 | pindexPrev = chainActive.LastTip(); |
4b729ec5 | 223 | const int nHeight = pindexPrev->GetHeight() + 1; |
df756d24 MT |
224 | const Consensus::Params &consensusParams = chainparams.GetConsensus(); |
225 | uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams); | |
226 | bool sapling = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING); | |
a0dd01bc | 227 | |
a1d3c6fb | 228 | const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); |
a0dd01bc | 229 | uint32_t proposedTime = GetAdjustedTime(); |
230 | if (proposedTime == nMedianTimePast) | |
231 | { | |
232 | // too fast or stuck, this addresses the too fast issue, while moving | |
233 | // forward as quickly as possible | |
234 | for (int i; i < 100; i++) | |
235 | { | |
236 | proposedTime = GetAdjustedTime(); | |
237 | if (proposedTime == nMedianTimePast) | |
238 | MilliSleep(10); | |
239 | } | |
240 | } | |
241 | pblock->nTime = GetAdjustedTime(); | |
242 | ||
7c70438d | 243 | CCoinsViewCache view(pcoinsTip); |
f9155fec | 244 | uint32_t expired; uint64_t commission; |
6ff77181 | 245 | |
4fc309f0 | 246 | SaplingMerkleTree sapling_tree; |
31a04d28 SB |
247 | assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree)); |
248 | ||
d247a5d1 JG |
249 | // Priority order to process transactions |
250 | list<COrphan> vOrphan; // list memory doesn't move | |
251 | map<uint256, vector<COrphan*> > mapDependers; | |
252 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
e9e70b95 | 253 | |
d247a5d1 JG |
254 | // This vector will be sorted into a priority queue: |
255 | vector<TxPriority> vecPriority; | |
df756d24 MT |
256 | vecPriority.reserve(mempool.mapTx.size() + 1); |
257 | ||
258 | // check if we should add cheat transaction | |
259 | CBlockIndex *ppast; | |
ec8a120b | 260 | CTransaction cb; |
83a426bc | 261 | int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY; |
df756d24 MT |
262 | if (cheatCatcher && |
263 | sapling && chainActive.Height() > 100 && | |
83a426bc | 264 | (ppast = chainActive[cheatHeight]) && |
df756d24 | 265 | ppast->IsVerusPOSBlock() && |
83a426bc | 266 | cheatList.IsHeightOrGreaterInList(cheatHeight)) |
df756d24 MT |
267 | { |
268 | // get the block and see if there is a cheat candidate for the stake tx | |
269 | CBlock b; | |
270 | if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1)) | |
271 | { | |
272 | CTransaction &stakeTx = b.vtx[b.vtx.size() - 1]; | |
273 | ||
274 | if (cheatList.IsCheatInList(stakeTx, &cheatTx)) | |
275 | { | |
276 | // make and sign the cheat transaction to spend the coinbase to our address | |
277 | CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight); | |
278 | ||
73a4cd20 | 279 | uint32_t voutNum; |
280 | // get the first vout with value | |
281 | for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++) | |
282 | { | |
283 | if (b.vtx[0].vout[voutNum].nValue > 0) | |
284 | break; | |
285 | } | |
286 | ||
df756d24 | 287 | // send to the same pub key as the destination of this block reward |
73a4cd20 | 288 | if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx)) |
df756d24 MT |
289 | { |
290 | extern CWallet *pwalletMain; | |
291 | LOCK(pwalletMain->cs_wallet); | |
6c621e0e | 292 | TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight); |
ec8a120b | 293 | cb = b.vtx[0]; |
df756d24 MT |
294 | cbHash = cb.GetHash(); |
295 | ||
296 | bool hasInput = false; | |
297 | for (uint32_t i = 0; i < cb.vout.size(); i++) | |
298 | { | |
299 | // add the spends with the cheat | |
73a4cd20 | 300 | if (cb.vout[i].nValue > 0) |
df756d24 MT |
301 | { |
302 | tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue); | |
303 | hasInput = true; | |
304 | } | |
305 | } | |
306 | ||
307 | if (hasInput) | |
308 | { | |
309 | // this is a send from a t-address to a sapling address, which we don't have an ovk for. | |
310 | // Instead, generate a common one from the HD seed. This ensures the data is | |
311 | // recoverable, at least for us, while keeping it logically separate from the ZIP 32 | |
312 | // Sapling key hierarchy, which the user might not be using. | |
313 | uint256 ovk; | |
314 | HDSeed seed; | |
315 | if (pwalletMain->GetHDSeed(seed)) { | |
316 | ovk = ovkForShieldingFromTaddr(seed); | |
317 | ||
ac2b2404 | 318 | // send everything to Sapling address |
319 | tb.SendChangeTo(cheatCatcher.value(), ovk); | |
320 | ||
2d02c19e | 321 | tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey); |
df756d24 MT |
322 | |
323 | cheatSpend = tb.Build(); | |
df756d24 MT |
324 | } |
325 | } | |
326 | } | |
327 | } | |
328 | } | |
329 | } | |
330 | ||
271326fa | 331 | if (cheatSpend) |
332 | { | |
90cc70cc | 333 | cheatTx = cheatSpend.value(); |
271326fa | 334 | std::list<CTransaction> removed; |
45bb4681 | 335 | mempool.removeConflicts(cheatTx, removed); |
c8700efe | 336 | printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n", |
ec8a120b | 337 | (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str()); |
45bb4681 | 338 | |
339 | // add to mem pool and relay | |
340 | if (myAddtomempool(cheatTx)) | |
341 | { | |
342 | RelayTransaction(cheatTx); | |
343 | } | |
271326fa | 344 | } |
345 | ||
4fa3b13d MT |
346 | // if we are a PBaaS chain, first make sure we don't start prematurely, and if |
347 | // we should make an earned notarization, make it | |
348 | if (!IsVerusActive()) | |
2299bd95 | 349 | { |
4fa3b13d MT |
350 | if (nHeight != 1 || ConnectedChains.IsVerusPBaaSAvailable()) |
351 | { | |
352 | // we are a PBaaS chain, create a notarization, if we would qualify, and add it to the mempool and block | |
353 | CMutableTransaction newNotarizationTx; | |
354 | CTransaction prevTx, crossTx; | |
355 | ChainMerkleMountainView mmv = chainActive.GetMMV(); | |
356 | uint256 mmrRoot = mmv.GetRoot(); | |
357 | if (CreateEarnedNotarization(newNotarizationTx, prevTx, crossTx, nHeight, mmrRoot)) | |
358 | { | |
359 | // we have a valid, earned notarization transaction. we may need to combine it with the coinbase if it is | |
360 | // block #1 | |
361 | } | |
362 | } | |
363 | else | |
364 | { | |
365 | // can't mine block 1 unless we have a connection to Verus and can notarize | |
366 | return NULL; | |
367 | } | |
2299bd95 MT |
368 | } |
369 | ||
271326fa | 370 | // now add transactions from the mem pool |
e328fa32 | 371 | for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); |
4d707d51 | 372 | mi != mempool.mapTx.end(); ++mi) |
d247a5d1 | 373 | { |
e328fa32 | 374 | const CTransaction& tx = mi->GetTx(); |
e9e70b95 | 375 | |
a1d3c6fb | 376 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) |
e9e70b95 | 377 | ? nMedianTimePast |
378 | : pblock->GetBlockTime(); | |
9c034267 | 379 | |
9bb37bf0 | 380 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) |
61f8caf2 | 381 | { |
51376f3c | 382 | //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight)); |
14aa6cc0 | 383 | continue; |
61f8caf2 | 384 | } |
9c034267 | 385 | |
161f617d | 386 | if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) |
6ff77181 | 387 | { |
64b45b71 | 388 | //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 | 389 | continue; |
14aa6cc0 | 390 | } |
df756d24 | 391 | |
d247a5d1 JG |
392 | COrphan* porphan = NULL; |
393 | double dPriority = 0; | |
a372168e | 394 | CAmount nTotalIn = 0; |
d247a5d1 | 395 | bool fMissingInputs = false; |
0cb91a8d | 396 | if (tx.IsCoinImport()) |
d247a5d1 | 397 | { |
0cb91a8d SS |
398 | CAmount nValueIn = GetCoinImportValue(tx); |
399 | nTotalIn += nValueIn; | |
400 | dPriority += (double)nValueIn * 1000; // flat multiplier | |
401 | } else { | |
402 | BOOST_FOREACH(const CTxIn& txin, tx.vin) | |
d247a5d1 | 403 | { |
0cb91a8d SS |
404 | // Read prev transaction |
405 | if (!view.HaveCoins(txin.prevout.hash)) | |
d247a5d1 | 406 | { |
0cb91a8d SS |
407 | // This should never happen; all transactions in the memory |
408 | // pool should connect to either transactions in the chain | |
409 | // or other transactions in the memory pool. | |
410 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
411 | { | |
412 | LogPrintf("ERROR: mempool transaction missing input\n"); | |
413 | if (fDebug) assert("mempool transaction missing input" == 0); | |
414 | fMissingInputs = true; | |
415 | if (porphan) | |
416 | vOrphan.pop_back(); | |
417 | break; | |
418 | } | |
419 | ||
420 | // Has to wait for dependencies | |
421 | if (!porphan) | |
422 | { | |
423 | // Use list for automatic deletion | |
424 | vOrphan.push_back(COrphan(&tx)); | |
425 | porphan = &vOrphan.back(); | |
426 | } | |
427 | mapDependers[txin.prevout.hash].push_back(porphan); | |
428 | porphan->setDependsOn.insert(txin.prevout.hash); | |
429 | nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue; | |
430 | continue; | |
d247a5d1 | 431 | } |
0cb91a8d SS |
432 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
433 | assert(coins); | |
434 | ||
435 | CAmount nValueIn = coins->vout[txin.prevout.n].nValue; | |
436 | nTotalIn += nValueIn; | |
437 | ||
438 | int nConf = nHeight - coins->nHeight; | |
439 | ||
440 | dPriority += (double)nValueIn * nConf; | |
d247a5d1 | 441 | } |
9feb4b9e | 442 | nTotalIn += tx.GetShieldedValueIn(); |
d247a5d1 | 443 | } |
0cb91a8d | 444 | |
d247a5d1 | 445 | if (fMissingInputs) continue; |
e9e70b95 | 446 | |
d6eb2599 | 447 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 448 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 449 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
e9e70b95 | 450 | |
805344dc | 451 | uint256 hash = tx.GetHash(); |
2a72d459 | 452 | mempool.ApplyDeltas(hash, dPriority, nTotalIn); |
e9e70b95 | 453 | |
c6cb21d1 | 454 | CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize); |
e9e70b95 | 455 | |
d247a5d1 JG |
456 | if (porphan) |
457 | { | |
458 | porphan->dPriority = dPriority; | |
c6cb21d1 | 459 | porphan->feeRate = feeRate; |
d247a5d1 JG |
460 | } |
461 | else | |
e328fa32 | 462 | vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); |
d247a5d1 | 463 | } |
df756d24 | 464 | |
d247a5d1 | 465 | // Collect transactions into block |
51ed9ec9 BD |
466 | uint64_t nBlockSize = 1000; |
467 | uint64_t nBlockTx = 0; | |
355ca565 | 468 | int64_t interest; |
d247a5d1 JG |
469 | int nBlockSigOps = 100; |
470 | bool fSortedByFee = (nBlockPrioritySize <= 0); | |
e9e70b95 | 471 | |
d247a5d1 JG |
472 | TxPriorityCompare comparer(fSortedByFee); |
473 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
e9e70b95 | 474 | |
d247a5d1 JG |
475 | while (!vecPriority.empty()) |
476 | { | |
477 | // Take highest priority transaction off the priority queue: | |
478 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 479 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 480 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
e9e70b95 | 481 | |
d247a5d1 JG |
482 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); |
483 | vecPriority.pop_back(); | |
e9e70b95 | 484 | |
d247a5d1 JG |
485 | // Size limits |
486 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
01fda4c1 | 487 | if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx |
61f8caf2 | 488 | { |
51376f3c | 489 | //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize); |
d247a5d1 | 490 | continue; |
61f8caf2 | 491 | } |
e9e70b95 | 492 | |
d247a5d1 JG |
493 | // Legacy limits on sigOps: |
494 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
a4a40a38 | 495 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 496 | { |
51376f3c | 497 | //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 | 498 | continue; |
61f8caf2 | 499 | } |
d247a5d1 | 500 | // Skip free transactions if we're past the minimum block size: |
805344dc | 501 | const uint256& hash = tx.GetHash(); |
2a72d459 | 502 | double dPriorityDelta = 0; |
a372168e | 503 | CAmount nFeeDelta = 0; |
2a72d459 | 504 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 505 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
61f8caf2 | 506 | { |
51376f3c | 507 | //fprintf(stderr,"fee rate skip\n"); |
d247a5d1 | 508 | continue; |
61f8caf2 | 509 | } |
2a72d459 | 510 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
511 | // transactions: |
512 | if (!fSortedByFee && | |
513 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
514 | { | |
515 | fSortedByFee = true; | |
516 | comparer = TxPriorityCompare(fSortedByFee); | |
517 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
518 | } | |
e9e70b95 | 519 | |
d247a5d1 | 520 | if (!view.HaveInputs(tx)) |
61f8caf2 | 521 | { |
51376f3c | 522 | //fprintf(stderr,"dont have inputs\n"); |
d247a5d1 | 523 | continue; |
61f8caf2 | 524 | } |
4b729ec5 | 525 | CAmount nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); |
e9e70b95 | 526 | |
d247a5d1 | 527 | nTxSigOps += GetP2SHSigOpCount(tx, view); |
a4a40a38 | 528 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 529 | { |
51376f3c | 530 | //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 | 531 | continue; |
61f8caf2 | 532 | } |
68f7d1d7 PT |
533 | // Note that flags: we don't want to set mempool/IsStandard() |
534 | // policy here, but we still have to ensure that the block we | |
535 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 536 | CValidationState state; |
6514771a | 537 | PrecomputedTransactionData txdata(tx); |
be126699 | 538 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) |
61f8caf2 | 539 | { |
51376f3c | 540 | //fprintf(stderr,"context failure\n"); |
d247a5d1 | 541 | continue; |
61f8caf2 | 542 | } |
8cb98d91 | 543 | UpdateCoins(tx, view, nHeight); |
d247a5d1 | 544 | |
31a04d28 SB |
545 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
546 | sapling_tree.append(outDescription.cm); | |
547 | } | |
548 | ||
d247a5d1 JG |
549 | // Added |
550 | pblock->vtx.push_back(tx); | |
551 | pblocktemplate->vTxFees.push_back(nTxFees); | |
552 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
553 | nBlockSize += nTxSize; | |
554 | ++nBlockTx; | |
555 | nBlockSigOps += nTxSigOps; | |
556 | nFees += nTxFees; | |
e9e70b95 | 557 | |
d247a5d1 JG |
558 | if (fPrintPriority) |
559 | { | |
3f0813b3 | 560 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 | 561 | } |
e9e70b95 | 562 | |
d247a5d1 JG |
563 | // Add transactions that depend on this one to the priority queue |
564 | if (mapDependers.count(hash)) | |
565 | { | |
566 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
567 | { | |
568 | if (!porphan->setDependsOn.empty()) | |
569 | { | |
570 | porphan->setDependsOn.erase(hash); | |
571 | if (porphan->setDependsOn.empty()) | |
572 | { | |
c6cb21d1 | 573 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
574 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
575 | } | |
576 | } | |
577 | } | |
578 | } | |
579 | } | |
e9e70b95 | 580 | |
d247a5d1 JG |
581 | nLastBlockTx = nBlockTx; |
582 | nLastBlockSize = nBlockSize; | |
d07308d2 | 583 | blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); |
9a0f2798 | 584 | //pblock->nTime = blocktime + 1; |
135fa24e | 585 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
586 | ||
86e31e3d | 587 | int32_t stakeHeight = chainActive.Height() + 1; |
86e31e3d | 588 | |
7dbeae5d | 589 | //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits); |
135fa24e | 590 | if ( ASSETCHAINS_SYMBOL[0] != 0 && isStake ) |
a4a40a38 | 591 | { |
1f722359 | 592 | uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr; |
86e31e3d | 593 | CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), stakeHeight); |
1f722359 | 594 | |
cfb55edb | 595 | //if ( blocktime > pindexPrev->GetMedianTimePast()+60 ) |
596 | // blocktime = pindexPrev->GetMedianTimePast() + 60; | |
1f722359 MT |
597 | if (ASSETCHAINS_LWMAPOS != 0) |
598 | { | |
599 | uint32_t nBitsPOS; | |
600 | arith_uint256 posHash; | |
17d0160a | 601 | |
06f41160 | 602 | siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk); |
1f722359 | 603 | blocktime = GetAdjustedTime(); |
cd230e37 MT |
604 | |
605 | // change the scriptPubKeyIn to the same output script exactly as the staking transaction | |
606 | if (siglen > 0) | |
607 | scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey); | |
1f722359 MT |
608 | } |
609 | else | |
610 | { | |
5034d1c1 | 611 | siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig); |
1f722359 MT |
612 | } |
613 | ||
614 | if ( siglen > 0 ) | |
a4a40a38 | 615 | { |
86e31e3d | 616 | CAmount txfees; |
617 | ||
618 | // after Sapling, stake transactions have a fee, but it is recovered in the reward | |
619 | // this ensures that a rebroadcast goes through quickly to begin staking again | |
df756d24 | 620 | txfees = sapling ? DEFAULT_STAKE_TXFEE : 0; |
86e31e3d | 621 | |
a4a40a38 | 622 | pblock->vtx.push_back(txStaked); |
a4a40a38 | 623 | pblocktemplate->vTxFees.push_back(txfees); |
d231a6a7 | 624 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked)); |
a4a40a38 | 625 | nFees += txfees; |
9339a0cb | 626 | pblock->nTime = blocktime; |
4b729ec5 | 627 | //printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.LastTip()->GetHeight()+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13))); |
9464ac21 | 628 | } else return(0); //fprintf(stderr,"no utxos eligible for staking\n"); |
a4a40a38 | 629 | } |
e9e70b95 | 630 | |
f3ffa3d2 | 631 | // Create coinbase tx |
df756d24 | 632 | CMutableTransaction txNew = CreateNewContextualCMutableTransaction(consensusParams, nHeight); |
f3ffa3d2 SB |
633 | txNew.vin.resize(1); |
634 | txNew.vin[0].prevout.SetNull(); | |
abb90a89 MT |
635 | txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; |
636 | ||
d581f229 | 637 | txNew.vout.resize(1); |
f3ffa3d2 | 638 | txNew.vout[0].scriptPubKey = scriptPubKeyIn; |
df756d24 | 639 | txNew.vout[0].nValue = GetBlockSubsidy(nHeight,consensusParams) + nFees; |
06f41160 | 640 | |
ca4a5f26 | 641 | // once we get to Sapling, enable CC StakeGuard for stake transactions |
df756d24 | 642 | if (isStake && sapling) |
06f41160 | 643 | { |
644 | // if there is a specific destination, use it | |
645 | CTransaction stakeTx = pblock->vtx[pblock->vtx.size() - 1]; | |
646 | CStakeParams p; | |
f3b0d2ab | 647 | if (ValidateStakeTransaction(stakeTx, p, false)) |
06f41160 | 648 | { |
86e31e3d | 649 | if (!p.pk.IsValid() || !MakeGuardedOutput(txNew.vout[0].nValue, p.pk, stakeTx, txNew.vout[0])) |
650 | { | |
651 | fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n"); | |
06f41160 | 652 | return 0; |
86e31e3d | 653 | } |
654 | } | |
655 | else | |
656 | { | |
657 | fprintf(stderr,"CreateNewBlock: invalid stake transaction\n"); | |
658 | return 0; | |
06f41160 | 659 | } |
06f41160 | 660 | } |
661 | ||
9bb37bf0 | 662 | txNew.nExpiryHeight = 0; |
48d800c2 | 663 | txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); |
abb90a89 | 664 | |
e0bc68e6 | 665 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
666 | txNew.vout[0].nValue += 5000; | |
5034d1c1 | 667 | |
29bd53a1 | 668 | // check if coinbase transactions must be time locked at current subsidy and prepend the time lock |
a0dd01bc | 669 | // to transaction if so, cast for GTE operator |
670 | if ((uint64_t)(txNew.vout[0].nValue) >= ASSETCHAINS_TIMELOCKGTE) | |
abb90a89 MT |
671 | { |
672 | int32_t opretlen, p2shlen, scriptlen; | |
29bd53a1 | 673 | CScriptExt opretScript = CScriptExt(); |
abb90a89 MT |
674 | |
675 | txNew.vout.resize(2); | |
676 | ||
29bd53a1 MT |
677 | // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins |
678 | // protected only by the time lock rather than 100% inaccessible | |
679 | opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight)); | |
06f41160 | 680 | if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition()) |
681 | { | |
86e31e3d | 682 | fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
06f41160 | 683 | return 0; |
684 | } | |
685 | ||
686 | opretScript += scriptPubKeyIn; | |
abb90a89 | 687 | |
29bd53a1 MT |
688 | txNew.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript)); |
689 | txNew.vout[1].scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK); | |
abb90a89 | 690 | txNew.vout[1].nValue = 0; |
48d800c2 | 691 | } // timelocks and commissions are currently incompatible due to validation complexity of the combination |
5034d1c1 | 692 | else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) |
c9b1071d | 693 | { |
c000c9ca | 694 | int32_t i; uint8_t *ptr; |
9ed1be03 | 695 | txNew.vout.resize(2); |
696 | txNew.vout[1].nValue = commission; | |
697 | txNew.vout[1].scriptPubKey.resize(35); | |
9feb4b9e | 698 | ptr = (uint8_t *)&txNew.vout[1].scriptPubKey[0]; |
c000c9ca | 699 | ptr[0] = 33; |
700 | for (i=0; i<33; i++) | |
701 | ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i]; | |
702 | ptr[34] = OP_CHECKSIG; | |
146d2aa2 | 703 | //printf("autocreate commision vout\n"); |
c9b1071d | 704 | } |
48d800c2 | 705 | |
4949004d | 706 | pblock->vtx[0] = txNew; |
d247a5d1 | 707 | pblocktemplate->vTxFees[0] = -nFees; |
48d800c2 | 708 | |
1fae37f6 MT |
709 | // if not Verus stake, setup nonce, otherwise, leave it alone |
710 | if (!isStake || ASSETCHAINS_LWMAPOS == 0) | |
711 | { | |
712 | // Randomise nonce | |
713 | arith_uint256 nonce = UintToArith256(GetRandHash()); | |
48d800c2 | 714 | |
1fae37f6 MT |
715 | // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters) |
716 | nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO]; | |
717 | nonce >>= 16; | |
718 | pblock->nNonce = ArithToUint256(nonce); | |
719 | } | |
e9e70b95 | 720 | |
d247a5d1 JG |
721 | // Fill in header |
722 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
31a04d28 | 723 | pblock->hashFinalSaplingRoot = sapling_tree.root(); |
0c8fa56a MT |
724 | |
725 | // all Verus PoS chains need this data in the block at all times | |
726 | if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 ) | |
9a0f2798 | 727 | { |
728 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
1fae37f6 | 729 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
9a0f2798 | 730 | } |
12217420 | 731 | |
d247a5d1 | 732 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
4d068367 | 733 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
af805d53 | 734 | { |
28a62b60 | 735 | uint32_t r; |
496f1fd2 | 736 | CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
fa04bcf3 | 737 | if ( pblock->nTime < pindexPrev->nTime+60 ) |
738 | pblock->nTime = pindexPrev->nTime + 60; | |
16593898 | 739 | if ( gpucount < 33 ) |
28a62b60 | 740 | { |
55566f16 | 741 | uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals; |
28a62b60 | 742 | memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid); |
743 | memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height); | |
744 | memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock); | |
9a146fef | 745 | vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n); |
55566f16 | 746 | memcpy(&r,&randvals,sizeof(r)); |
747 | pblock->nTime += (r % (33 - gpucount)*(33 - gpucount)); | |
28a62b60 | 748 | } |
a893e994 | 749 | if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 ) |
496f1fd2 | 750 | { |
2d79309f | 751 | CAmount txfees = 5000; |
496f1fd2 | 752 | pblock->vtx.push_back(txNotary); |
753 | pblocktemplate->vTxFees.push_back(txfees); | |
754 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary)); | |
755 | nFees += txfees; | |
2d79309f | 756 | pblocktemplate->vTxFees[0] = -nFees; |
c881e52b | 757 | //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees; |
f31815fc | 758 | //fprintf(stderr,"added notaryvin\n"); |
0857c3d5 | 759 | } |
760 | else | |
761 | { | |
762 | fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n"); | |
763 | return(0); | |
764 | } | |
707b061c | 765 | } |
809f2e25 | 766 | else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) |
af805d53 | 767 | { |
8fc79ac9 | 768 | CValidationState state; |
809f2e25 | 769 | //fprintf(stderr,"check validity\n"); |
770 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks | |
8fc79ac9 | 771 | { |
9feb4b9e | 772 | throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
8fc79ac9 | 773 | } |
809f2e25 | 774 | //fprintf(stderr,"valid\n"); |
af805d53 | 775 | } |
d247a5d1 | 776 | } |
2a6a442a | 777 | //fprintf(stderr,"done new block\n"); |
d247a5d1 JG |
778 | return pblocktemplate.release(); |
779 | } | |
32b915c9 | 780 | |
1a31463b | 781 | /* |
e9e70b95 | 782 | #ifdef ENABLE_WALLET |
783 | boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey) | |
784 | #else | |
785 | boost::optional<CScript> GetMinerScriptPubKey() | |
786 | #endif | |
787 | { | |
788 | CKeyID keyID; | |
789 | CBitcoinAddress addr; | |
790 | if (addr.SetString(GetArg("-mineraddress", ""))) { | |
791 | addr.GetKeyID(keyID); | |
792 | } else { | |
793 | #ifdef ENABLE_WALLET | |
794 | CPubKey pubkey; | |
795 | if (!reservekey.GetReservedKey(pubkey)) { | |
796 | return boost::optional<CScript>(); | |
797 | } | |
798 | keyID = pubkey.GetID(); | |
799 | #else | |
800 | return boost::optional<CScript>(); | |
801 | #endif | |
802 | } | |
803 | ||
804 | CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
805 | return scriptPubKey; | |
806 | } | |
807 | ||
808 | #ifdef ENABLE_WALLET | |
809 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) | |
810 | { | |
811 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey); | |
812 | #else | |
813 | CBlockTemplate* CreateNewBlockWithKey() | |
814 | { | |
815 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(); | |
816 | #endif | |
817 | ||
818 | if (!scriptPubKey) { | |
819 | return NULL; | |
820 | } | |
821 | return CreateNewBlock(*scriptPubKey); | |
822 | }*/ | |
acfa0333 | 823 | |
c1de826f JG |
824 | ////////////////////////////////////////////////////////////////////////////// |
825 | // | |
826 | // Internal miner | |
827 | // | |
828 | ||
2cc0a252 | 829 | #ifdef ENABLE_MINING |
c1de826f | 830 | |
d247a5d1 JG |
831 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) |
832 | { | |
833 | // Update nExtraNonce | |
834 | static uint256 hashPrevBlock; | |
835 | if (hashPrevBlock != pblock->hashPrevBlock) | |
836 | { | |
837 | nExtraNonce = 0; | |
838 | hashPrevBlock = pblock->hashPrevBlock; | |
839 | } | |
840 | ++nExtraNonce; | |
4b729ec5 | 841 | unsigned int nHeight = pindexPrev->GetHeight()+1; // Height first in coinbase required for block.version=2 |
4949004d PW |
842 | CMutableTransaction txCoinbase(pblock->vtx[0]); |
843 | txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
844 | assert(txCoinbase.vin[0].scriptSig.size() <= 100); | |
e9e70b95 | 845 | |
4949004d | 846 | pblock->vtx[0] = txCoinbase; |
d247a5d1 JG |
847 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); |
848 | } | |
849 | ||
4a85e067 | 850 | #ifdef ENABLE_WALLET |
acfa0333 WL |
851 | ////////////////////////////////////////////////////////////////////////////// |
852 | // | |
853 | // Internal miner | |
854 | // | |
acfa0333 | 855 | |
5034d1c1 | 856 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake) |
acfa0333 | 857 | { |
9feb4b9e | 858 | CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i; |
d9f176ac | 859 | if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 ) |
860 | { | |
861 | scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG; | |
862 | } | |
863 | else if ( USE_EXTERNAL_PUBKEY != 0 ) | |
998397aa | 864 | { |
7bfc207a | 865 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 866 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 867 | } |
868 | else | |
869 | { | |
f1f6dfbb | 870 | if (!isStake) |
1b5b89ba | 871 | { |
f1f6dfbb | 872 | if (!reservekey.GetReservedKey(pubkey)) |
873 | { | |
874 | return NULL; | |
875 | } | |
876 | scriptPubKey.resize(35); | |
877 | ptr = (uint8_t *)pubkey.begin(); | |
878 | scriptPubKey[0] = 33; | |
879 | for (i=0; i<33; i++) | |
880 | scriptPubKey[i+1] = ptr[i]; | |
881 | scriptPubKey[34] = OP_CHECKSIG; | |
882 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
1b5b89ba | 883 | } |
f6c647ed | 884 | } |
5034d1c1 | 885 | return CreateNewBlock(scriptPubKey, gpucount, isStake); |
acfa0333 WL |
886 | } |
887 | ||
395f10cf | 888 | void komodo_broadcast(CBlock *pblock,int32_t limit) |
889 | { | |
890 | int32_t n = 1; | |
891 | //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
892 | { | |
893 | LOCK(cs_vNodes); | |
894 | BOOST_FOREACH(CNode* pnode, vNodes) | |
895 | { | |
896 | if ( pnode->hSocket == INVALID_SOCKET ) | |
897 | continue; | |
898 | if ( (rand() % n) == 0 ) | |
899 | { | |
900 | pnode->PushMessage("block", *pblock); | |
901 | if ( n++ > limit ) | |
902 | break; | |
903 | } | |
904 | } | |
905 | } | |
906 | //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
907 | } | |
945f015d | 908 | |
269d8ba0 | 909 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
8e8b6d70 JG |
910 | #else |
911 | static bool ProcessBlockFound(CBlock* pblock) | |
912 | #endif // ENABLE_WALLET | |
d247a5d1 | 913 | { |
81212588 | 914 | LogPrintf("%s\n", pblock->ToString()); |
4b729ec5 | 915 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.LastTip()->GetHeight()+1); |
e9e70b95 | 916 | |
d247a5d1 JG |
917 | // Found a solution |
918 | { | |
86131275 | 919 | if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash()) |
ba8419c7 | 920 | { |
921 | uint256 hash; int32_t i; | |
922 | hash = pblock->hashPrevBlock; | |
92266e99 | 923 | for (i=31; i>=0; i--) |
ba8419c7 | 924 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 925 | fprintf(stderr," <- prev (stale)\n"); |
86131275 | 926 | hash = chainActive.LastTip()->GetBlockHash(); |
92266e99 | 927 | for (i=31; i>=0; i--) |
ba8419c7 | 928 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 929 | fprintf(stderr," <- chainTip (stale)\n"); |
e9e70b95 | 930 | |
2e500f50 | 931 | return error("KomodoMiner: generated block is stale"); |
ba8419c7 | 932 | } |
18e72167 | 933 | } |
e9e70b95 | 934 | |
8e8b6d70 | 935 | #ifdef ENABLE_WALLET |
18e72167 | 936 | // Remove key from key pool |
998397aa | 937 | if ( IS_KOMODO_NOTARY == 0 ) |
945f015d | 938 | { |
939 | if (GetArg("-mineraddress", "").empty()) { | |
940 | // Remove key from key pool | |
941 | reservekey.KeepKey(); | |
942 | } | |
8e8b6d70 | 943 | } |
18e72167 | 944 | // Track how many getdata requests this block gets |
438ba9c1 | 945 | //if ( 0 ) |
18e72167 | 946 | { |
d1bc3a75 | 947 | //fprintf(stderr,"lock cs_wallet\n"); |
18e72167 PW |
948 | LOCK(wallet.cs_wallet); |
949 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 | 950 | } |
8e8b6d70 | 951 | #endif |
d1bc3a75 | 952 | //fprintf(stderr,"process new block\n"); |
194ad5b8 | 953 | |
18e72167 PW |
954 | // Process this block the same as if we had received it from another node |
955 | CValidationState state; | |
4b729ec5 | 956 | if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL)) |
2e500f50 | 957 | return error("KomodoMiner: ProcessNewBlock, block not accepted"); |
e9e70b95 | 958 | |
d793f94b | 959 | TrackMinedBlock(pblock->GetHash()); |
395f10cf | 960 | komodo_broadcast(pblock,16); |
d247a5d1 JG |
961 | return true; |
962 | } | |
963 | ||
078f6af1 | 964 | int32_t komodo_baseid(char *origbase); |
a30dd993 | 965 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); |
13691369 | 966 | arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); |
8ee93080 | 967 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
99ba67a0 | 968 | extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC; |
8b51b9e4 | 969 | int32_t roundrobin_delay; |
18443f69 | 970 | arith_uint256 HASHTarget,HASHTarget_POW; |
3363d1c0 | 971 | int32_t komodo_longestchain(); |
078f6af1 | 972 | |
5642c96c | 973 | // wait for peers to connect |
12217420 | 974 | void waitForPeers(const CChainParams &chainparams) |
5642c96c | 975 | { |
976 | if (chainparams.MiningRequiresPeers()) | |
977 | { | |
3da69a31 MT |
978 | bool fvNodesEmpty; |
979 | { | |
00a7120e | 980 | boost::this_thread::interruption_point(); |
3da69a31 MT |
981 | LOCK(cs_vNodes); |
982 | fvNodesEmpty = vNodes.empty(); | |
983 | } | |
3363d1c0 | 984 | int longestchain = komodo_longestchain(); |
985 | int lastlongest = 0; | |
986 | if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight())) | |
3da69a31 | 987 | { |
af2e212d | 988 | int loops = 0, blockDiff = 0, newDiff = 0; |
989 | ||
3da69a31 | 990 | do { |
64d6048f | 991 | if (fvNodesEmpty) |
3da69a31 | 992 | { |
69fa3d0e | 993 | MilliSleep(1000 + rand() % 4000); |
00a7120e | 994 | boost::this_thread::interruption_point(); |
3da69a31 MT |
995 | LOCK(cs_vNodes); |
996 | fvNodesEmpty = vNodes.empty(); | |
af2e212d | 997 | loops = 0; |
998 | blockDiff = 0; | |
3363d1c0 | 999 | lastlongest = 0; |
af2e212d | 1000 | } |
3363d1c0 | 1001 | else if ((newDiff = IsNotInSync()) > 0) |
af2e212d | 1002 | { |
1003 | if (blockDiff != newDiff) | |
1004 | { | |
1005 | blockDiff = newDiff; | |
1006 | } | |
1007 | else | |
1008 | { | |
3363d1c0 | 1009 | if (++loops <= 5) |
af2e212d | 1010 | { |
1011 | MilliSleep(1000); | |
1012 | } | |
1013 | else break; | |
1014 | } | |
3363d1c0 | 1015 | lastlongest = 0; |
1016 | } | |
1017 | else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight()) | |
1018 | { | |
1019 | // the only thing may be that we are seeing a long chain that we'll never get | |
1020 | // don't wait forever | |
1021 | if (lastlongest == 0) | |
1022 | { | |
1023 | MilliSleep(3000); | |
1024 | lastlongest = longestchain; | |
1025 | } | |
3da69a31 | 1026 | } |
af2e212d | 1027 | } while (fvNodesEmpty || IsNotInSync()); |
0ba20651 | 1028 | MilliSleep(100 + rand() % 400); |
3da69a31 | 1029 | } |
5642c96c | 1030 | } |
1031 | } | |
1032 | ||
42181656 | 1033 | #ifdef ENABLE_WALLET |
d7e6718d MT |
1034 | CBlockIndex *get_chainactive(int32_t height) |
1035 | { | |
3c40a9a6 | 1036 | if ( chainActive.LastTip() != 0 ) |
d7e6718d | 1037 | { |
4b729ec5 | 1038 | if ( height <= chainActive.LastTip()->GetHeight() ) |
3c40a9a6 MT |
1039 | { |
1040 | LOCK(cs_main); | |
d7e6718d | 1041 | return(chainActive[height]); |
3c40a9a6 | 1042 | } |
4b729ec5 | 1043 | // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight()); |
d7e6718d MT |
1044 | } |
1045 | //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); | |
1046 | return(0); | |
1047 | } | |
1048 | ||
b2a98c42 MT |
1049 | /* |
1050 | * When called, this checks to see if Verus daemon is running and available. If so, it calls to get the latest | |
1051 | * notarization data and all information necessary to make a notarization transaction for the current chain, or the | |
1052 | * Verus chain. | |
1053 | */ | |
1054 | void static UpdateNotarizationData() | |
1055 | { | |
1056 | ||
1057 | } | |
1058 | ||
135fa24e | 1059 | /* |
1060 | * A separate thread to stake, while the miner threads mine. | |
1061 | */ | |
1062 | void static VerusStaker(CWallet *pwallet) | |
1063 | { | |
1064 | LogPrintf("Verus staker thread started\n"); | |
1065 | RenameThread("verus-staker"); | |
1066 | ||
1067 | const CChainParams& chainparams = Params(); | |
2d02c19e | 1068 | auto consensusParams = chainparams.GetConsensus(); |
135fa24e | 1069 | |
1070 | // Each thread has its own key | |
1071 | CReserveKey reservekey(pwallet); | |
1072 | ||
1073 | // Each thread has its own counter | |
1074 | unsigned int nExtraNonce = 0; | |
12217420 | 1075 | |
135fa24e | 1076 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
1077 | ||
4b729ec5 | 1078 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
135fa24e | 1079 | { |
1080 | sleep(1); | |
1081 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
1082 | break; | |
1083 | } | |
1084 | ||
1085 | // try a nice clean peer connection to start | |
bf9c36f4 MT |
1086 | CBlockIndex *pindexPrev, *pindexCur; |
1087 | do { | |
1088 | pindexPrev = chainActive.LastTip(); | |
1089 | MilliSleep(5000 + rand() % 5000); | |
1090 | waitForPeers(chainparams); | |
1091 | pindexCur = chainActive.LastTip(); | |
1092 | } while (pindexPrev != pindexCur); | |
c132b91a | 1093 | |
135fa24e | 1094 | try { |
0fc0dc56 | 1095 | static int32_t lastStakingHeight = 0; |
1096 | ||
135fa24e | 1097 | while (true) |
1098 | { | |
135fa24e | 1099 | waitForPeers(chainparams); |
4ca6678c | 1100 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
135fa24e | 1101 | |
b2a98c42 MT |
1102 | // TODO: update notarization data if this is a PBaaS chain, and there is a Verus daemon available |
1103 | ||
135fa24e | 1104 | // Create new block |
1105 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
0fc0dc56 | 1106 | |
4b729ec5 | 1107 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
135fa24e | 1108 | { |
4b729ec5 | 1109 | Mining_height = pindexPrev->GetHeight()+1; |
135fa24e | 1110 | Mining_start = (uint32_t)time(NULL); |
1111 | } | |
1112 | ||
0fc0dc56 | 1113 | if ( Mining_height != lastStakingHeight ) |
1114 | { | |
1115 | printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL); | |
1116 | lastStakingHeight = Mining_height; | |
1117 | } | |
1118 | ||
1fae37f6 MT |
1119 | // Check for stop or if block needs to be rebuilt |
1120 | boost::this_thread::interruption_point(); | |
1121 | ||
135fa24e | 1122 | // try to stake a block |
1fae37f6 MT |
1123 | CBlockTemplate *ptr = NULL; |
1124 | if (Mining_height > VERUS_MIN_STAKEAGE) | |
5034d1c1 | 1125 | ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true); |
135fa24e | 1126 | |
1127 | if ( ptr == 0 ) | |
1128 | { | |
1fae37f6 | 1129 | // wait to try another staking block until after the tip moves again |
37ad6886 | 1130 | while ( chainActive.LastTip() == pindexPrev ) |
e58fbfb0 | 1131 | MilliSleep(100); |
135fa24e | 1132 | continue; |
1133 | } | |
1134 | ||
1135 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
1136 | if (!pblocktemplate.get()) | |
1137 | { | |
1138 | if (GetArg("-mineraddress", "").empty()) { | |
1fae37f6 | 1139 | LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
135fa24e | 1140 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
1141 | } else { | |
1142 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
1fae37f6 | 1143 | LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
135fa24e | 1144 | } |
1145 | return; | |
1146 | } | |
1147 | ||
1148 | CBlock *pblock = &pblocktemplate->block; | |
1fae37f6 | 1149 | LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
135fa24e | 1150 | // |
1151 | // Search | |
1152 | // | |
1fae37f6 MT |
1153 | int64_t nStart = GetTime(); |
1154 | ||
1155 | // we don't use this, but IncrementExtraNonce is the function that builds the merkle tree | |
1156 | unsigned int nExtraNonce = 0; | |
1157 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); | |
135fa24e | 1158 | |
b2a98c42 MT |
1159 | // update PBaaS header |
1160 | if (CConstVerusSolutionVector::activationHeight.ActiveVersion(Mining_height) == CActivationHeight::SOLUTION_VERUSV3) | |
1161 | { | |
1162 | // set the PBaaS header | |
1163 | uint256 mmvRoot; | |
1164 | { | |
1165 | LOCK(cs_main); | |
1166 | ChainMerkleMountainView mmv(chainActive.GetMMR(), pindexPrev->GetHeight()); | |
1167 | mmvRoot = mmv.GetRoot(); | |
1168 | pblock->AddUpdatePBaaSHeader(mmvRoot); | |
1169 | } | |
1170 | } | |
1171 | ||
1fae37f6 MT |
1172 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
1173 | { | |
1174 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1175 | { | |
1176 | fprintf(stderr,"no nodes, attempting reconnect\n"); | |
1177 | continue; | |
1178 | } | |
1179 | } | |
1180 | ||
1181 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
1182 | { | |
1183 | fprintf(stderr,"timeout, retrying\n"); | |
1184 | continue; | |
1185 | } | |
135fa24e | 1186 | |
37ad6886 | 1187 | if ( pindexPrev != chainActive.LastTip() ) |
135fa24e | 1188 | { |
4b729ec5 | 1189 | printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight()); |
135fa24e | 1190 | MilliSleep(250); |
1191 | continue; | |
1192 | } | |
1193 | ||
1fae37f6 MT |
1194 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
1195 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
135fa24e | 1196 | |
1fae37f6 | 1197 | uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits)); |
135fa24e | 1198 | |
df756d24 | 1199 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b9956efc | 1200 | |
df756d24 | 1201 | UpdateTime(pblock, consensusParams, pindexPrev); |
b9956efc MT |
1202 | |
1203 | ProcessBlockFound(pblock, *pwallet, reservekey); | |
1204 | ||
1fae37f6 MT |
1205 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
1206 | LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
1207 | printf("Found block %d \n", Mining_height ); | |
1208 | printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
b9956efc MT |
1209 | arith_uint256 post; |
1210 | post.SetCompact(pblock->GetVerusPOSTarget()); | |
d7e6718d | 1211 | pindexPrev = get_chainactive(Mining_height - 100); |
d0cd5074 | 1212 | CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1]; |
1213 | printf("POS hash: %s \ntarget: %s\n", | |
1214 | CTransaction::_GetVerusPOSHash(&(pblock->nNonce), sTx.vin[0].prevout.hash, sTx.vin[0].prevout.n, Mining_height, pindexPrev->GetBlockHeader().GetVerusEntropyHash(Mining_height - 100), sTx.vout[0].nValue).GetHex().c_str(), ArithToUint256(post).GetHex().c_str()); | |
1fae37f6 MT |
1215 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
1216 | printf("- timelocked until block %i\n", unlockTime); | |
1217 | else | |
1218 | printf("\n"); | |
135fa24e | 1219 | |
1fae37f6 MT |
1220 | // Check for stop or if block needs to be rebuilt |
1221 | boost::this_thread::interruption_point(); | |
135fa24e | 1222 | |
bf9c36f4 | 1223 | sleep(3); |
3da69a31 | 1224 | |
1fae37f6 MT |
1225 | // In regression test mode, stop mining after a block is found. |
1226 | if (chainparams.MineBlocksOnDemand()) { | |
1227 | throw boost::thread_interrupted(); | |
135fa24e | 1228 | } |
1229 | } | |
1230 | } | |
1231 | catch (const boost::thread_interrupted&) | |
1232 | { | |
135fa24e | 1233 | LogPrintf("VerusStaker terminated\n"); |
1234 | throw; | |
1235 | } | |
1236 | catch (const std::runtime_error &e) | |
1237 | { | |
135fa24e | 1238 | LogPrintf("VerusStaker runtime error: %s\n", e.what()); |
1239 | return; | |
1240 | } | |
135fa24e | 1241 | } |
1242 | ||
fa7fdbc6 | 1243 | typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); |
1244 | bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
1245 | bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
1246 | ||
42181656 | 1247 | void static BitcoinMiner_noeq(CWallet *pwallet) |
1248 | #else | |
1249 | void static BitcoinMiner_noeq() | |
1250 | #endif | |
1251 | { | |
05f6e633 | 1252 | LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
05f6e633 | 1253 | RenameThread("verushash-miner"); |
42181656 | 1254 | |
1255 | #ifdef ENABLE_WALLET | |
1256 | // Each thread has its own key | |
1257 | CReserveKey reservekey(pwallet); | |
1258 | #endif | |
1259 | ||
2910478b | 1260 | const CChainParams& chainparams = Params(); |
42181656 | 1261 | // Each thread has its own counter |
1262 | unsigned int nExtraNonce = 0; | |
12217420 | 1263 | |
42181656 | 1264 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
1265 | ||
4b729ec5 | 1266 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
42181656 | 1267 | { |
1268 | sleep(1); | |
1269 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
1270 | break; | |
1271 | } | |
9f3e2213 | 1272 | |
3da69a31 MT |
1273 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
1274 | ||
5642c96c | 1275 | // try a nice clean peer connection to start |
c132b91a | 1276 | CBlockIndex *pindexPrev, *pindexCur; |
9f3e2213 | 1277 | do { |
37ad6886 | 1278 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 1279 | MilliSleep(5000 + rand() % 5000); |
bf9c36f4 | 1280 | waitForPeers(chainparams); |
37ad6886 | 1281 | pindexCur = chainActive.LastTip(); |
c132b91a | 1282 | } while (pindexPrev != pindexCur); |
6176a421 | 1283 | |
dbe656fe MT |
1284 | // this will not stop printing more than once in all cases, but it will allow us to print in all cases |
1285 | // and print duplicates rarely without having to synchronize | |
1286 | static CBlockIndex *lastChainTipPrinted; | |
90198f71 | 1287 | static int32_t lastMiningHeight = 0; |
9f3e2213 | 1288 | |
42181656 | 1289 | miningTimer.start(); |
1290 | ||
1291 | try { | |
dbe656fe | 1292 | printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
08d46b7f | 1293 | |
08d46b7f | 1294 | // v2 hash writer |
1295 | CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION); | |
1296 | ||
42181656 | 1297 | while (true) |
1298 | { | |
68334c8d | 1299 | miningTimer.stop(); |
1300 | waitForPeers(chainparams); | |
dfcf8255 | 1301 | |
37ad6886 | 1302 | pindexPrev = chainActive.LastTip(); |
12217420 | 1303 | MilliSleep(100); |
dfcf8255 MT |
1304 | |
1305 | // prevent forking on startup before the diff algorithm kicks in | |
12217420 | 1306 | if (chainparams.MiningRequiresPeers() && (pindexPrev->GetHeight() < 50 || pindexPrev != chainActive.LastTip())) |
dfcf8255 MT |
1307 | { |
1308 | do { | |
37ad6886 | 1309 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 1310 | MilliSleep(5000 + rand() % 5000); |
37ad6886 | 1311 | } while (pindexPrev != chainActive.LastTip()); |
dfcf8255 | 1312 | } |
42181656 | 1313 | |
1314 | // Create new block | |
1315 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
4b729ec5 | 1316 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
42181656 | 1317 | { |
4b729ec5 | 1318 | Mining_height = pindexPrev->GetHeight()+1; |
90198f71 | 1319 | if (lastMiningHeight != Mining_height) |
1320 | { | |
1321 | lastMiningHeight = Mining_height; | |
1322 | printf("Mining height %d\n", Mining_height); | |
1323 | } | |
42181656 | 1324 | Mining_start = (uint32_t)time(NULL); |
1325 | } | |
1326 | ||
dbe656fe | 1327 | miningTimer.start(); |
42181656 | 1328 | |
1329 | #ifdef ENABLE_WALLET | |
5034d1c1 | 1330 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0); |
42181656 | 1331 | #else |
1332 | CBlockTemplate *ptr = CreateNewBlockWithKey(); | |
1333 | #endif | |
1334 | if ( ptr == 0 ) | |
1335 | { | |
1336 | static uint32_t counter; | |
1337 | if ( counter++ < 100 ) | |
1338 | fprintf(stderr,"created illegal block, retry\n"); | |
1339 | continue; | |
1340 | } | |
dbe656fe | 1341 | |
42181656 | 1342 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
1343 | if (!pblocktemplate.get()) | |
1344 | { | |
1345 | if (GetArg("-mineraddress", "").empty()) { | |
05f6e633 | 1346 | LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
1347 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
42181656 | 1348 | } else { |
1349 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
05f6e633 | 1350 | LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
42181656 | 1351 | } |
1352 | return; | |
1353 | } | |
1354 | CBlock *pblock = &pblocktemplate->block; | |
1355 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) | |
1356 | { | |
1357 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) | |
1358 | { | |
1359 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1360 | { | |
1361 | static uint32_t counter; | |
1362 | if ( counter++ < 10 ) | |
1363 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
1364 | sleep(10); | |
1365 | continue; | |
1366 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
1367 | } | |
1368 | } | |
b2a98c42 MT |
1369 | |
1370 | // this builds the Merkle tree | |
42181656 | 1371 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
b2a98c42 MT |
1372 | |
1373 | // update PBaaS header | |
1374 | if (CConstVerusSolutionVector::activationHeight.ActiveVersion(Mining_height) == CActivationHeight::SOLUTION_VERUSV3) | |
1375 | { | |
1376 | // set the PBaaS header | |
1377 | uint256 mmvRoot; | |
1378 | { | |
1379 | LOCK(cs_main); | |
1380 | ChainMerkleMountainView mmv(chainActive.GetMMR(), pindexPrev->GetHeight()); | |
1381 | mmvRoot = mmv.GetRoot(); | |
1382 | pblock->AddUpdatePBaaSHeader(mmvRoot); | |
1383 | ||
1384 | // tests to validate a few transactions and all past blocks | |
1385 | for (uint32_t i = 1; i <= pindexPrev->GetHeight(); i += 10) | |
1386 | { | |
1387 | CBlockIndex *pindex = chainActive[i - 1]; | |
1388 | mmv.resize(i); | |
1389 | uint256 testRoot = mmv.GetRoot(); | |
1390 | uint32_t testHeight = ((unsigned char *)&testRoot)[0] < i ? (i - ((unsigned char *)&testRoot)[0]) - 1 : i - 1; | |
1391 | CMerkleBranch branchMerkle, branchBlock; | |
1392 | chainActive.GetBlockProof(mmv, branchBlock, testHeight); | |
1393 | chainActive.GetMerkleProof(mmv, branchMerkle, testHeight); | |
1394 | uint256 merkleAnswer = branchMerkle.SafeCheck(chainActive[testHeight]->hashMerkleRoot); | |
1395 | uint256 blockAnswer = branchBlock.SafeCheck(chainActive[testHeight]->GetBlockHash()); | |
1396 | if (merkleAnswer != testRoot) | |
1397 | { | |
1398 | printf("Failed merkle proof at testheight: %u\nexpected: %s\ncalculated: %s\n", testHeight, testRoot.GetHex().c_str(), merkleAnswer.GetHex().c_str()); | |
1399 | printf("Bits for left (0) and right (1): \n"); | |
1400 | std::vector<unsigned char> proofBits = ChainMerkleMountainView::GetProofBits(testHeight, i); | |
1401 | printf("right\n"); | |
1402 | for (auto bit : proofBits) | |
1403 | { | |
1404 | printf("%s\n", bit ? "left" : "right"); | |
1405 | } | |
1406 | } | |
1407 | if (blockAnswer != testRoot) | |
1408 | { | |
1409 | printf("Failed block proof at testheight: %u\nexpected: %s\ncalculated: %s\n", testHeight, testRoot.GetHex().c_str(), blockAnswer.GetHex().c_str()); | |
1410 | printf("Bits for left (0) and right (1): \n"); | |
1411 | std::vector<unsigned char> proofBits = ChainMerkleMountainView::GetProofBits(testHeight, i); | |
1412 | printf("left\n"); | |
1413 | for (auto bit : proofBits) | |
1414 | { | |
1415 | printf("%s\n", bit ? "left" : "right"); | |
1416 | } | |
1417 | } | |
1418 | const CMMRPowerNode *ppower = mmv.GetRootNode(); | |
1419 | if (!ppower || ppower->Work() != pindex->chainPower.chainWork) | |
1420 | { | |
1421 | printf("Work did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainWork).GetHex().c_str(), ArithToUint256(ppower->Work()).GetHex().c_str()); | |
1422 | } | |
1423 | if (!ppower || ppower->Stake() != pindex->chainPower.chainStake) | |
1424 | { | |
1425 | printf("Stake did not match:\nexpected: %s\ncalculated: %s\n", ArithToUint256(pindex->chainPower.chainStake).GetHex().c_str(), ArithToUint256(ppower->Stake()).GetHex().c_str()); | |
1426 | } | |
1427 | } | |
1428 | } | |
1429 | } | |
1430 | ||
42181656 | 1431 | LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], |
1432 | pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); | |
1433 | // | |
1434 | // Search | |
1435 | // | |
1436 | uint32_t savebits; int64_t nStart = GetTime(); | |
1437 | ||
42181656 | 1438 | savebits = pblock->nBits; |
1439 | arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); | |
fa7fdbc6 | 1440 | uint256 uintTarget = ArithToUint256(hashTarget); |
42181656 | 1441 | Mining_start = 0; |
ef70c5b2 | 1442 | |
37ad6886 | 1443 | if ( pindexPrev != chainActive.LastTip() ) |
05f6e633 | 1444 | { |
37ad6886 | 1445 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 1446 | { |
37ad6886 | 1447 | lastChainTipPrinted = chainActive.LastTip(); |
4b729ec5 | 1448 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 1449 | } |
6176a421 | 1450 | MilliSleep(250); |
05f6e633 | 1451 | continue; |
1452 | } | |
ef70c5b2 | 1453 | |
135fa24e | 1454 | if ( ASSETCHAINS_STAKED != 0 ) |
1455 | { | |
1456 | int32_t percPoS,z; | |
1457 | hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED); | |
1458 | for (z=31; z>=0; z--) | |
1459 | fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); | |
1460 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
1461 | } | |
1462 | ||
b2a98c42 | 1463 | uint64_t count, hashesToGo; |
458bfcab | 1464 | bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2; |
fa7fdbc6 | 1465 | if (!verusHashV2) |
458bfcab | 1466 | { |
fa7fdbc6 | 1467 | // must not be in sync |
1468 | printf("Mining on incorrect block version.\n"); | |
1469 | sleep(2); | |
1470 | continue; | |
458bfcab | 1471 | } |
1472 | ||
fa7fdbc6 | 1473 | count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
db027133 | 1474 | CVerusHashV2 *vh2 = &ss2.GetState(); |
3b500530 | 1475 | u128 *hashKey; |
1476 | verusclhasher &vclh = vh2->vclh; | |
fa7fdbc6 | 1477 | minefunction mine_verus; |
1478 | mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port; | |
f21fad6a | 1479 | |
42181656 | 1480 | while (true) |
1481 | { | |
4dcb64c0 | 1482 | uint256 hashResult = uint256(); |
458bfcab | 1483 | |
e5fb645e | 1484 | unsigned char *curBuf; |
1485 | ||
fa7fdbc6 | 1486 | // check NONCEMASK at a time |
1487 | for (uint64_t i = 0; i < count; i++) | |
42181656 | 1488 | { |
fa7fdbc6 | 1489 | hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
d5040cb1 | 1490 | |
fa7fdbc6 | 1491 | uint64_t start = i * hashesToGo; |
1492 | // hashesToGo gets updated with actual number run for metrics | |
1493 | if (!(*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo)) | |
12217420 | 1494 | { |
fa7fdbc6 | 1495 | // Check for stop or if block needs to be rebuilt |
1496 | boost::this_thread::interruption_point(); | |
1497 | if ( pindexPrev != chainActive.LastTip() ) | |
458bfcab | 1498 | { |
fa7fdbc6 | 1499 | if (lastChainTipPrinted != chainActive.LastTip()) |
1500 | { | |
1501 | lastChainTipPrinted = chainActive.LastTip(); | |
1502 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); | |
1503 | } | |
1504 | break; | |
458bfcab | 1505 | } |
1506 | else | |
1507 | { | |
458bfcab | 1508 | { |
fa7fdbc6 | 1509 | LOCK(cs_metrics); |
1510 | nHashCount += hashesToGo; | |
458bfcab | 1511 | } |
fa7fdbc6 | 1512 | continue; |
458bfcab | 1513 | } |
1514 | } | |
1515 | else | |
42181656 | 1516 | { |
c98efb5a | 1517 | // Check for stop or if block needs to be rebuilt |
1518 | boost::this_thread::interruption_point(); | |
1519 | ||
4dcb64c0 MT |
1520 | if (pblock->nSolution.size() != 1344) |
1521 | { | |
1522 | LogPrintf("ERROR: Block solution is not 1344 bytes as it should be"); | |
4dcb64c0 MT |
1523 | break; |
1524 | } | |
1525 | ||
42181656 | 1526 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
1527 | ||
ef70c5b2 | 1528 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
1529 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
1530 | ||
3363d1c0 | 1531 | #ifdef VERUSHASHDEBUG |
1532 | std::string validateStr = hashResult.GetHex(); | |
1533 | std::string hashStr = pblock->GetHash().GetHex(); | |
1534 | uint256 *bhalf1 = (uint256 *)vh2->CurBuffer(); | |
1535 | uint256 *bhalf2 = bhalf1 + 1; | |
1536 | #else | |
d5040cb1 | 1537 | std::string hashStr = hashResult.GetHex(); |
3363d1c0 | 1538 | #endif |
3af22e67 | 1539 | |
135fa24e | 1540 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
d5040cb1 | 1541 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, hashTarget.GetHex()); |
14d104e9 | 1542 | printf("Found block %d \n", Mining_height ); |
a62041d9 | 1543 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); |
3363d1c0 | 1544 | #ifdef VERUSHASHDEBUG |
1545 | printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), hashTarget.GetHex().c_str()); | |
1546 | printf("intermediate %lx\n", intermediate); | |
3af22e67 | 1547 | printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); |
1b11b9ae | 1548 | bhalf1 = (uint256 *)verusclhasher_key.get(); |
08d46b7f | 1549 | bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5); |
3af22e67 | 1550 | printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); |
3363d1c0 | 1551 | #else |
90198f71 | 1552 | printf(" hash: %s\ntarget: %s", hashStr.c_str(), hashTarget.GetHex().c_str()); |
3363d1c0 | 1553 | #endif |
ef70c5b2 | 1554 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
90198f71 | 1555 | printf(" - timelocked until block %i\n", unlockTime); |
ef70c5b2 | 1556 | else |
1557 | printf("\n"); | |
42181656 | 1558 | #ifdef ENABLE_WALLET |
1559 | ProcessBlockFound(pblock, *pwallet, reservekey); | |
1560 | #else | |
fa7fdbc6 | 1561 | ProcessBlockFound(pblock); |
42181656 | 1562 | #endif |
1563 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
42181656 | 1564 | break; |
1565 | } | |
42181656 | 1566 | } |
1567 | ||
69767347 MT |
1568 | { |
1569 | LOCK(cs_metrics); | |
fa7fdbc6 | 1570 | nHashCount += hashesToGo; |
69767347 MT |
1571 | } |
1572 | ||
42181656 | 1573 | // Check for stop or if block needs to be rebuilt |
1574 | boost::this_thread::interruption_point(); | |
1575 | ||
1576 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
1577 | { | |
1578 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
1579 | { | |
ef70c5b2 | 1580 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
42181656 | 1581 | break; |
1582 | } | |
1583 | } | |
1584 | ||
dbe656fe | 1585 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
42181656 | 1586 | { |
dbe656fe | 1587 | fprintf(stderr,"timeout, retrying\n"); |
42181656 | 1588 | break; |
1589 | } | |
1590 | ||
37ad6886 | 1591 | if ( pindexPrev != chainActive.LastTip() ) |
42181656 | 1592 | { |
37ad6886 | 1593 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 1594 | { |
37ad6886 | 1595 | lastChainTipPrinted = chainActive.LastTip(); |
90198f71 | 1596 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 1597 | } |
42181656 | 1598 | break; |
1599 | } | |
1600 | ||
52cf66e1 | 1601 | #ifdef _WIN32 |
3b02f606 | 1602 | printf("%llu mega hashes complete - working\n", ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / 1048576); |
52cf66e1 | 1603 | #else |
3b02f606 | 1604 | printf("%lu mega hashes complete - working\n", ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / 1048576); |
52cf66e1 | 1605 | #endif |
4dcb64c0 | 1606 | break; |
8682e17a | 1607 | |
42181656 | 1608 | } |
1609 | } | |
1610 | } | |
1611 | catch (const boost::thread_interrupted&) | |
1612 | { | |
1613 | miningTimer.stop(); | |
5034d1c1 | 1614 | LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 1615 | throw; |
1616 | } | |
1617 | catch (const std::runtime_error &e) | |
1618 | { | |
1619 | miningTimer.stop(); | |
5034d1c1 | 1620 | LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what()); |
42181656 | 1621 | return; |
1622 | } | |
1623 | miningTimer.stop(); | |
1624 | } | |
1625 | ||
8e8b6d70 | 1626 | #ifdef ENABLE_WALLET |
d247a5d1 | 1627 | void static BitcoinMiner(CWallet *pwallet) |
8e8b6d70 JG |
1628 | #else |
1629 | void static BitcoinMiner() | |
1630 | #endif | |
d247a5d1 | 1631 | { |
2e500f50 | 1632 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 1633 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 1634 | RenameThread("komodo-miner"); |
bebe7282 | 1635 | const CChainParams& chainparams = Params(); |
e9e70b95 | 1636 | |
8e8b6d70 JG |
1637 | #ifdef ENABLE_WALLET |
1638 | // Each thread has its own key | |
d247a5d1 | 1639 | CReserveKey reservekey(pwallet); |
8e8b6d70 | 1640 | #endif |
e9e70b95 | 1641 | |
8e8b6d70 | 1642 | // Each thread has its own counter |
d247a5d1 | 1643 | unsigned int nExtraNonce = 0; |
e9e70b95 | 1644 | |
e9574728 JG |
1645 | unsigned int n = chainparams.EquihashN(); |
1646 | unsigned int k = chainparams.EquihashK(); | |
16593898 | 1647 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1; |
99ba67a0 | 1648 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) |
755ead98 | 1649 | { |
1650 | sleep(1); | |
4e624c04 | 1651 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
1652 | break; | |
755ead98 | 1653 | } |
32b0978b | 1654 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
4b729ec5 | 1655 | komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); |
28a62b60 | 1656 | if ( notaryid != My_notaryid ) |
1657 | My_notaryid = notaryid; | |
755ead98 | 1658 | std::string solver; |
e1e65cef | 1659 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
e9e70b95 | 1660 | solver = "tromp"; |
e1e65cef | 1661 | //else solver = "default"; |
5f0009b2 | 1662 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 1663 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 1664 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 1665 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
1666 | std::mutex m_cs; |
1667 | bool cancelSolver = false; | |
1668 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
e9e70b95 | 1669 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { |
1670 | std::lock_guard<std::mutex> lock{m_cs}; | |
1671 | cancelSolver = true; | |
1672 | } | |
1673 | ); | |
07be8f7e | 1674 | miningTimer.start(); |
e9e70b95 | 1675 | |
0655fac0 | 1676 | try { |
ad84148d | 1677 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 1678 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 1679 | while (true) |
1680 | { | |
4b729ec5 | 1681 | if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 && |
e725f1cb | 1682 | { |
4b729ec5 | 1683 | //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 ) |
a96fd7b5 | 1684 | // break; |
0655fac0 PK |
1685 | // Busy-wait for the network to come online so we don't waste time mining |
1686 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
07be8f7e | 1687 | miningTimer.stop(); |
bba7c249 GM |
1688 | do { |
1689 | bool fvNodesEmpty; | |
1690 | { | |
373668be | 1691 | //LOCK(cs_vNodes); |
bba7c249 GM |
1692 | fvNodesEmpty = vNodes.empty(); |
1693 | } | |
269fe243 | 1694 | if (!fvNodesEmpty )//&& !IsInitialBlockDownload()) |
bba7c249 | 1695 | break; |
6e78d3df | 1696 | MilliSleep(15000); |
ad84148d | 1697 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
e9e70b95 | 1698 | |
bba7c249 | 1699 | } while (true); |
ad84148d | 1700 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
07be8f7e | 1701 | miningTimer.start(); |
0655fac0 | 1702 | } |
0655fac0 PK |
1703 | // |
1704 | // Create new block | |
1705 | // | |
1706 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
86131275 | 1707 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
4b729ec5 | 1708 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
4940066c | 1709 | { |
4b729ec5 | 1710 | Mining_height = pindexPrev->GetHeight()+1; |
4940066c | 1711 | Mining_start = (uint32_t)time(NULL); |
1712 | } | |
8e9ef91c | 1713 | if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) |
2825c0b5 | 1714 | { |
40304479 | 1715 | //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
5a7fd132 | 1716 | //sleep(3); |
2825c0b5 | 1717 | } |
135fa24e | 1718 | |
8e8b6d70 | 1719 | #ifdef ENABLE_WALLET |
135fa24e | 1720 | // notaries always default to staking |
4b729ec5 | 1721 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); |
8e8b6d70 | 1722 | #else |
945f015d | 1723 | CBlockTemplate *ptr = CreateNewBlockWithKey(); |
8e8b6d70 | 1724 | #endif |
08d0b73c | 1725 | if ( ptr == 0 ) |
1726 | { | |
d0f7ead0 | 1727 | static uint32_t counter; |
5bb3d0fe | 1728 | if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) |
1b5b89ba | 1729 | fprintf(stderr,"created illegal block, retry\n"); |
8fc79ac9 | 1730 | sleep(1); |
d0f7ead0 | 1731 | continue; |
08d0b73c | 1732 | } |
2a6a442a | 1733 | //fprintf(stderr,"get template\n"); |
08d0b73c | 1734 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
0655fac0 | 1735 | if (!pblocktemplate.get()) |
6c37f7fd | 1736 | { |
8e8b6d70 | 1737 | if (GetArg("-mineraddress", "").empty()) { |
945f015d | 1738 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
8e8b6d70 JG |
1739 | } else { |
1740 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
945f015d | 1741 | LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n"); |
8e8b6d70 | 1742 | } |
0655fac0 | 1743 | return; |
6c37f7fd | 1744 | } |
0655fac0 | 1745 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 1746 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
1747 | { | |
42181656 | 1748 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) |
16c7bf6b | 1749 | { |
8683bd8d | 1750 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
1751 | { | |
1752 | static uint32_t counter; | |
1753 | if ( counter++ < 10 ) | |
1754 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
1755 | sleep(10); | |
1756 | continue; | |
1757 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
1758 | } | |
16c7bf6b | 1759 | } |
0655fac0 | 1760 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2a6a442a | 1761 | //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size()); |
2e500f50 | 1762 | 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 |
1763 | // |
1764 | // Search | |
1765 | // | |
2ba9de01 | 1766 | 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 | 1767 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
404391b5 | 1768 | savebits = pblock->nBits; |
d5614a76 | 1769 | HASHTarget = arith_uint256().SetCompact(savebits); |
f0100e72 | 1770 | roundrobin_delay = ROUNDROBIN_DELAY; |
3e7e3109 | 1771 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 ) |
5203fc4b | 1772 | { |
fda5f849 | 1773 | j = 65; |
67df454d | 1774 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) |
fb6c7505 | 1775 | { |
4fff8a63 | 1776 | int32_t dispflag = 0; |
ef70c5b2 | 1777 | if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) |
4fff8a63 | 1778 | dispflag = 1; |
4b729ec5 | 1779 | komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); |
29e60e48 | 1780 | if ( nonzpkeys > 0 ) |
1781 | { | |
ccb71a6e | 1782 | for (i=0; i<33; i++) |
1783 | if( pubkeys[0][i] != 0 ) | |
1784 | break; | |
1785 | if ( i == 33 ) | |
1786 | externalflag = 1; | |
1787 | else externalflag = 0; | |
4d068367 | 1788 | if ( IS_KOMODO_NOTARY != 0 ) |
b176c125 | 1789 | { |
345e545e | 1790 | for (i=1; i<66; i++) |
1791 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
1792 | break; | |
6494f040 | 1793 | if ( externalflag == 0 && i != 66 && mids[i] >= 0 ) |
1794 | printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]); | |
2c7ad758 | 1795 | for (j=gpucount=0; j<65; j++) |
1796 | { | |
4fff8a63 | 1797 | if ( dispflag != 0 ) |
e4a383e3 | 1798 | { |
1799 | if ( mids[j] >= 0 ) | |
1800 | fprintf(stderr,"%d ",mids[j]); | |
1801 | else fprintf(stderr,"GPU "); | |
1802 | } | |
2c7ad758 | 1803 | if ( mids[j] == -1 ) |
1804 | gpucount++; | |
1805 | } | |
4fff8a63 | 1806 | if ( dispflag != 0 ) |
4b729ec5 | 1807 | fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->GetHeight(),notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL)); |
b176c125 | 1808 | } |
29e60e48 | 1809 | for (j=0; j<65; j++) |
1810 | if ( mids[j] == notaryid ) | |
1811 | break; | |
49b49585 | 1812 | if ( j == 65 ) |
1813 | KOMODO_LASTMINED = 0; | |
965f0f7e | 1814 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 1815 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 1816 | { |
88287857 | 1817 | HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); |
4b729ec5 | 1818 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1); |
fda5f849 | 1819 | } //else fprintf(stderr,"duplicate at j.%d\n",j); |
fb6c7505 | 1820 | } else Mining_start = 0; |
d7d27bb3 | 1821 | } else Mining_start = 0; |
2ba9de01 | 1822 | if ( ASSETCHAINS_STAKED != 0 ) |
e725f1cb | 1823 | { |
ed3d0a05 | 1824 | int32_t percPoS,z; bool fNegative,fOverflow; |
18443f69 | 1825 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
f108acf9 | 1826 | HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); |
f2c1ac06 | 1827 | if ( ASSETCHAINS_STAKED < 100 ) |
1828 | { | |
1829 | for (z=31; z>=0; z--) | |
1830 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); | |
1831 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
1832 | } | |
deba7f20 | 1833 | } |
e725f1cb | 1834 | while (true) |
1835 | { | |
99ba67a0 | 1836 | if ( KOMODO_INSYNC == 0 ) |
1837 | { | |
e9d56b2c | 1838 | fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); |
1839 | if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) | |
a02c45db | 1840 | KOMODO_INSYNC = 1; |
99ba67a0 | 1841 | sleep(3); |
1842 | } | |
7213c0b1 | 1843 | // Hash state |
8c22eb46 | 1844 | KOMODO_CHOSEN_ONE = 0; |
42181656 | 1845 | |
7213c0b1 | 1846 | crypto_generichash_blake2b_state state; |
e9574728 | 1847 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
1848 | // I = the block header minus nonce and solution. |
1849 | CEquihashInput I{*pblock}; | |
1850 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
1851 | ss << I; | |
7213c0b1 JG |
1852 | // H(I||... |
1853 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
1854 | // H(I||V||... |
1855 | crypto_generichash_blake2b_state curr_state; | |
1856 | curr_state = state; | |
7a4c01c9 | 1857 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 1858 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 1859 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
18443f69 | 1860 | arith_uint256 hashTarget; |
6e78d3df | 1861 | if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 ) |
18443f69 | 1862 | hashTarget = HASHTarget_POW; |
1863 | else hashTarget = HASHTarget; | |
5be6abbf | 1864 | std::function<bool(std::vector<unsigned char>)> validBlock = |
8e8b6d70 | 1865 | #ifdef ENABLE_WALLET |
e9e70b95 | 1866 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 1867 | #else |
e9e70b95 | 1868 | [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 1869 | #endif |
e9e70b95 | 1870 | (std::vector<unsigned char> soln) { |
c21c6306 | 1871 | int32_t z; arith_uint256 h; CBlock B; |
51eb5273 JG |
1872 | // Write the solution to the hash and compute the result. |
1873 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 1874 | pblock->nSolution = soln; |
e7d59bbc | 1875 | solutionTargetChecks.increment(); |
eff2c3a3 | 1876 | B = *pblock; |
1877 | h = UintToArith256(B.GetHash()); | |
eff2c3a3 | 1878 | /*for (z=31; z>=16; z--) |
02c30aac | 1879 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); |
aea2d1aa | 1880 | fprintf(stderr," mined "); |
1881 | for (z=31; z>=16; z--) | |
18443f69 | 1882 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); |
aea2d1aa | 1883 | fprintf(stderr," hashTarget "); |
1884 | for (z=31; z>=16; z--) | |
18443f69 | 1885 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); |
eff2c3a3 | 1886 | fprintf(stderr," POW\n");*/ |
265f4e96 | 1887 | if ( h > hashTarget ) |
40df8d84 | 1888 | { |
6e78d3df | 1889 | //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 ) |
afa90f17 | 1890 | // sleep(1); |
265f4e96 | 1891 | return false; |
40df8d84 | 1892 | } |
41e9c815 | 1893 | if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() ) |
d7d27bb3 | 1894 | { |
45ee62cb | 1895 | //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime())); |
596b05ba | 1896 | while ( GetAdjustedTime() < B.nTime-2 ) |
8e9ef91c | 1897 | { |
eb1ba5a0 | 1898 | sleep(1); |
4b729ec5 | 1899 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
4cc387ec | 1900 | { |
1901 | fprintf(stderr,"new block arrived\n"); | |
1902 | return(false); | |
1903 | } | |
8e9ef91c | 1904 | } |
eb1ba5a0 | 1905 | } |
8e9ef91c | 1906 | if ( ASSETCHAINS_STAKED == 0 ) |
d7d27bb3 | 1907 | { |
4d068367 | 1908 | if ( IS_KOMODO_NOTARY != 0 ) |
8e9ef91c | 1909 | { |
26810a26 | 1910 | int32_t r; |
9703f8a0 | 1911 | if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 ) |
596b05ba | 1912 | MilliSleep((rand() % (r * 1000)) + 1000); |
ef70c5b2 | 1913 | } |
e5430f52 | 1914 | } |
8e9ef91c | 1915 | else |
d7d27bb3 | 1916 | { |
0c35569b | 1917 | while ( B.nTime-57 > GetAdjustedTime() ) |
deba7f20 | 1918 | { |
afa90f17 | 1919 | sleep(1); |
4b729ec5 | 1920 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
afa90f17 | 1921 | return(false); |
68d0354d | 1922 | } |
4d068367 | 1923 | uint256 tmp = B.GetHash(); |
1924 | int32_t z; for (z=31; z>=0; z--) | |
1925 | fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); | |
01e50e73 | 1926 | fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height); |
d7d27bb3 | 1927 | } |
8fc79ac9 | 1928 | CValidationState state; |
86131275 | 1929 | if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false)) |
d2d3c766 | 1930 | { |
8fc79ac9 | 1931 | h = UintToArith256(B.GetHash()); |
1932 | for (z=31; z>=0; z--) | |
1933 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); | |
1934 | fprintf(stderr," Invalid block mined, try again\n"); | |
1935 | return(false); | |
d2d3c766 | 1936 | } |
b3183e3e | 1937 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
1938 | // Found a solution |
1939 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 1940 | LogPrintf("KomodoMiner:\n"); |
eff2c3a3 | 1941 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); |
8e8b6d70 | 1942 | #ifdef ENABLE_WALLET |
eff2c3a3 | 1943 | if (ProcessBlockFound(&B, *pwallet, reservekey)) { |
8e8b6d70 | 1944 | #else |
eff2c3a3 | 1945 | if (ProcessBlockFound(&B)) { |
8e8b6d70 | 1946 | #endif |
e9e70b95 | 1947 | // Ignore chain updates caused by us |
1948 | std::lock_guard<std::mutex> lock{m_cs}; | |
1949 | cancelSolver = false; | |
1950 | } | |
1951 | KOMODO_CHOSEN_ONE = 0; | |
1952 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
1953 | // In regression test mode, stop mining after a block is found. | |
1954 | if (chainparams.MineBlocksOnDemand()) { | |
1955 | // Increment here because throwing skips the call below | |
1956 | ehSolverRuns.increment(); | |
1957 | throw boost::thread_interrupted(); | |
1958 | } | |
e9e70b95 | 1959 | return true; |
1960 | }; | |
1961 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
a6a0d913 | 1962 | std::lock_guard<std::mutex> lock{m_cs}; |
e9e70b95 | 1963 | return cancelSolver; |
1964 | }; | |
1965 | ||
1966 | // TODO: factor this out into a function with the same API for each solver. | |
1967 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { | |
1968 | // Create solver and initialize it. | |
1969 | equi eq(1); | |
1970 | eq.setstate(&curr_state); | |
1971 | ||
1972 | // Initialization done, start algo driver. | |
1973 | eq.digit0(0); | |
c7aaab7a | 1974 | eq.xfull = eq.bfull = eq.hfull = 0; |
e9e70b95 | 1975 | eq.showbsizes(0); |
1976 | for (u32 r = 1; r < WK; r++) { | |
1977 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
1978 | eq.xfull = eq.bfull = eq.hfull = 0; | |
1979 | eq.showbsizes(r); | |
c7aaab7a | 1980 | } |
e9e70b95 | 1981 | eq.digitK(0); |
1982 | ehSolverRuns.increment(); | |
1983 | ||
1984 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
1985 | for (size_t s = 0; s < eq.nsols; s++) { | |
1986 | LogPrint("pow", "Checking solution %d\n", s+1); | |
1987 | std::vector<eh_index> index_vector(PROOFSIZE); | |
1988 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
1989 | index_vector[i] = eq.sols[s][i]; | |
1990 | } | |
1991 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
1992 | ||
1993 | if (validBlock(sol_char)) { | |
1994 | // If we find a POW solution, do not try other solutions | |
1995 | // because they become invalid as we created a new block in blockchain. | |
1996 | break; | |
1997 | } | |
1998 | } | |
1999 | } else { | |
2000 | try { | |
2001 | // If we find a valid block, we rebuild | |
2002 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); | |
2003 | ehSolverRuns.increment(); | |
2004 | if (found) { | |
997ddd92 | 2005 | int32_t i; uint256 hash = pblock->GetHash(); |
e9e70b95 | 2006 | for (i=0; i<32; i++) |
2007 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
2008 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
2009 | FOUND_BLOCK = 1; | |
2010 | KOMODO_MAYBEMINED = Mining_height; | |
2011 | break; | |
2012 | } | |
2013 | } catch (EhSolverCancelledException&) { | |
2014 | LogPrint("pow", "Equihash solver cancelled\n"); | |
2015 | std::lock_guard<std::mutex> lock{m_cs}; | |
2016 | cancelSolver = false; | |
c7aaab7a DH |
2017 | } |
2018 | } | |
e9e70b95 | 2019 | |
2020 | // Check for stop or if block needs to be rebuilt | |
2021 | boost::this_thread::interruption_point(); | |
2022 | // Regtest mode doesn't require peers | |
2023 | if ( FOUND_BLOCK != 0 ) | |
2024 | { | |
2025 | FOUND_BLOCK = 0; | |
2026 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
2027 | //sleep(2000); | |
2028 | } | |
2029 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
2030 | { | |
2031 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2032 | { | |
2033 | fprintf(stderr,"no nodes, break\n"); | |
c7aaab7a | 2034 | break; |
a6df7ab5 | 2035 | } |
c7aaab7a | 2036 | } |
997ddd92 | 2037 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
10694486 | 2038 | { |
e9e70b95 | 2039 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
2040 | fprintf(stderr,"0xffff, break\n"); | |
d90cef0b | 2041 | break; |
10694486 | 2042 | } |
e9e70b95 | 2043 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
2044 | { | |
2045 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
2046 | fprintf(stderr,"timeout, break\n"); | |
2047 | break; | |
2048 | } | |
86131275 | 2049 | if ( pindexPrev != chainActive.LastTip() ) |
e9e70b95 | 2050 | { |
2051 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
2052 | fprintf(stderr,"Tip advanced, break\n"); | |
2053 | break; | |
2054 | } | |
2055 | // Update nNonce and nTime | |
2056 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
2057 | pblock->nBits = savebits; | |
18dd6a3b | 2058 | /*if ( NOTARY_PUBKEY33[0] == 0 ) |
e9e70b95 | 2059 | { |
f8f740a9 | 2060 | int32_t percPoS; |
df756d24 MT |
2061 | UpdateTime(pblock, consensusParams, pindexPrev); |
2062 | if (consensusParams.fPowAllowMinDifficultyBlocks) | |
23fc88bb | 2063 | { |
2064 | // Changing pblock->nTime can change work required on testnet: | |
2065 | HASHTarget.SetCompact(pblock->nBits); | |
18443f69 | 2066 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
23fc88bb | 2067 | } |
18dd6a3b | 2068 | }*/ |
48265f3c | 2069 | } |
d247a5d1 JG |
2070 | } |
2071 | } | |
e9e70b95 | 2072 | catch (const boost::thread_interrupted&) |
2073 | { | |
2074 | miningTimer.stop(); | |
2075 | c.disconnect(); | |
2076 | LogPrintf("KomodoMiner terminated\n"); | |
2077 | throw; | |
2078 | } | |
2079 | catch (const std::runtime_error &e) | |
2080 | { | |
2081 | miningTimer.stop(); | |
2082 | c.disconnect(); | |
2083 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); | |
2084 | return; | |
2085 | } | |
07be8f7e | 2086 | miningTimer.stop(); |
5e9b555f | 2087 | c.disconnect(); |
bba7c249 | 2088 | } |
e9e70b95 | 2089 | |
8e8b6d70 | 2090 | #ifdef ENABLE_WALLET |
e9e70b95 | 2091 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
8e8b6d70 | 2092 | #else |
e9e70b95 | 2093 | void GenerateBitcoins(bool fGenerate, int nThreads) |
8e8b6d70 | 2094 | #endif |
d247a5d1 | 2095 | { |
10214558 | 2096 | // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at |
2097 | // initialization, and this is the first time we can get it. store the Sapling address here | |
2098 | extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher; | |
2099 | extern std::string VERUS_CHEATCATCHER; | |
2100 | libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER); | |
2101 | if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr)) | |
2102 | { | |
99c94fc3 | 2103 | try |
2104 | { | |
2105 | cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr); | |
2106 | } | |
2107 | catch (...) | |
2108 | { | |
2109 | } | |
10214558 | 2110 | } |
bd6639fd | 2111 | |
b20c38cc | 2112 | VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0); |
bd6639fd | 2113 | |
89cd7b59 | 2114 | if (fGenerate == true || VERUS_MINTBLOCKS) |
10214558 | 2115 | { |
89cd7b59 MT |
2116 | mapArgs["-gen"] = "1"; |
2117 | ||
2118 | if (VERUS_CHEATCATCHER.size() > 0) | |
99c94fc3 | 2119 | { |
89cd7b59 MT |
2120 | if (cheatCatcher == boost::none) |
2121 | { | |
2122 | LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n"); | |
2123 | fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n"); | |
2124 | } | |
2125 | else | |
2126 | { | |
2127 | LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
2128 | fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
2129 | } | |
99c94fc3 | 2130 | } |
2131 | } | |
10214558 | 2132 | |
e9e70b95 | 2133 | static boost::thread_group* minerThreads = NULL; |
28424e9f | 2134 | |
e9e70b95 | 2135 | if (nThreads < 0) |
2136 | nThreads = GetNumCores(); | |
2137 | ||
2138 | if (minerThreads != NULL) | |
2139 | { | |
2140 | minerThreads->interrupt_all(); | |
2141 | delete minerThreads; | |
2142 | minerThreads = NULL; | |
2143 | } | |
135fa24e | 2144 | |
afaeb54b | 2145 | //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate); |
5034d1c1 | 2146 | if ( nThreads == 0 && ASSETCHAINS_STAKED ) |
3a446d9f | 2147 | nThreads = 1; |
5034d1c1 | 2148 | |
28424e9f | 2149 | if (!fGenerate) |
e9e70b95 | 2150 | return; |
135fa24e | 2151 | |
e9e70b95 | 2152 | minerThreads = new boost::thread_group(); |
135fa24e | 2153 | |
2154 | #ifdef ENABLE_WALLET | |
b20c38cc | 2155 | if (VERUS_MINTBLOCKS && pwallet != NULL) |
135fa24e | 2156 | { |
2157 | minerThreads->create_thread(boost::bind(&VerusStaker, pwallet)); | |
2158 | } | |
2159 | #endif | |
2160 | ||
e9e70b95 | 2161 | for (int i = 0; i < nThreads; i++) { |
135fa24e | 2162 | |
8e8b6d70 | 2163 | #ifdef ENABLE_WALLET |
135fa24e | 2164 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
2165 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
2166 | else | |
2167 | minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet)); | |
8e8b6d70 | 2168 | #else |
135fa24e | 2169 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
2170 | minerThreads->create_thread(&BitcoinMiner); | |
2171 | else | |
2172 | minerThreads->create_thread(&BitcoinMiner_noeq); | |
8e8b6d70 | 2173 | #endif |
e9e70b95 | 2174 | } |
8e8b6d70 | 2175 | } |
e9e70b95 | 2176 | |
2cc0a252 | 2177 | #endif // ENABLE_MINING |