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