]>
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" | |
e7e14f44 | 52 | #include "rpc/pbaasrpc.h" |
13ed2980 | 53 | #include "transaction_builder.h" |
2299bd95 | 54 | |
09eb201b | 55 | using namespace std; |
7b4737c8 | 56 | |
d247a5d1 JG |
57 | ////////////////////////////////////////////////////////////////////////////// |
58 | // | |
59 | // BitcoinMiner | |
60 | // | |
61 | ||
c6cb21d1 GA |
62 | // |
63 | // Unconfirmed transactions in the memory pool often depend on other | |
64 | // transactions in the memory pool. When we select transactions from the | |
65 | // pool, we select by highest priority or fee rate, so we might consider | |
66 | // transactions that depend on transactions that aren't yet in the block. | |
67 | // The COrphan class keeps track of these 'temporary orphans' while | |
68 | // CreateBlock is figuring out which transactions to include. | |
69 | // | |
d247a5d1 JG |
70 | class COrphan |
71 | { | |
72 | public: | |
4d707d51 | 73 | const CTransaction* ptx; |
d247a5d1 | 74 | set<uint256> setDependsOn; |
c6cb21d1 | 75 | CFeeRate feeRate; |
02bec4b2 | 76 | double dPriority; |
e9e70b95 | 77 | |
c6cb21d1 | 78 | COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) |
d247a5d1 | 79 | { |
d247a5d1 | 80 | } |
d247a5d1 JG |
81 | }; |
82 | ||
51ed9ec9 BD |
83 | uint64_t nLastBlockTx = 0; |
84 | uint64_t nLastBlockSize = 0; | |
d247a5d1 | 85 | |
c6cb21d1 GA |
86 | // We want to sort transactions by priority and fee rate, so: |
87 | typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority; | |
d247a5d1 JG |
88 | class TxPriorityCompare |
89 | { | |
90 | bool byFee; | |
e9e70b95 | 91 | |
d247a5d1 JG |
92 | public: |
93 | TxPriorityCompare(bool _byFee) : byFee(_byFee) { } | |
e9e70b95 | 94 | |
d247a5d1 JG |
95 | bool operator()(const TxPriority& a, const TxPriority& b) |
96 | { | |
97 | if (byFee) | |
98 | { | |
99 | if (a.get<1>() == b.get<1>()) | |
100 | return a.get<0>() < b.get<0>(); | |
101 | return a.get<1>() < b.get<1>(); | |
102 | } | |
103 | else | |
104 | { | |
105 | if (a.get<0>() == b.get<0>()) | |
106 | return a.get<1>() < b.get<1>(); | |
107 | return a.get<0>() < b.get<0>(); | |
108 | } | |
109 | } | |
110 | }; | |
111 | ||
bebe7282 | 112 | void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) |
22c4272b | 113 | { |
114 | pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); | |
5ead4b17 JG |
115 | |
116 | // Updating time can change work required on testnet: | |
4c902704 | 117 | if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) { |
5ead4b17 | 118 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b86dc980 | 119 | } |
22c4272b | 120 | } |
121 | ||
5416af1d | 122 | #include "komodo_defs.h" |
123 | ||
69767347 | 124 | extern CCriticalSection cs_metrics; |
6e78d3df | 125 | 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 | 126 | extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED; |
5f63373e | 127 | extern bool VERUS_MINTBLOCKS; |
42181656 | 128 | extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[]; |
129 | extern const char *ASSETCHAINS_ALGORITHMS[]; | |
5296a850 | 130 | extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_ALGO, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[]; |
7c130297 | 131 | extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; |
b2a98c42 MT |
132 | extern uint160 ASSETCHAINS_CHAINID; |
133 | extern uint160 VERUS_CHAINID; | |
f2d873d0 | 134 | extern std::string VERUS_CHAINNAME; |
68b309c0 | 135 | extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK; |
7af5cf39 | 136 | extern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;; |
f8f61a6d | 137 | extern int32_t PBAAS_PORT; |
7af5cf39 | 138 | extern uint16_t ASSETCHAINS_RPCPORT; |
d9f176ac | 139 | extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY; |
292809f7 | 140 | void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len); |
d9f176ac | 141 | |
94a465a6 | 142 | extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; |
f24b36ca | 143 | uint32_t Mining_start,Mining_height; |
28a62b60 | 144 | int32_t My_notaryid = -1; |
8683bd8d | 145 | int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); |
b4810651 | 146 | int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); |
d63fdb34 | 147 | int32_t komodo_baseid(char *origbase); |
3bc88f14 | 148 | int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); |
29bd53a1 | 149 | int64_t komodo_block_unlocktime(uint32_t nHeight); |
18443f69 | 150 | uint64_t komodo_commission(const CBlock *block); |
d231a6a7 | 151 | 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 | 152 | int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk); |
496f1fd2 | 153 | int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33); |
7652ed92 | 154 | |
1685bba0 MT |
155 | void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int &nExtraNonce, bool buildMerkle, uint32_t *pSaveBits) |
156 | { | |
157 | // Update nExtraNonce | |
158 | static uint256 hashPrevBlock; | |
159 | if (hashPrevBlock != pblock->hashPrevBlock) | |
160 | { | |
161 | nExtraNonce = 0; | |
162 | hashPrevBlock = pblock->hashPrevBlock; | |
163 | } | |
164 | ++nExtraNonce; | |
165 | ||
166 | if (pSaveBits) | |
167 | { | |
168 | *pSaveBits = pblock->nBits; | |
169 | } | |
170 | ||
171 | int32_t nHeight = pindexPrev->GetHeight() + 1; | |
172 | ||
173 | if (CConstVerusSolutionVector::activationHeight.ActiveVersion(nHeight) >= CConstVerusSolutionVector::activationHeight.SOLUTION_VERUSV3) | |
174 | { | |
175 | // coinbase should already be finalized in the new version | |
176 | if (buildMerkle) | |
177 | { | |
178 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); | |
179 | } | |
180 | ||
181 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
182 | ||
183 | uint256 mmvRoot; | |
184 | { | |
185 | LOCK(cs_main); | |
186 | // set the PBaaS header | |
187 | ChainMerkleMountainView mmv = chainActive.GetMMV(); | |
188 | mmvRoot = mmv.GetRoot(); | |
189 | } | |
190 | ||
191 | pblock->AddUpdatePBaaSHeader(mmvRoot); | |
192 | ||
193 | // POS blocks have already had their solution space filled, and there is no actual extra nonce, extradata is used | |
194 | // for POS proof, so don't modify it | |
195 | if (!pblock->IsVerusPOSBlock()) | |
196 | { | |
197 | uint8_t dummy; | |
198 | // clear extra data to allow adding more PBaaS headers | |
199 | pblock->SetExtraData(&dummy, 0); | |
200 | ||
201 | // combine blocks and set compact difficulty if necessary | |
202 | uint32_t savebits; | |
203 | if ((savebits = ConnectedChains.CombineBlocks(*pblock)) && pSaveBits) | |
204 | { | |
205 | arith_uint256 ours, merged; | |
206 | ours.SetCompact(pblock->nBits); | |
207 | merged.SetCompact(savebits); | |
208 | if (merged > ours) | |
209 | { | |
210 | *pSaveBits = savebits; | |
211 | } | |
212 | } | |
213 | ||
214 | // extra nonce is kept in the header, not in the coinbase any longer | |
215 | // this allows instant spend transactions to use coinbase funds for | |
216 | // inputs by ensuring that once final, the coinbase transaction hash | |
217 | // will not continue to change | |
218 | CDataStream s(SER_NETWORK, PROTOCOL_VERSION); | |
219 | s << nExtraNonce; | |
220 | std::vector<unsigned char> vENonce(s.begin(), s.end()); | |
221 | ||
222 | assert(pblock->ExtraDataLen() >= vENonce.size()); | |
223 | pblock->SetExtraData(vENonce.data(), vENonce.size()); | |
224 | } | |
225 | } | |
226 | else | |
227 | { | |
228 | // finalize input of coinbase | |
229 | CMutableTransaction txcb(pblock->vtx[0]); | |
230 | txcb.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; | |
231 | assert(txcb.vin[0].scriptSig.size() <= 100); | |
232 | pblock->vtx[0] = txcb; | |
233 | if (buildMerkle) | |
234 | { | |
235 | pblock->hashMerkleRoot = pblock->BuildMerkleTree(); | |
236 | } | |
237 | ||
238 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
239 | } | |
240 | } | |
241 | ||
5034d1c1 | 242 | CBlockTemplate* CreateNewBlock(const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake) |
d247a5d1 | 243 | { |
8626f666 | 244 | CScript scriptPubKeyIn(_scriptPubKeyIn); |
06f41160 | 245 | |
41f170fd MT |
246 | // instead of one scriptPubKeyIn, we take a vector of them along with relative weight. each is assigned a percentage of the block subsidy and |
247 | // mining reward based on its weight relative to the total | |
bb6c3482 | 248 | std::vector<pair<int, CScript>> minerOutputs = scriptPubKeyIn.size() ? std::vector<pair<int, CScript>>({make_pair((int)1, scriptPubKeyIn)}) : std::vector<pair<int, CScript>>(); |
41f170fd | 249 | |
88bc6df5 | 250 | // TODO: when we accept a parameter of the minerOutputs vector, remove this comment but not the check |
c3250dcd | 251 | CTxDestination firstDestination; |
bb6c3482 | 252 | if (!(scriptPubKeyIn.size() && ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination) || isStake)) |
88bc6df5 | 253 | { |
34d1aa13 | 254 | fprintf(stderr,"%s: Must have valid miner outputs, including script with valid PK or PKH destination.\n", __func__); |
88bc6df5 MT |
255 | return NULL; |
256 | } | |
257 | ||
bb6c3482 | 258 | if (minerOutputs.size()) |
06f41160 | 259 | { |
bb6c3482 | 260 | int64_t shareCheck = 0; |
261 | for (auto output : minerOutputs) | |
c3250dcd | 262 | { |
bb6c3482 | 263 | shareCheck += output.first; |
264 | if (shareCheck < 0 || shareCheck > INT_MAX) | |
265 | { | |
266 | fprintf(stderr,"Invalid miner outputs share specifications\n"); | |
267 | return NULL; | |
268 | } | |
c3250dcd | 269 | } |
06f41160 | 270 | } |
271 | ||
c3250dcd MT |
272 | CPubKey pk = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), firstDestination); |
273 | ||
9339a0cb | 274 | uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params(); |
2a6a442a | 275 | //fprintf(stderr,"create new block\n"); |
df756d24 | 276 | // Create new block |
16593898 | 277 | if ( gpucount < 0 ) |
278 | gpucount = KOMODO_MAXGPUCOUNT; | |
08c58194 | 279 | std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); |
d247a5d1 | 280 | if(!pblocktemplate.get()) |
1b5b89ba | 281 | { |
282 | fprintf(stderr,"pblocktemplate.get() failure\n"); | |
d247a5d1 | 283 | return NULL; |
1b5b89ba | 284 | } |
d247a5d1 | 285 | CBlock *pblock = &pblocktemplate->block; // pointer for convenience |
12217420 | 286 | |
287 | // set version according to the current tip height, add solution if it is | |
288 | // VerusHash | |
289 | if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH) | |
290 | { | |
291 | pblock->nSolution.resize(Eh200_9.SolutionWidth); | |
292 | } | |
293 | else | |
294 | { | |
295 | pblock->nSolution.clear(); | |
296 | } | |
297 | pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1); | |
298 | ||
299 | // -regtest only: allow overriding block.nVersion with | |
dbca89b7 GA |
300 | // -blockversion=N to test forking scenarios |
301 | if (Params().MineBlocksOnDemand()) | |
302 | pblock->nVersion = GetArg("-blockversion", pblock->nVersion); | |
e9e70b95 | 303 | |
41f170fd | 304 | // Add dummy coinbase tx placeholder as first transaction |
4949004d | 305 | pblock->vtx.push_back(CTransaction()); |
41f170fd | 306 | |
d247a5d1 JG |
307 | pblocktemplate->vTxFees.push_back(-1); // updated at end |
308 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
e9e70b95 | 309 | |
d247a5d1 | 310 | // Largest block you're willing to create: |
ad898b40 | 311 | unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); |
d247a5d1 JG |
312 | // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: |
313 | nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); | |
e9e70b95 | 314 | |
d247a5d1 JG |
315 | // How much of the block should be dedicated to high-priority transactions, |
316 | // included regardless of the fees they pay | |
317 | unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); | |
318 | nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); | |
e9e70b95 | 319 | |
d247a5d1 JG |
320 | // Minimum block size you want to create; block will be filled with free transactions |
321 | // until there are no more or the block reaches this size: | |
037b4f14 | 322 | unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); |
d247a5d1 | 323 | nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); |
e9e70b95 | 324 | |
d247a5d1 | 325 | // Collect memory pool transactions into the block |
a372168e | 326 | CAmount nFees = 0; |
df756d24 | 327 | |
41f170fd MT |
328 | // if this is a reserve currency, update the currency state from the coinbase of the last block |
329 | bool isVerusActive = IsVerusActive(); | |
330 | CPBaaSChainDefinition &thisChain = ConnectedChains.ThisChain(); | |
331 | CCoinbaseCurrencyState currencyState = CCoinbaseCurrencyState(CCurrencyState(thisChain.conversion, thisChain.premine, 0, 0, 0), 0, 0, CReserveOutput(), 0, 0); | |
332 | CAmount exchangeRate; | |
333 | ||
df756d24 MT |
334 | // we will attempt to spend any cheats we see |
335 | CTransaction cheatTx; | |
336 | boost::optional<CTransaction> cheatSpend; | |
337 | uint256 cbHash; | |
338 | ||
687e93d5 MT |
339 | extern CWallet *pwalletMain; |
340 | ||
562852ab | 341 | CBlockIndex* pindexPrev = 0; |
d247a5d1 JG |
342 | { |
343 | LOCK2(cs_main, mempool.cs); | |
562852ab | 344 | pindexPrev = chainActive.LastTip(); |
4b729ec5 | 345 | const int nHeight = pindexPrev->GetHeight() + 1; |
df756d24 MT |
346 | const Consensus::Params &consensusParams = chainparams.GetConsensus(); |
347 | uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams); | |
348 | bool sapling = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING); | |
a0dd01bc | 349 | |
a1d3c6fb | 350 | const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); |
a0dd01bc | 351 | uint32_t proposedTime = GetAdjustedTime(); |
352 | if (proposedTime == nMedianTimePast) | |
353 | { | |
354 | // too fast or stuck, this addresses the too fast issue, while moving | |
355 | // forward as quickly as possible | |
356 | for (int i; i < 100; i++) | |
357 | { | |
358 | proposedTime = GetAdjustedTime(); | |
359 | if (proposedTime == nMedianTimePast) | |
360 | MilliSleep(10); | |
361 | } | |
362 | } | |
363 | pblock->nTime = GetAdjustedTime(); | |
364 | ||
7c70438d | 365 | CCoinsViewCache view(pcoinsTip); |
f9155fec | 366 | uint32_t expired; uint64_t commission; |
6ff77181 | 367 | |
4fc309f0 | 368 | SaplingMerkleTree sapling_tree; |
31a04d28 SB |
369 | assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree)); |
370 | ||
d247a5d1 JG |
371 | // Priority order to process transactions |
372 | list<COrphan> vOrphan; // list memory doesn't move | |
373 | map<uint256, vector<COrphan*> > mapDependers; | |
374 | bool fPrintPriority = GetBoolArg("-printpriority", false); | |
e9e70b95 | 375 | |
d247a5d1 JG |
376 | // This vector will be sorted into a priority queue: |
377 | vector<TxPriority> vecPriority; | |
df756d24 MT |
378 | vecPriority.reserve(mempool.mapTx.size() + 1); |
379 | ||
380 | // check if we should add cheat transaction | |
381 | CBlockIndex *ppast; | |
ec8a120b | 382 | CTransaction cb; |
83a426bc | 383 | int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY; |
df756d24 MT |
384 | if (cheatCatcher && |
385 | sapling && chainActive.Height() > 100 && | |
83a426bc | 386 | (ppast = chainActive[cheatHeight]) && |
df756d24 | 387 | ppast->IsVerusPOSBlock() && |
83a426bc | 388 | cheatList.IsHeightOrGreaterInList(cheatHeight)) |
df756d24 MT |
389 | { |
390 | // get the block and see if there is a cheat candidate for the stake tx | |
391 | CBlock b; | |
392 | if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, 1)) | |
393 | { | |
394 | CTransaction &stakeTx = b.vtx[b.vtx.size() - 1]; | |
395 | ||
396 | if (cheatList.IsCheatInList(stakeTx, &cheatTx)) | |
397 | { | |
398 | // make and sign the cheat transaction to spend the coinbase to our address | |
399 | CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight); | |
400 | ||
73a4cd20 | 401 | uint32_t voutNum; |
402 | // get the first vout with value | |
403 | for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++) | |
404 | { | |
405 | if (b.vtx[0].vout[voutNum].nValue > 0) | |
406 | break; | |
407 | } | |
408 | ||
df756d24 | 409 | // send to the same pub key as the destination of this block reward |
73a4cd20 | 410 | if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx)) |
df756d24 | 411 | { |
df756d24 | 412 | LOCK(pwalletMain->cs_wallet); |
6c621e0e | 413 | TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight); |
ec8a120b | 414 | cb = b.vtx[0]; |
df756d24 MT |
415 | cbHash = cb.GetHash(); |
416 | ||
417 | bool hasInput = false; | |
418 | for (uint32_t i = 0; i < cb.vout.size(); i++) | |
419 | { | |
420 | // add the spends with the cheat | |
73a4cd20 | 421 | if (cb.vout[i].nValue > 0) |
df756d24 MT |
422 | { |
423 | tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue); | |
424 | hasInput = true; | |
425 | } | |
426 | } | |
427 | ||
428 | if (hasInput) | |
429 | { | |
430 | // this is a send from a t-address to a sapling address, which we don't have an ovk for. | |
431 | // Instead, generate a common one from the HD seed. This ensures the data is | |
432 | // recoverable, at least for us, while keeping it logically separate from the ZIP 32 | |
433 | // Sapling key hierarchy, which the user might not be using. | |
434 | uint256 ovk; | |
435 | HDSeed seed; | |
436 | if (pwalletMain->GetHDSeed(seed)) { | |
437 | ovk = ovkForShieldingFromTaddr(seed); | |
438 | ||
ac2b2404 | 439 | // send everything to Sapling address |
440 | tb.SendChangeTo(cheatCatcher.value(), ovk); | |
441 | ||
2d02c19e | 442 | tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey); |
df756d24 MT |
443 | |
444 | cheatSpend = tb.Build(); | |
df756d24 MT |
445 | } |
446 | } | |
447 | } | |
448 | } | |
449 | } | |
450 | } | |
451 | ||
271326fa | 452 | if (cheatSpend) |
453 | { | |
90cc70cc | 454 | cheatTx = cheatSpend.value(); |
271326fa | 455 | std::list<CTransaction> removed; |
45bb4681 | 456 | mempool.removeConflicts(cheatTx, removed); |
c8700efe | 457 | printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n", |
ec8a120b | 458 | (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str()); |
45bb4681 | 459 | |
460 | // add to mem pool and relay | |
461 | if (myAddtomempool(cheatTx)) | |
462 | { | |
463 | RelayTransaction(cheatTx); | |
464 | } | |
271326fa | 465 | } |
466 | ||
41f170fd MT |
467 | // |
468 | // Now start solving the block | |
469 | // | |
470 | ||
471 | uint64_t nBlockSize = 1000; // initial size | |
472 | uint64_t nBlockTx = 1; // number of transactions - always have a coinbase | |
473 | uint32_t autoTxSize = 0; // extra transaction overhead that we will add while creating the block | |
474 | int nBlockSigOps = 100; | |
475 | ||
476 | // VerusPoP staking transaction data | |
477 | CMutableTransaction txStaked; // if this is a stake operation, the staking transaction that goes at the end | |
478 | uint32_t nStakeTxSize = 0; // serialized size of the stake transaction | |
479 | ||
480 | // if this is not for mining, first determine if we have a right to bother | |
481 | if (isStake) | |
482 | { | |
483 | uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr; | |
484 | txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); | |
485 | ||
486 | //if ( blocktime > pindexPrev->GetMedianTimePast()+60 ) | |
487 | // blocktime = pindexPrev->GetMedianTimePast() + 60; | |
488 | if (ASSETCHAINS_LWMAPOS != 0) | |
489 | { | |
490 | uint32_t nBitsPOS; | |
491 | arith_uint256 posHash; | |
492 | ||
493 | siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk); | |
494 | blocktime = GetAdjustedTime(); | |
495 | ||
496 | // change the default scriptPubKeyIn to the same output script exactly as the staking transaction | |
497 | // TODO: improve this and just implement stake guard here rather than keeping this legacy | |
498 | if (siglen > 0) | |
499 | scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey); | |
500 | } | |
501 | else | |
502 | { | |
503 | siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig); | |
504 | } | |
505 | ||
506 | if (siglen <= 0) | |
507 | { | |
508 | return NULL; | |
509 | } | |
510 | ||
511 | pblock->nTime = blocktime; | |
512 | nStakeTxSize = GetSerializeSize(txStaked, SER_NETWORK, PROTOCOL_VERSION); | |
513 | nBlockSize += nStakeTxSize; | |
bb6c3482 | 514 | |
515 | // get the public key and make a miner output if needed for this | |
516 | if (!minerOutputs.size()) | |
517 | { | |
518 | minerOutputs.push_back(make_pair((int)1, txStaked.vout[0].scriptPubKey)); | |
519 | txnouttype typeRet; | |
520 | std::vector<std::vector<unsigned char>> vSolutions; | |
521 | if (Solver(txStaked.vout[0].scriptPubKey, typeRet, vSolutions)) | |
522 | { | |
523 | if (typeRet == TX_PUBKEY) | |
524 | { | |
525 | pk = CPubKey(vSolutions[0]); | |
526 | } | |
527 | else | |
528 | { | |
529 | pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk); | |
530 | } | |
531 | } | |
532 | ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination); | |
533 | } | |
41f170fd MT |
534 | } |
535 | ||
bb6c3482 | 536 | ConnectedChains.AggregateChainTransfers(firstDestination, nHeight); |
537 | ||
41f170fd MT |
538 | // Now the coinbase - |
539 | // A PBaaS coinbase must have some additional outputs to enable certain chain state and functions to be properly | |
540 | // validated. All but currency state and the first chain definition are either optional or not valid on non-fractional reserve PBaaS blockchains | |
541 | // All of these are instant spend outputs that have no maturity wait time and may be spent in the same block. | |
542 | // | |
543 | // 1. (required) currency state - current state of currency supply and optionally reserve, premine, etc. This is primarily a data output to provide | |
544 | // cross check for coin minting and burning operations, making it efficient to determine up-to-date supply, reserves, and conversions. To provide | |
545 | // an extra level of supply cross-checking and fast data retrieval, this is part of all PBaaS chains' protocol, not just reserves. | |
546 | // This output also includes reserve and native amounts for total conversions, less fees, of any conversions between Verus reserve and the | |
547 | // native currency. | |
548 | // | |
549 | // 2. (block 1 required) chain definition - in order to confirm the amount of coins converted and issued within the possible range, before chain start, | |
550 | // new PBaaS chains have a zero-amount, unspendable chain definition output. | |
551 | // | |
552 | // 3. (block 1 optional) initial import utxo - for any chain with conversion or pre-conversion, the first coinbase must include an initial import utxo. | |
553 | // Pre-conversions are handled on the launch chain before the PBaaS chain starts, so they are an additional output, which begins | |
554 | // as a fixed amount and is spent with as many outputs as necessary to the recipients of the pre-conversion transactions when those pre-conversions | |
555 | // are imported. All pre-converted outputs get their source currency from a thread that starts with this output in block 1. | |
556 | // | |
557 | // 4. (block 1 optional) initial export utxo - reserve chains, or any chain that will use exports to another chain must have an initial export utxo, any chain | |
558 | // may have one, but currently, they can only be spent with valid exports, which only occur on reserve chains | |
559 | // | |
560 | // 5. (optional) notarization output - in order to ensure that notarization can occur independent of the availability of fungible | |
561 | // coins on the network, and also that the notarization can provide a spendable finalization output and possible reward | |
562 | // | |
563 | // In addition, each PBaaS block can be mined with optional, fee-generating transactions. Inporting transactions from the reserve chain or sending | |
564 | // exported transactions to the reserve chain are optional fee-generating steps that would be easy to do when running multiple daemons. | |
565 | // The types of transactions miners/stakers may facilitate or create for fees are as follows: | |
566 | // | |
567 | // 1. Earned notarization of Verus chain - spends the notarization instant out. must be present and spend the notarization output if there is a notarization output | |
568 | // | |
569 | // 2. Imported transactions from the export thread for this PBaaS chain on the Verus blockchain - imported transactions must spend the import utxo | |
570 | // thread, represent the export from the alternate chain which spends the export output from the prior import transaction, carry a notary proof, and | |
571 | // include outputs that map to each of its inputs on the source chain. Outputs can include unconverted reserve outputs only on fractional | |
572 | // reserve chains, pre-converted outputs for any chain with launch conversion, and post launch outputs to be converted on fractional reserve | |
573 | // chains. Each are handled in the following way: | |
574 | // a. Unconverted outputs are left as outputs to the intended destination of Verus reserve token and do not pass through the coinbase | |
575 | // b. Pre-converted outputs require that the import transaction spend the last pre-conversion output starting at block 1 as the source for | |
576 | // pre-converted currency. | |
577 | // | |
578 | // 3. Zero or more aggregated exports that combine individual cross-chain transactions and reserve transfer outputs for export to the Verus chain. | |
579 | // | |
580 | // 4. Conversion distribution transactions for all native and reserve currency conversions, including reserve transfer outputs without conversion as | |
581 | // a second step for reserve transfers that have conversion included. Any remaining pre-converted reserve must always remain in a change output | |
582 | // until it is exhausted | |
88bc6df5 | 583 | CTxOut premineOut, chainDefinitionOut, importThreadOut, exportThreadOut, currencyStateOut, notarizationOut; |
41f170fd MT |
584 | CMutableTransaction newNotarizationTx, newConversionOutputTx; |
585 | ||
586 | // size of conversion tx | |
0574c740 | 587 | std::vector<CInputDescriptor> conversionInputs; |
41f170fd MT |
588 | |
589 | // if we are a PBaaS chain, first make sure we don't start prematurely, and if | |
590 | // we should make an earned notarization, make it and set index to non-zero value | |
591 | int32_t notarizationTxIndex = 0; // index of notarization if it is added | |
592 | int32_t conversionTxIndex = 0; // index of conversion transaction if it is added | |
593 | ||
594 | // export transactions can be created here by aggregating all pending transfer requests and either getting 10 or more together, or | |
595 | // waiting n (10) blocks since the last one. each export must spend the output of the one before it | |
596 | std::vector<CMutableTransaction> exportTransactions; | |
597 | ||
598 | // all transaction outputs requesting conversion to another currency (PBaaS fractional reserve only) | |
599 | // these will be used to calculate conversion price, fees, and generate coinbase conversion output as well as the | |
600 | // conversion output transaction | |
601 | std::vector<CTxOut> reserveConversionTo; | |
602 | std::vector<CTxOut> reserveConversionFrom; | |
603 | ||
604 | int64_t pbaasTransparentIn = 0; | |
605 | int64_t pbaasTransparentOut = 0; | |
606 | int64_t blockSubsidy = GetBlockSubsidy(nHeight, consensusParams); | |
607 | ||
608 | uint160 thisChainID = ConnectedChains.ThisChain().GetChainID(); | |
609 | ||
610 | uint256 mmrRoot; | |
611 | vector<CInputDescriptor> notarizationInputs; | |
612 | ||
41f170fd MT |
613 | // used as scratch for making CCs, should be reinitialized each time |
614 | CCcontract_info CC; | |
615 | CCcontract_info *cp; | |
616 | vector<CTxDestination> vKeys; | |
c3250dcd | 617 | CPubKey pkCC; |
41f170fd MT |
618 | |
619 | // Create coinbase tx and set up the null input with height | |
620 | CMutableTransaction coinbaseTx = CreateNewContextualCMutableTransaction(consensusParams, nHeight); | |
bb6c3482 | 621 | coinbaseTx.vin.push_back(CTxIn(uint256(), (uint32_t)-1, CScript() << nHeight << OP_0)); |
41f170fd MT |
622 | |
623 | // default outputs for mining and before stake guard or fee calculation | |
624 | // store the relative weight in the amount output to convert later to a relative portion | |
625 | // of the reward + fees | |
626 | for (auto &spk : minerOutputs) | |
627 | { | |
628 | coinbaseTx.vout.push_back(CTxOut(spk.first, spk.second)); | |
629 | } | |
630 | ||
631 | // we will update amounts and fees later, but convert the guarded output now for validity checking and size estimate | |
632 | if (isStake) | |
633 | { | |
634 | // if there is a specific destination, use it | |
635 | CTransaction stakeTx(txStaked); | |
636 | CStakeParams p; | |
637 | if (ValidateStakeTransaction(stakeTx, p, false)) | |
638 | { | |
639 | if (!p.pk.IsValid()) | |
640 | { | |
641 | LogPrintf("CreateNewBlock: invalid public key\n"); | |
642 | fprintf(stderr,"CreateNewBlock: invalid public key\n"); | |
643 | return NULL; | |
644 | } | |
645 | for (auto &cbOutput : coinbaseTx.vout) | |
646 | { | |
647 | if (!MakeGuardedOutput(cbOutput.nValue, p.pk, stakeTx, cbOutput)) | |
648 | { | |
649 | LogPrintf("CreateNewBlock: failed to make GuardedOutput on staking coinbase\n"); | |
650 | fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n"); | |
651 | return NULL; | |
652 | } | |
653 | } | |
654 | } | |
655 | else | |
656 | { | |
657 | LogPrintf("CreateNewBlock: invalid stake transaction\n"); | |
658 | fprintf(stderr,"CreateNewBlock: invalid stake transaction\n"); | |
659 | return NULL; | |
660 | } | |
661 | } | |
662 | ||
34d1aa13 MT |
663 | CAmount totalEmission = blockSubsidy; |
664 | ||
1fa4454d | 665 | // make earned notarization only if this is not the notary chain and we have enough subsidy |
41f170fd | 666 | if (!isVerusActive) |
2299bd95 | 667 | { |
4e1c9d8f | 668 | if (nHeight == 1) |
669 | { | |
670 | blockSubsidy -= GetBlockOnePremine(); // separate subsidy, which can go to miner, from premine | |
671 | } | |
672 | ||
68b309c0 | 673 | // if we don't have a connected root PBaaS chain, we can't properly check |
41f170fd | 674 | // and notarize the start block, so we have to pass the notarization and cross chain steps |
989b1de1 | 675 | bool notaryConnected = ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK; |
e7e14f44 | 676 | |
e7c700b5 | 677 | // get current currency state differently, depending on height |
e7e14f44 MT |
678 | if (nHeight == 1) |
679 | { | |
680 | if (!notaryConnected) | |
681 | { | |
e7c700b5 | 682 | // cannt make block 1 unless we can properly notarize that the launch chain is past the start block |
e7e14f44 MT |
683 | return NULL; |
684 | } | |
685 | ||
e7c700b5 | 686 | // if some amount of pre-conversion was allowed |
e7e14f44 MT |
687 | if (thisChain.maxpreconvert) |
688 | { | |
689 | // this is invalid | |
690 | if (thisChain.conversion <= 0) | |
691 | { | |
692 | return NULL; | |
693 | } | |
694 | ||
695 | // get the total amount pre-converted | |
696 | UniValue params(UniValue::VARR); | |
697 | params.push_back(ASSETCHAINS_CHAINID.GetHex()); | |
698 | ||
699 | UniValue result; | |
700 | try | |
701 | { | |
702 | result = find_value(RPCCallRoot("getinitialcurrencystate", params), "result"); | |
703 | } catch (exception e) | |
704 | { | |
705 | result = NullUniValue; | |
706 | } | |
707 | ||
58148aef | 708 | if (!result.isNull()) |
709 | { | |
710 | currencyState = CCoinbaseCurrencyState(result); | |
711 | } | |
712 | ||
713 | if (result.isNull() || !currencyState.IsValid()) | |
e7e14f44 MT |
714 | { |
715 | // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail | |
716 | LogPrintf("Unable to get initial currency state to create block.\n"); | |
717 | printf("Failure to get initial currency state. Cannot create block.\n"); | |
718 | return NULL; | |
719 | } | |
720 | } | |
41f170fd MT |
721 | |
722 | // add needed block one coinbase outputs | |
88bc6df5 | 723 | // send normal reward to the miner, premine to the address in the chain definition, and pre-converted to the |
41f170fd | 724 | // import thread out |
dd4f0fdd | 725 | if (GetBlockOnePremine()) |
e7e14f44 | 726 | { |
41f170fd MT |
727 | premineOut = CTxOut(GetBlockOnePremine(), GetScriptForDestination(CTxDestination(ConnectedChains.ThisChain().address))); |
728 | coinbaseTx.vout.push_back(premineOut); | |
e7e14f44 | 729 | } |
41f170fd MT |
730 | |
731 | // chain definition - always | |
732 | // make the chain definition output | |
733 | vKeys.clear(); | |
734 | cp = CCinit(&CC, EVAL_PBAASDEFINITION); | |
735 | ||
736 | // send this to EVAL_PBAASDEFINITION address as a destination, locked by the default pubkey | |
c3250dcd | 737 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
41f170fd MT |
738 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_PBAASDEFINITION))); |
739 | thisChain.preconverted = currencyState.ReserveIn; // update known, preconverted amount | |
715182a4 | 740 | |
c3250dcd | 741 | chainDefinitionOut = MakeCC1of1Vout(EVAL_PBAASDEFINITION, 0, pkCC, vKeys, thisChain); |
41f170fd MT |
742 | coinbaseTx.vout.push_back(chainDefinitionOut); |
743 | ||
744 | // import - only spendable for reserve currency or currency with preconversion to allow import of conversions, this output will include | |
90100fac | 745 | // all pre-converted coins and all pre-conversion fees, denominated in Verus reserve currency |
41f170fd MT |
746 | // chain definition - always |
747 | // make the chain definition output | |
748 | vKeys.clear(); | |
749 | cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT); | |
750 | ||
c3250dcd MT |
751 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
752 | ||
753 | // import thread is specific to the chain importing from | |
754 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetChainID(), EVAL_CROSSCHAIN_IMPORT))); | |
41f170fd | 755 | |
1b268198 | 756 | // log import of all reserve in as well as the fees that are passed through the initial ReserveOut in the initial import |
41f170fd | 757 | importThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_IMPORT, |
c3250dcd | 758 | currencyState.ReserveToNative(thisChain.preconverted, thisChain.conversion), pkCC, vKeys, |
1b268198 | 759 | CCrossChainImport(ConnectedChains.NotaryChain().GetChainID(), currencyState.ReserveIn + currencyState.ReserveOut.nValue)); |
c3250dcd | 760 | |
41f170fd MT |
761 | coinbaseTx.vout.push_back(importThreadOut); |
762 | ||
763 | // export - currently only spendable for reserve currency, but added for future capabilities | |
764 | vKeys.clear(); | |
765 | cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT); | |
766 | ||
c3250dcd | 767 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
78a36746 | 768 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetChainID(), EVAL_CROSSCHAIN_EXPORT))); |
41f170fd | 769 | |
c3250dcd | 770 | exportThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_EXPORT, 0, pkCC, vKeys, |
41f170fd MT |
771 | CCrossChainExport(ConnectedChains.NotaryChain().GetChainID(), 0, 0, 0)); |
772 | coinbaseTx.vout.push_back(exportThreadOut); | |
e7e14f44 MT |
773 | } |
774 | else | |
989b1de1 | 775 | { |
e7e14f44 | 776 | CBlock block; |
e7c700b5 | 777 | assert(nHeight > 1); |
41f170fd | 778 | currencyState = ConnectedChains.GetCurrencyState(nHeight - 1); |
1f15dff1 | 779 | currencyState.Fees = 0; |
780 | currencyState.NativeIn = 0; | |
781 | currencyState.ReserveIn = 0; | |
782 | currencyState.ReserveOut.nValue = 0; | |
783 | ||
41f170fd | 784 | if (!currencyState.IsValid()) |
e7e14f44 | 785 | { |
41f170fd MT |
786 | // we should be able to get a valid currency state, if not, fail |
787 | LogPrintf("Unable to get initial currency state to create block #%d.\n", nHeight); | |
788 | printf("Failure to get initial currency state. Cannot create block #%d.\n", nHeight); | |
789 | return NULL; | |
e7e14f44 | 790 | } |
989b1de1 MT |
791 | } |
792 | ||
34d1aa13 | 793 | // update the currency state to include emissions before calculating conversions |
58148aef | 794 | // premine is an emission that is factored in before this |
34d1aa13 MT |
795 | currencyState.UpdateWithEmission(totalEmission); |
796 | ||
41f170fd MT |
797 | // always add currency state output for coinbase |
798 | vKeys.clear(); | |
799 | cp = CCinit(&CC, EVAL_CURRENCYSTATE); | |
800 | ||
7b961d96 | 801 | CPubKey currencyOutPK(ParseHex(cp->CChexstr)); |
41f170fd | 802 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_CURRENCYSTATE)))); |
41f170fd MT |
803 | |
804 | // make an output that either carries zero coins pre-converting, or the initial supply for block 1, conversion amounts will be adjusted later | |
7b961d96 | 805 | currencyStateOut = MakeCC1of1Vout(EVAL_CURRENCYSTATE, 0, currencyOutPK, vKeys, currencyState); |
41f170fd MT |
806 | |
807 | coinbaseTx.vout.push_back(currencyStateOut); | |
808 | ||
989b1de1 | 809 | if (notaryConnected) |
4fa3b13d | 810 | { |
41f170fd | 811 | // if we have access to our notary daemon |
1fa4454d | 812 | // create a notarization if we would qualify, and add it to the mempool and block |
687e93d5 | 813 | CTransaction prevTx, crossTx, lastConfirmed, lastImportTx; |
4fa3b13d | 814 | ChainMerkleMountainView mmv = chainActive.GetMMV(); |
8577896f | 815 | mmrRoot = mmv.GetRoot(); |
1fa4454d MT |
816 | int32_t confirmedInput = -1; |
817 | CTxDestination confirmedDest; | |
687e93d5 | 818 | if (CreateEarnedNotarization(newNotarizationTx, notarizationInputs, prevTx, crossTx, lastConfirmed, nHeight, &confirmedInput, &confirmedDest)) |
4fa3b13d | 819 | { |
1fa4454d MT |
820 | // we have a valid, earned notarization transaction. we still need to complete it as follows: |
821 | // 1. Add an instant-spend input from the coinbase transaction to fund the finalization output | |
822 | // | |
823 | // 2. if we are spending finalization outputs, create an output of the same amount as a finalization output | |
824 | // plus and any excess from the other, orphaned finalizations to the creator of the confirmed notarization | |
825 | // | |
e7e14f44 MT |
826 | // 3. make sure the currency state is correct |
827 | ||
1fa4454d | 828 | // input should either be 0 or PBAAS_MINNOTARIZATIONOUTPUT + all finalized outputs |
41f170fd | 829 | // we will add PBAAS_MINNOTARIZATIONOUTPUT from a coinbase instant spend in all cases and double that when it is 0 for block 1 |
68b309c0 MT |
830 | for (const CTxIn& txin : newNotarizationTx.vin) |
831 | { | |
832 | const uint256& prevHash = txin.prevout.hash; | |
1fa4454d | 833 | const CCoins *pcoins = view.AccessCoins(prevHash); |
68b309c0 MT |
834 | pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0; |
835 | } | |
eb0a6550 | 836 | |
1fa4454d MT |
837 | // calculate the amount that will be sent to the confirmed notary address |
838 | // this will only be non-zero if we have finalized inputs | |
839 | if (pbaasTransparentIn > 0) | |
eb0a6550 | 840 | { |
1fa4454d | 841 | pbaasTransparentOut = pbaasTransparentIn - PBAAS_MINNOTARIZATIONOUTPUT; |
eb0a6550 | 842 | } |
843 | ||
1fa4454d | 844 | if (pbaasTransparentOut) |
eb0a6550 | 845 | { |
1fa4454d MT |
846 | // if we are on a non-fungible chain, reward out must be unspendable |
847 | // make a normal output to the confirmed notary with the excess right behind the op_return | |
848 | // TODO: make this a cc out to only allow spending on a fungible chain | |
849 | CTxOut rewardOut = CTxOut(pbaasTransparentOut, GetScriptForDestination(confirmedDest)); | |
850 | newNotarizationTx.vout.insert(newNotarizationTx.vout.begin() + newNotarizationTx.vout.size() - 1, rewardOut); | |
eb0a6550 | 851 | } |
41f170fd MT |
852 | |
853 | // make the earned notarization coinbase output | |
854 | vKeys.clear(); | |
855 | cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION); | |
856 | ||
857 | // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey | |
c3250dcd | 858 | pkCC = CPubKey(ParseHex(cp->CChexstr)); |
6b732553 | 859 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION)))); |
41f170fd MT |
860 | |
861 | int64_t needed = nHeight == 1 ? PBAAS_MINNOTARIZATIONOUTPUT << 1 : PBAAS_MINNOTARIZATIONOUTPUT; | |
862 | ||
863 | // output duplicate notarization as coinbase output for instant spend to notarization | |
864 | // the output amount is considered part of the total value of this coinbase | |
865 | CPBaaSNotarization pbn(newNotarizationTx); | |
c3250dcd | 866 | notarizationOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pkCC, vKeys, pbn); |
41f170fd MT |
867 | coinbaseTx.vout.push_back(notarizationOut); |
868 | ||
bb6c3482 | 869 | // place the notarization |
870 | pblock->vtx.push_back(CTransaction(newNotarizationTx)); | |
871 | pblocktemplate->vTxFees.push_back(0); | |
872 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
873 | nBlockSize += GetSerializeSize(newNotarizationTx, SER_NETWORK, PROTOCOL_VERSION); | |
874 | notarizationTxIndex = pblock->vtx.size() - 1; | |
875 | nBlockTx++; | |
68b309c0 MT |
876 | } |
877 | else if (nHeight == 1) | |
878 | { | |
879 | // failed to notarize at block 1 | |
880 | return NULL; | |
4fa3b13d | 881 | } |
687e93d5 MT |
882 | |
883 | // if we have a last confirmed notarization, then check for new imports from the notary chain | |
884 | if (lastConfirmed.vout.size()) | |
885 | { | |
886 | // we need to find the last unspent import transaction | |
887 | std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; | |
888 | ||
889 | bool found = false; | |
890 | ||
891 | // we cannot get export to a chain that has shut down | |
892 | // if the chain definition is spent, a chain is inactive | |
893 | if (GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_IMPORT)), 1, unspentOutputs)) | |
894 | { | |
0c21c983 | 895 | // if one spends the prior one, get the one that is not spent |
687e93d5 MT |
896 | for (auto txidx : unspentOutputs) |
897 | { | |
687e93d5 MT |
898 | uint256 blkHash; |
899 | CTransaction itx; | |
900 | if (myGetTransaction(txidx.first.txhash, lastImportTx, blkHash) && | |
901 | CCrossChainImport(lastImportTx).IsValid() && | |
902 | (lastImportTx.IsCoinBase() || | |
903 | (myGetTransaction(lastImportTx.vin[0].prevout.hash, itx, blkHash) && | |
904 | CCrossChainImport(itx).IsValid()))) | |
905 | { | |
906 | found = true; | |
0c21c983 | 907 | break; |
687e93d5 MT |
908 | } |
909 | } | |
910 | } | |
911 | ||
67aac3cf | 912 | if (found && pwalletMain) |
687e93d5 MT |
913 | { |
914 | UniValue params(UniValue::VARR); | |
915 | UniValue param(UniValue::VOBJ); | |
916 | ||
4f86f9ca | 917 | CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); |
918 | int i; | |
919 | for (i = 0; i < lastImportTx.vout.size(); i++) | |
687e93d5 | 920 | { |
4f86f9ca | 921 | COptCCParams p; |
922 | if (lastImportTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.evalCode == EVAL_CROSSCHAIN_IMPORT) | |
923 | { | |
924 | txTemplate.vin.push_back(CTxIn(lastImportTx.GetHash(), (uint32_t)i)); | |
925 | break; | |
926 | } | |
927 | } | |
928 | ||
929 | UniValue result = NullUniValue; | |
930 | if (i < lastImportTx.vout.size()) | |
687e93d5 | 931 | { |
4f86f9ca | 932 | param.push_back(Pair("name", thisChain.name)); |
933 | param.push_back(Pair("lastimporttx", EncodeHexTx(lastImportTx))); | |
934 | param.push_back(Pair("lastconfirmednotarization", EncodeHexTx(lastConfirmed))); | |
5e346982 | 935 | param.push_back(Pair("importtxtemplate", EncodeHexTx(txTemplate))); |
4f86f9ca | 936 | params.push_back(param); |
937 | ||
938 | try | |
939 | { | |
940 | result = find_value(RPCCallRoot("getlatestimportsout", params), "result"); | |
941 | } catch (exception e) | |
942 | { | |
943 | printf("Could not get latest imports from notary chain\n"); | |
944 | } | |
687e93d5 MT |
945 | } |
946 | ||
67aac3cf | 947 | if (result.isArray() && result.size()) |
687e93d5 MT |
948 | { |
949 | LOCK(pwalletMain->cs_wallet); | |
950 | ||
951 | uint256 lastImportHash = lastImportTx.GetHash(); | |
952 | for (int i = 0; i < result.size(); i++) | |
953 | { | |
954 | CTransaction itx; | |
955 | if (result[i].isStr() && DecodeHexTx(itx, result[i].get_str()) && itx.vin.size() && itx.vin[0].prevout.hash == lastImportHash) | |
956 | { | |
0574c740 | 957 | // sign the transaction spending the last import and add to mempool |
687e93d5 MT |
958 | CMutableTransaction mtx(itx); |
959 | CCrossChainImport cci(lastImportTx); | |
960 | ||
961 | bool signSuccess; | |
962 | SignatureData sigdata; | |
963 | CAmount value; | |
964 | const CScript *pScriptPubKey; | |
965 | ||
966 | const CScript virtualCC; | |
967 | CTxOut virtualCCOut; | |
968 | ||
687e93d5 | 969 | signSuccess = ProduceSignature( |
67aac3cf | 970 | TransactionSignatureCreator(pwalletMain, &itx, 0, lastImportTx.vout[itx.vin[0].prevout.n].nValue, SIGHASH_ALL), lastImportTx.vout[itx.vin[0].prevout.n].scriptPubKey, sigdata, consensusBranchId); |
687e93d5 | 971 | |
0574c740 | 972 | if (!signSuccess) |
687e93d5 | 973 | { |
0574c740 | 974 | break; |
687e93d5 MT |
975 | } |
976 | ||
0574c740 | 977 | UpdateTransaction(mtx, 0, sigdata); |
9a91da5a | 978 | itx = CTransaction(mtx); |
0574c740 | 979 | |
687e93d5 MT |
980 | // commit to mempool and remove any conflicts |
981 | std::list<CTransaction> removed; | |
982 | mempool.removeConflicts(itx, removed); | |
983 | CValidationState state; | |
984 | if (!myAddtomempool(itx, &state)) | |
985 | { | |
bb6c3482 | 986 | LogPrintf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); |
987 | printf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); | |
687e93d5 MT |
988 | break; // if we failed to add one, the others will fail to spend it |
989 | } | |
0574c740 | 990 | |
991 | lastImportTx = itx; | |
992 | lastImportHash = itx.GetHash(); | |
687e93d5 MT |
993 | } |
994 | } | |
995 | } | |
996 | } | |
997 | } | |
4fa3b13d | 998 | } |
e7e14f44 | 999 | } |
34d1aa13 MT |
1000 | else |
1001 | { | |
1002 | currencyState.UpdateWithEmission(totalEmission); | |
1003 | } | |
e7e14f44 | 1004 | |
41f170fd MT |
1005 | // coinbase should have all necessary outputs (TODO: timelock is not supported or finished yet) |
1006 | uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION); | |
1007 | nBlockSize += nCoinbaseSize; | |
e7c700b5 | 1008 | |
41f170fd MT |
1009 | // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later |
1010 | bool haveReserveTransactions = false; | |
1011 | uint32_t reserveExchangeLimitSize = 0; | |
1012 | std::vector<const CTransaction *> limitOrders; | |
e7e14f44 | 1013 | |
41f170fd | 1014 | // now add transactions from the mem pool to the priority heap |
e328fa32 | 1015 | for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); |
4d707d51 | 1016 | mi != mempool.mapTx.end(); ++mi) |
d247a5d1 | 1017 | { |
e328fa32 | 1018 | const CTransaction& tx = mi->GetTx(); |
41f170fd | 1019 | uint256 hash = tx.GetHash(); |
e9e70b95 | 1020 | |
a1d3c6fb | 1021 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) |
e9e70b95 | 1022 | ? nMedianTimePast |
1023 | : pblock->GetBlockTime(); | |
9c034267 | 1024 | |
9bb37bf0 | 1025 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) |
61f8caf2 | 1026 | { |
51376f3c | 1027 | //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight)); |
14aa6cc0 | 1028 | continue; |
61f8caf2 | 1029 | } |
9c034267 | 1030 | |
161f617d | 1031 | if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) |
6ff77181 | 1032 | { |
64b45b71 | 1033 | //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 | 1034 | continue; |
14aa6cc0 | 1035 | } |
df756d24 | 1036 | |
d247a5d1 JG |
1037 | COrphan* porphan = NULL; |
1038 | double dPriority = 0; | |
a372168e | 1039 | CAmount nTotalIn = 0; |
e7e14f44 | 1040 | CAmount nTotalReserveIn = 0; |
d247a5d1 | 1041 | bool fMissingInputs = false; |
41f170fd MT |
1042 | CReserveTransactionDescriptor rtxd; |
1043 | bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd); | |
e7e14f44 | 1044 | |
0cb91a8d | 1045 | if (tx.IsCoinImport()) |
d247a5d1 | 1046 | { |
0cb91a8d SS |
1047 | CAmount nValueIn = GetCoinImportValue(tx); |
1048 | nTotalIn += nValueIn; | |
1049 | dPriority += (double)nValueIn * 1000; // flat multiplier | |
1050 | } else { | |
41f170fd | 1051 | // separate limit orders to be added later, we add them at the end, failed fill or kills are normal transactions, consider them reserve txs |
15e4d481 | 1052 | if (isReserve && rtxd.IsReserveExchange() && rtxd.IsLimit()) |
41f170fd MT |
1053 | { |
1054 | // if we might expire, refresh and check again | |
1055 | if (rtxd.IsFillOrKill()) | |
1056 | { | |
1057 | rtxd = CReserveTransactionDescriptor(tx, view, nHeight); | |
1058 | mempool.PrioritiseReserveTransaction(rtxd, currencyState); | |
1059 | } | |
1060 | ||
1061 | // if is is a failed conversion, drop through | |
1062 | if (!rtxd.IsFillOrKillFail()) | |
1063 | { | |
1064 | limitOrders.push_back(&tx); | |
1065 | reserveExchangeLimitSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd MT |
1066 | continue; |
1067 | } | |
1068 | } | |
1069 | if (isReserve) | |
1070 | { | |
1071 | nTotalIn += rtxd.nativeIn; | |
1072 | nTotalReserveIn += rtxd.reserveIn; | |
1073 | } | |
0cb91a8d | 1074 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
d247a5d1 | 1075 | { |
41f170fd MT |
1076 | CAmount nValueIn = 0, nReserveValueIn = 0; |
1077 | ||
0cb91a8d SS |
1078 | // Read prev transaction |
1079 | if (!view.HaveCoins(txin.prevout.hash)) | |
d247a5d1 | 1080 | { |
0cb91a8d SS |
1081 | // This should never happen; all transactions in the memory |
1082 | // pool should connect to either transactions in the chain | |
1083 | // or other transactions in the memory pool. | |
1084 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
1085 | { | |
1086 | LogPrintf("ERROR: mempool transaction missing input\n"); | |
1087 | if (fDebug) assert("mempool transaction missing input" == 0); | |
1088 | fMissingInputs = true; | |
1089 | if (porphan) | |
1090 | vOrphan.pop_back(); | |
1091 | break; | |
1092 | } | |
1093 | ||
1094 | // Has to wait for dependencies | |
1095 | if (!porphan) | |
1096 | { | |
1097 | // Use list for automatic deletion | |
1098 | vOrphan.push_back(COrphan(&tx)); | |
1099 | porphan = &vOrphan.back(); | |
1100 | } | |
1101 | mapDependers[txin.prevout.hash].push_back(porphan); | |
1102 | porphan->setDependsOn.insert(txin.prevout.hash); | |
e7e14f44 MT |
1103 | |
1104 | const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx(); | |
e7e14f44 | 1105 | // consider reserve outputs and set priority according to their value here as well |
71a3314d | 1106 | if (!isReserve) |
e7e14f44 | 1107 | { |
71a3314d | 1108 | nTotalIn += otx.vout[txin.prevout.n].nValue; |
e7e14f44 | 1109 | } |
0cb91a8d | 1110 | continue; |
d247a5d1 | 1111 | } |
0cb91a8d SS |
1112 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
1113 | assert(coins); | |
1114 | ||
e7e14f44 | 1115 | // consider reserve outputs and set priority according to their value here as well |
41f170fd | 1116 | if (isReserve) |
e7e14f44 | 1117 | { |
41f170fd | 1118 | nReserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue(); |
e7e14f44 | 1119 | } |
0cb91a8d | 1120 | |
41f170fd | 1121 | nValueIn = coins->vout[txin.prevout.n].nValue; |
0cb91a8d SS |
1122 | int nConf = nHeight - coins->nHeight; |
1123 | ||
41f170fd | 1124 | dPriority += ((double)((nReserveValueIn ? currencyState.ReserveToNative(nReserveValueIn) : 0) + nValueIn)) * nConf; |
71a3314d | 1125 | |
1126 | // reserve is totaled differently | |
1127 | if (!isReserve) | |
1128 | { | |
1129 | nTotalIn += nValueIn; | |
1130 | nTotalReserveIn += nReserveValueIn; | |
1131 | } | |
d247a5d1 | 1132 | } |
9feb4b9e | 1133 | nTotalIn += tx.GetShieldedValueIn(); |
d247a5d1 | 1134 | } |
0cb91a8d | 1135 | |
d247a5d1 | 1136 | if (fMissingInputs) continue; |
e9e70b95 | 1137 | |
d6eb2599 | 1138 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 1139 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 1140 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
e9e70b95 | 1141 | |
41f170fd MT |
1142 | CAmount nDeltaValueIn = nTotalIn + (nTotalReserveIn ? currencyState.ReserveToNative(nTotalReserveIn) : 0); |
1143 | CAmount nFeeValueIn = nDeltaValueIn; | |
1144 | mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn); | |
e7e14f44 | 1145 | |
71a3314d | 1146 | CAmount nativeEquivalentOut = 0; |
e7e14f44 MT |
1147 | |
1148 | // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly | |
41f170fd | 1149 | if (isReserve & rtxd.reserveOut) |
e7e14f44 MT |
1150 | { |
1151 | // if this has reserve currency out, convert it to native currency for fee calculation | |
71a3314d | 1152 | nativeEquivalentOut = currencyState.ReserveToNative(rtxd.reserveOut); |
e7e14f44 MT |
1153 | } |
1154 | ||
71a3314d | 1155 | CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) : nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize); |
e7e14f44 | 1156 | |
d247a5d1 JG |
1157 | if (porphan) |
1158 | { | |
1159 | porphan->dPriority = dPriority; | |
c6cb21d1 | 1160 | porphan->feeRate = feeRate; |
d247a5d1 JG |
1161 | } |
1162 | else | |
e328fa32 | 1163 | vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); |
d247a5d1 | 1164 | } |
df756d24 | 1165 | |
41f170fd MT |
1166 | // |
1167 | // NOW -- REALLY START TO FILL THE BLOCK | |
bb6c3482 | 1168 | // |
41f170fd | 1169 | // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required |
e7c700b5 | 1170 | |
41f170fd | 1171 | int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize); |
e7e14f44 | 1172 | |
355ca565 | 1173 | int64_t interest; |
d247a5d1 | 1174 | bool fSortedByFee = (nBlockPrioritySize <= 0); |
41f170fd | 1175 | |
d247a5d1 JG |
1176 | TxPriorityCompare comparer(fSortedByFee); |
1177 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
41f170fd MT |
1178 | |
1179 | std::vector<int> reservePositions; | |
1180 | ||
1181 | // now loop and fill the block, leaving space for reserve exchange limit transactions | |
d247a5d1 JG |
1182 | while (!vecPriority.empty()) |
1183 | { | |
1184 | // Take highest priority transaction off the priority queue: | |
1185 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 1186 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 1187 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
e9e70b95 | 1188 | |
d247a5d1 JG |
1189 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1190 | vecPriority.pop_back(); | |
e9e70b95 | 1191 | |
d247a5d1 JG |
1192 | // Size limits |
1193 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd | 1194 | if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx |
61f8caf2 | 1195 | { |
41f170fd | 1196 | //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize); |
d247a5d1 | 1197 | continue; |
61f8caf2 | 1198 | } |
e9e70b95 | 1199 | |
d247a5d1 JG |
1200 | // Legacy limits on sigOps: |
1201 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
a4a40a38 | 1202 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 1203 | { |
51376f3c | 1204 | //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 | 1205 | continue; |
61f8caf2 | 1206 | } |
d247a5d1 | 1207 | // Skip free transactions if we're past the minimum block size: |
805344dc | 1208 | const uint256& hash = tx.GetHash(); |
2a72d459 | 1209 | double dPriorityDelta = 0; |
a372168e | 1210 | CAmount nFeeDelta = 0; |
2a72d459 | 1211 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 1212 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
61f8caf2 | 1213 | { |
51376f3c | 1214 | //fprintf(stderr,"fee rate skip\n"); |
d247a5d1 | 1215 | continue; |
61f8caf2 | 1216 | } |
41f170fd | 1217 | |
2a72d459 | 1218 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
1219 | // transactions: |
1220 | if (!fSortedByFee && | |
1221 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
1222 | { | |
1223 | fSortedByFee = true; | |
1224 | comparer = TxPriorityCompare(fSortedByFee); | |
1225 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
1226 | } | |
e9e70b95 | 1227 | |
d247a5d1 | 1228 | if (!view.HaveInputs(tx)) |
61f8caf2 | 1229 | { |
51376f3c | 1230 | //fprintf(stderr,"dont have inputs\n"); |
d247a5d1 | 1231 | continue; |
61f8caf2 | 1232 | } |
41f170fd MT |
1233 | CAmount nTxFees; |
1234 | CReserveTransactionDescriptor txDesc; | |
1235 | bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc); | |
1236 | ||
88bc6df5 MT |
1237 | nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); |
1238 | ||
1239 | nTxSigOps += GetP2SHSigOpCount(tx, view); | |
1240 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) | |
41f170fd | 1241 | { |
88bc6df5 MT |
1242 | //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
1243 | continue; | |
61f8caf2 | 1244 | } |
41f170fd | 1245 | |
68f7d1d7 PT |
1246 | // Note that flags: we don't want to set mempool/IsStandard() |
1247 | // policy here, but we still have to ensure that the block we | |
1248 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 1249 | CValidationState state; |
6514771a | 1250 | PrecomputedTransactionData txdata(tx); |
be126699 | 1251 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) |
61f8caf2 | 1252 | { |
51376f3c | 1253 | //fprintf(stderr,"context failure\n"); |
d247a5d1 | 1254 | continue; |
61f8caf2 | 1255 | } |
e7e14f44 | 1256 | |
8cb98d91 | 1257 | UpdateCoins(tx, view, nHeight); |
d247a5d1 | 1258 | |
41f170fd MT |
1259 | if (isReserve) |
1260 | { | |
88bc6df5 | 1261 | nTxFees = 0; // we will adjust all reserve transaction fees when we get an accurate conversion rate |
41f170fd MT |
1262 | reservePositions.push_back(nBlockTx); |
1263 | haveReserveTransactions = true; | |
1264 | } | |
1265 | ||
31a04d28 SB |
1266 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1267 | sapling_tree.append(outDescription.cm); | |
1268 | } | |
1269 | ||
d247a5d1 JG |
1270 | // Added |
1271 | pblock->vtx.push_back(tx); | |
1272 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1273 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1274 | nBlockSize += nTxSize; | |
1275 | ++nBlockTx; | |
1276 | nBlockSigOps += nTxSigOps; | |
1277 | nFees += nTxFees; | |
e9e70b95 | 1278 | |
d247a5d1 JG |
1279 | if (fPrintPriority) |
1280 | { | |
3f0813b3 | 1281 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 | 1282 | } |
e9e70b95 | 1283 | |
d247a5d1 JG |
1284 | // Add transactions that depend on this one to the priority queue |
1285 | if (mapDependers.count(hash)) | |
1286 | { | |
1287 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
1288 | { | |
1289 | if (!porphan->setDependsOn.empty()) | |
1290 | { | |
1291 | porphan->setDependsOn.erase(hash); | |
1292 | if (porphan->setDependsOn.empty()) | |
1293 | { | |
c6cb21d1 | 1294 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
1295 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1296 | } | |
1297 | } | |
1298 | } | |
1299 | } | |
1300 | } | |
e7c700b5 | 1301 | |
41f170fd MT |
1302 | // if we have reserve transactions or limit transactions to add: |
1303 | // 1. collect all the reserve transactions from the block and add them to the reserveFills vector | |
1304 | // 2. add all limit transactions to the orders vector | |
1305 | // 3. match orders to include all limit transactions that qualify and will fit | |
1306 | if (haveReserveTransactions) | |
1307 | { | |
1308 | std::vector<CReserveTransactionDescriptor> reserveFills; | |
1309 | std::vector<const CTransaction *> expiredFillOrKills; | |
1310 | std::vector<const CTransaction *> noFills; | |
1311 | std::vector<const CTransaction *> rejects; | |
e7c700b5 | 1312 | |
41f170fd MT |
1313 | // identify all reserve transactions in the block to calculate fees |
1314 | for (int i = 0; i < reservePositions.size(); i++) | |
1315 | { | |
1316 | CReserveTransactionDescriptor txDesc; | |
0059e3a5 | 1317 | if (mempool.IsKnownReserveTransaction(pblock->vtx[reservePositions[i]].GetHash(), txDesc)) |
41f170fd MT |
1318 | { |
1319 | reserveFills.push_back(txDesc); | |
1320 | } | |
1321 | } | |
135fa24e | 1322 | |
41f170fd MT |
1323 | // now, we need to have room for the transaction which will spend the coinbase |
1324 | // and output all conversions mined/staked | |
1325 | newConversionOutputTx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); | |
9e87ac50 | 1326 | newConversionOutputTx.vin.resize(1); // placeholder for size calculation |
41f170fd MT |
1327 | |
1328 | int64_t newBlockSize = nBlockSize; | |
88bc6df5 | 1329 | |
47aecf2f | 1330 | // TODO:PBAAS - NEED TO ADD SIGOPS LIMIT TO THIS FOR HARDENING |
1331 | CCoinbaseCurrencyState newState = currencyState.MatchOrders(limitOrders, | |
1332 | reserveFills, | |
1333 | expiredFillOrKills, | |
1334 | noFills, | |
1335 | rejects, | |
1336 | exchangeRate, nHeight, conversionInputs, | |
1337 | nBlockMaxSize - autoTxSize, &newBlockSize, &newConversionOutputTx); | |
88bc6df5 MT |
1338 | |
1339 | assert(reserveFills.size() >= reservePositions.size()); | |
41f170fd MT |
1340 | |
1341 | // create the conversion transaction and all outputs indicated by every single mined transaction | |
1342 | CAmount nativeConversionFees = 0; | |
1343 | CAmount reserveConversionFees = 0; | |
1344 | if (reserveFills.size()) | |
1345 | { | |
607402ba | 1346 | currencyState = newState; |
41f170fd | 1347 | } |
86e31e3d | 1348 | |
88bc6df5 | 1349 | int oldRPSize = reservePositions.size(); |
41f170fd | 1350 | |
88bc6df5 MT |
1351 | // add the rest of the reserve fills that have not yet been added to the block, |
1352 | for (int i = oldRPSize; i < reserveFills.size(); i++) | |
1f722359 | 1353 | { |
88bc6df5 MT |
1354 | // add these transactions to the block |
1355 | reservePositions.push_back(nBlockTx); | |
1356 | pblock->vtx.push_back(*reserveFills[i].ptx); | |
1357 | const CTransaction &tx = pblock->vtx.back(); | |
cd230e37 | 1358 | |
88bc6df5 | 1359 | UpdateCoins(tx, view, nHeight); |
41f170fd | 1360 | |
88bc6df5 MT |
1361 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1362 | sapling_tree.append(outDescription.cm); | |
1363 | } | |
41f170fd | 1364 | |
88bc6df5 MT |
1365 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); |
1366 | uint32_t nTxSigOps = GetLegacySigOpCount(tx); | |
41f170fd | 1367 | |
88bc6df5 MT |
1368 | // size was already updated |
1369 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1370 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1371 | ++nBlockTx; | |
1372 | nBlockSigOps += nTxSigOps; | |
1373 | nFees += nTxFees; | |
1f722359 | 1374 | } |
41f170fd | 1375 | |
88bc6df5 MT |
1376 | // update block size with the calculation from the function called, which includes all additional transactions, |
1377 | // but does not include the conversion transaction, since its final size is still unknown | |
1378 | nBlockSize = newBlockSize; | |
41f170fd | 1379 | |
88bc6df5 MT |
1380 | // fixup the transaction block template fees that were added before we knew the correct exchange rate and |
1381 | // add them to the block fee total | |
1382 | for (int i = 0; i < oldRPSize; i++) | |
1383 | { | |
1384 | assert(pblocktemplate->vTxFees.size() > reservePositions[i]); | |
1385 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); | |
1386 | pblocktemplate->vTxFees[reservePositions[i]] = nTxFees; | |
1387 | nFees += nTxFees; | |
1f722359 MT |
1388 | } |
1389 | ||
88bc6df5 | 1390 | // remake the newConversionOutputTx, right now, it has dummy inputs and placeholder outputs, just remake it correctly |
9e87ac50 | 1391 | newConversionOutputTx.vin.resize(1); |
88bc6df5 | 1392 | newConversionOutputTx.vout.clear(); |
0574c740 | 1393 | conversionInputs.clear(); |
1394 | ||
9e87ac50 | 1395 | // keep one placeholder for txCoinbase output as input and remake with the correct exchange rate |
88bc6df5 | 1396 | for (auto fill : reserveFills) |
a4a40a38 | 1397 | { |
0574c740 | 1398 | fill.AddConversionInOuts(newConversionOutputTx, conversionInputs, exchangeRate, ¤cyState); |
41f170fd | 1399 | } |
41f170fd MT |
1400 | |
1401 | // update the currency state | |
1402 | currencyState.ConversionPrice = exchangeRate; | |
a4a40a38 | 1403 | } |
abb90a89 | 1404 | |
88bc6df5 | 1405 | currencyState.Fees = nFees; |
41f170fd | 1406 | |
88bc6df5 MT |
1407 | // first calculate and distribute block rewards, including fees as specified in the minerOutputs vector |
1408 | CAmount rewardTotalShareAmount = 0; | |
1409 | CAmount rewardTotal = blockSubsidy + nFees; | |
d6f7d693 | 1410 | CAmount rewardLeft = notarizationTxIndex ? rewardTotal - notarizationOut.nValue : rewardTotal; |
41f170fd | 1411 | |
88bc6df5 MT |
1412 | for (auto &outputShare : minerOutputs) |
1413 | { | |
1414 | rewardTotalShareAmount += outputShare.first; | |
1415 | } | |
41f170fd | 1416 | |
88bc6df5 MT |
1417 | int cbOutIdx; |
1418 | for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++) | |
1419 | { | |
1420 | CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].first) / arith_uint256(rewardTotalShareAmount)).GetLow64(); | |
1421 | if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size()) | |
1422 | { | |
1423 | amount = rewardLeft; | |
1424 | } | |
1425 | rewardLeft -= amount; | |
1426 | coinbaseTx.vout[cbOutIdx].nValue = amount; | |
1427 | // the only valid CC output we currently support on coinbases is stake guard, which does not need to be modified for this | |
1428 | } | |
41f170fd | 1429 | |
88bc6df5 | 1430 | // update all remaining coinbase outputs |
41f170fd | 1431 | |
88bc6df5 MT |
1432 | // premineOut - done |
1433 | if (premineOut.scriptPubKey.size()) | |
1434 | { | |
1435 | cbOutIdx++; | |
1436 | } | |
41f170fd | 1437 | |
88bc6df5 MT |
1438 | // chainDefinitionOut - done |
1439 | if (chainDefinitionOut.scriptPubKey.size()) | |
1440 | { | |
1441 | cbOutIdx++; | |
1442 | } | |
41f170fd | 1443 | |
88bc6df5 MT |
1444 | // importThreadOut - done |
1445 | if (importThreadOut.scriptPubKey.size()) | |
1446 | { | |
1447 | cbOutIdx++; | |
1448 | } | |
41f170fd | 1449 | |
88bc6df5 | 1450 | // exportThreadOut - done |
40951949 | 1451 | if (exportThreadOut.scriptPubKey.size()) |
88bc6df5 MT |
1452 | { |
1453 | cbOutIdx++; | |
1454 | } | |
1455 | ||
90888b8a | 1456 | // currencyStateOut - update currency state, output is present whether or not there is a conversion transaction |
88bc6df5 | 1457 | // the transaction itself pays no fees, but all conversion fees are included for each conversion transaction between its input and this output |
90888b8a | 1458 | if (currencyStateOut.scriptPubKey.size()) |
88bc6df5 | 1459 | { |
19f01561 | 1460 | COptCCParams p; |
1461 | currencyStateOut.scriptPubKey.IsPayToCryptoCondition(p); | |
1462 | p.vData[0] = currencyState.AsVector(); | |
1463 | currencyStateOut.scriptPubKey.ReplaceCCParams(p); | |
1464 | ||
90888b8a | 1465 | if (newConversionOutputTx.vout.size()) |
1466 | { | |
90888b8a | 1467 | CTransaction convertTx(newConversionOutputTx); |
90888b8a | 1468 | |
e5e3cb6e | 1469 | assert(convertTx.GetValueOut() <= currencyState.ReserveToNative(currencyState.ReserveIn, currencyState.ConversionPrice)); |
1470 | ||
1471 | currencyStateOut.nValue = currencyState.ReserveToNative(currencyState.ReserveIn, currencyState.ConversionPrice); | |
45d7e5d5 | 1472 | |
90888b8a | 1473 | // the coinbase is not finished, store index placeholder here now and fixup hash later |
1474 | newConversionOutputTx.vin[0] = CTxIn(uint256(), cbOutIdx); | |
1475 | } | |
88bc6df5 MT |
1476 | |
1477 | coinbaseTx.vout[cbOutIdx] = currencyStateOut; | |
88bc6df5 MT |
1478 | cbOutIdx++; |
1479 | } | |
06f41160 | 1480 | |
88bc6df5 MT |
1481 | // notarizationOut - update currencyState in notarization |
1482 | if (notarizationTxIndex) | |
06f41160 | 1483 | { |
88bc6df5 MT |
1484 | COptCCParams p; |
1485 | int i; | |
1486 | for (i = 0; i < newNotarizationTx.vout.size(); i++) | |
06f41160 | 1487 | { |
88bc6df5 | 1488 | if (newNotarizationTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.evalCode == EVAL_EARNEDNOTARIZATION) |
86e31e3d | 1489 | { |
88bc6df5 | 1490 | break; |
86e31e3d | 1491 | } |
1492 | } | |
88bc6df5 | 1493 | if (i >= newNotarizationTx.vout.size()) |
86e31e3d | 1494 | { |
88bc6df5 MT |
1495 | LogPrintf("CreateNewBlock: bad notarization\n"); |
1496 | fprintf(stderr,"CreateNewBlock: bad notarization\n"); | |
1497 | return NULL; | |
ebee7b5b | 1498 | } |
88bc6df5 MT |
1499 | CPBaaSNotarization nz(p.vData[0]); |
1500 | nz.currencyState = currencyState; | |
1501 | p.vData[0] = nz.AsVector(); | |
1502 | newNotarizationTx.vout[i].scriptPubKey.ReplaceCCParams(p); | |
1503 | ||
1504 | notarizationOut.scriptPubKey.IsPayToCryptoCondition(p); | |
1505 | p.vData[0] = nz.AsVector(); | |
1506 | notarizationOut.scriptPubKey.ReplaceCCParams(p); | |
1507 | ||
1508 | coinbaseTx.vout[cbOutIdx] = notarizationOut; | |
1509 | ||
1510 | // now that the coinbase is finished, finish and place conversion transaction before the stake transaction | |
1511 | newNotarizationTx.vin.push_back(CTxIn(uint256(), cbOutIdx)); | |
1512 | ||
1513 | cbOutIdx++; | |
1514 | ||
1515 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; | |
ebee7b5b | 1516 | } |
06f41160 | 1517 | |
88bc6df5 MT |
1518 | // this should be the end of the outputs |
1519 | assert(cbOutIdx == coinbaseTx.vout.size()); | |
1520 | ||
1521 | nLastBlockTx = nBlockTx; | |
1522 | nLastBlockSize = nBlockSize; | |
1523 | ||
1524 | blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime()); | |
1525 | ||
1526 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); | |
1527 | ||
41f170fd | 1528 | coinbaseTx.nExpiryHeight = 0; |
88bc6df5 | 1529 | coinbaseTx.nLockTime = blocktime; |
abb90a89 | 1530 | |
e0bc68e6 | 1531 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
41f170fd | 1532 | coinbaseTx.vout[0].nValue += 5000; |
5034d1c1 | 1533 | |
88bc6df5 | 1534 | /* |
29bd53a1 | 1535 | // check if coinbase transactions must be time locked at current subsidy and prepend the time lock |
a0dd01bc | 1536 | // to transaction if so, cast for GTE operator |
ebee7b5b | 1537 | CAmount cbValueOut = 0; |
41f170fd | 1538 | for (auto txout : coinbaseTx.vout) |
ebee7b5b MT |
1539 | { |
1540 | cbValueOut += txout.nValue; | |
1541 | } | |
1542 | if (cbValueOut >= ASSETCHAINS_TIMELOCKGTE) | |
abb90a89 MT |
1543 | { |
1544 | int32_t opretlen, p2shlen, scriptlen; | |
29bd53a1 | 1545 | CScriptExt opretScript = CScriptExt(); |
abb90a89 | 1546 | |
41f170fd | 1547 | coinbaseTx.vout.push_back(CTxOut()); |
abb90a89 | 1548 | |
29bd53a1 MT |
1549 | // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins |
1550 | // protected only by the time lock rather than 100% inaccessible | |
1551 | opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight)); | |
06f41160 | 1552 | if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition()) |
1553 | { | |
514fde1b | 1554 | LogPrintf("CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
86e31e3d | 1555 | fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
06f41160 | 1556 | return 0; |
1557 | } | |
1558 | ||
1559 | opretScript += scriptPubKeyIn; | |
abb90a89 | 1560 | |
41f170fd MT |
1561 | coinbaseTx.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript)); |
1562 | coinbaseTx.vout.back().scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK); | |
1563 | coinbaseTx.vout.back().nValue = 0; | |
48d800c2 | 1564 | } // timelocks and commissions are currently incompatible due to validation complexity of the combination |
5034d1c1 | 1565 | else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) |
c9b1071d | 1566 | { |
c000c9ca | 1567 | int32_t i; uint8_t *ptr; |
41f170fd MT |
1568 | coinbaseTx.vout.resize(2); |
1569 | coinbaseTx.vout[1].nValue = commission; | |
1570 | coinbaseTx.vout[1].scriptPubKey.resize(35); | |
1571 | ptr = (uint8_t *)&coinbaseTx.vout[1].scriptPubKey[0]; | |
c000c9ca | 1572 | ptr[0] = 33; |
1573 | for (i=0; i<33; i++) | |
1574 | ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i]; | |
1575 | ptr[34] = OP_CHECKSIG; | |
146d2aa2 | 1576 | //printf("autocreate commision vout\n"); |
c9b1071d | 1577 | } |
88bc6df5 | 1578 | */ |
48d800c2 | 1579 | |
ebee7b5b | 1580 | // finalize input of coinbase |
41f170fd MT |
1581 | coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS; |
1582 | assert(coinbaseTx.vin[0].scriptSig.size() <= 100); | |
ebee7b5b | 1583 | |
88bc6df5 MT |
1584 | // coinbase is done |
1585 | pblock->vtx[0] = coinbaseTx; | |
1586 | uint256 cbHash = coinbaseTx.GetHash(); | |
68b309c0 | 1587 | |
88bc6df5 | 1588 | // if there is a conversion, update the correct coinbase hash and add it to the block |
34d1aa13 MT |
1589 | // we also need to sign the conversion transaction |
1590 | if (newConversionOutputTx.vin.size() > 1) | |
88bc6df5 | 1591 | { |
a6b1eaf9 | 1592 | // put the coinbase into the updated coins, since we will spend from it |
1593 | UpdateCoins(pblock->vtx[0], view, nHeight); | |
1594 | ||
88bc6df5 | 1595 | newConversionOutputTx.vin[0].prevout.hash = cbHash; |
0574c740 | 1596 | |
1597 | CTransaction ncoTx(newConversionOutputTx); | |
1598 | ||
1599 | // sign transaction for cb output and conversions | |
1600 | for (int i = 0; i < ncoTx.vin.size(); i++) | |
1601 | { | |
1602 | bool signSuccess; | |
1603 | SignatureData sigdata; | |
1604 | CAmount value; | |
1605 | const CScript *pScriptPubKey; | |
1606 | ||
1607 | const CScript virtualCC; | |
1608 | CTxOut virtualCCOut; | |
1609 | ||
1610 | // if this is our coinbase input, different signing | |
1611 | if (i) | |
1612 | { | |
1613 | pScriptPubKey = &conversionInputs[i - 1].scriptPubKey; | |
1614 | value = conversionInputs[i - 1].nValue; | |
1615 | } | |
1616 | else | |
1617 | { | |
1618 | pScriptPubKey = &coinbaseTx.vout[ncoTx.vin[i].prevout.n].scriptPubKey; | |
1619 | value = coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue; | |
1620 | } | |
1621 | ||
1622 | signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ncoTx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId); | |
1623 | ||
1624 | if (!signSuccess) | |
1625 | { | |
1626 | if (ncoTx.vin[i].prevout.hash == coinbaseTx.GetHash()) | |
1627 | { | |
1628 | LogPrintf("Coinbase conversion source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); | |
1629 | printf("Coinbase conversion source tx - amount: %lu, n: %d, id: %s\n", coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue, ncoTx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str()); | |
1630 | } | |
1631 | LogPrintf("CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\n", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str()); | |
1632 | printf("CreateNewBlock: failure to sign conversion tx for input %d from output %d of %s\n", i, ncoTx.vin[i].prevout.n, ncoTx.vin[i].prevout.hash.GetHex().c_str()); | |
1633 | return NULL; | |
1634 | } else { | |
1635 | UpdateTransaction(newConversionOutputTx, i, sigdata); | |
1636 | } | |
1637 | } | |
1638 | ||
88bc6df5 MT |
1639 | UpdateCoins(newConversionOutputTx, view, nHeight); |
1640 | pblock->vtx.push_back(newConversionOutputTx); | |
1641 | pblocktemplate->vTxFees.push_back(0); | |
1642 | int txSigOps = GetLegacySigOpCount(newConversionOutputTx); | |
1643 | pblocktemplate->vTxSigOps.push_back(txSigOps); | |
1644 | nBlockSize += GetSerializeSize(newConversionOutputTx, SER_NETWORK, PROTOCOL_VERSION); | |
1645 | ++nBlockTx; | |
1646 | nBlockSigOps += txSigOps; | |
1647 | } | |
68b309c0 | 1648 | |
88bc6df5 MT |
1649 | // if there is a stake transaction, add it to the very end |
1650 | if (isStake) | |
1651 | { | |
1652 | UpdateCoins(txStaked, view, nHeight); | |
1653 | pblock->vtx.push_back(txStaked); | |
1654 | pblocktemplate->vTxFees.push_back(0); | |
1655 | int txSigOps = GetLegacySigOpCount(txStaked); | |
1656 | pblocktemplate->vTxSigOps.push_back(txSigOps); | |
1657 | // already added to the block size above | |
1658 | ++nBlockTx; | |
1659 | nBlockSigOps += txSigOps; | |
1660 | } | |
68b309c0 | 1661 | |
88bc6df5 | 1662 | extern CWallet *pwalletMain; |
8577896f | 1663 | |
88bc6df5 MT |
1664 | // add final notarization and instant spend coinbase output hash fixup |
1665 | if (notarizationTxIndex) | |
1666 | { | |
1667 | LOCK(pwalletMain->cs_wallet); | |
eb0a6550 | 1668 | |
88bc6df5 | 1669 | newNotarizationTx.vin.back().prevout.hash = cbHash; |
68b309c0 | 1670 | |
88bc6df5 | 1671 | CTransaction ntx(newNotarizationTx); |
68b309c0 | 1672 | |
13ed2980 | 1673 | for (int i = 0; i < ntx.vin.size(); i++) |
68b309c0 MT |
1674 | { |
1675 | bool signSuccess; | |
68b309c0 | 1676 | SignatureData sigdata; |
eb0a6550 | 1677 | CAmount value; |
1678 | const CScript *pScriptPubKey; | |
8577896f | 1679 | |
1680 | const CScript virtualCC; | |
1681 | CTxOut virtualCCOut; | |
1682 | ||
13ed2980 MT |
1683 | // if this is our coinbase input, we won't find it elsewhere |
1684 | if (i < notarizationInputs.size()) | |
eb0a6550 | 1685 | { |
13ed2980 MT |
1686 | pScriptPubKey = ¬arizationInputs[i].scriptPubKey; |
1687 | value = notarizationInputs[i].nValue; | |
eb0a6550 | 1688 | } |
1689 | else | |
1690 | { | |
41f170fd MT |
1691 | pScriptPubKey = &coinbaseTx.vout[ntx.vin[i].prevout.n].scriptPubKey; |
1692 | value = coinbaseTx.vout[ntx.vin[i].prevout.n].nValue; | |
eb0a6550 | 1693 | } |
8577896f | 1694 | |
eb0a6550 | 1695 | signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId); |
68b309c0 MT |
1696 | |
1697 | if (!signSuccess) | |
1698 | { | |
41f170fd | 1699 | if (ntx.vin[i].prevout.hash == coinbaseTx.GetHash()) |
4edfdbb0 | 1700 | { |
41f170fd MT |
1701 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1702 | printf("Coinbase source tx - amount: %lu, n: %d, id: %s\n", coinbaseTx.vout[ntx.vin[i].prevout.n].nValue, ntx.vin[i].prevout.n, coinbaseTx.GetHash().GetHex().c_str()); | |
4edfdbb0 MT |
1703 | } |
1704 | LogPrintf("CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\n", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str()); | |
1705 | printf("CreateNewBlock: failure to sign earned notarization for input %d from output %d of %s\n", i, ntx.vin[i].prevout.n, ntx.vin[i].prevout.hash.GetHex().c_str()); | |
68b309c0 MT |
1706 | return NULL; |
1707 | } else { | |
88bc6df5 | 1708 | UpdateTransaction(newNotarizationTx, i, sigdata); |
68b309c0 MT |
1709 | } |
1710 | } | |
88bc6df5 | 1711 | pblocktemplate->vTxSigOps[notarizationTxIndex] = GetLegacySigOpCount(newNotarizationTx); |
13ed2980 MT |
1712 | |
1713 | // put now signed notarization back in the block | |
88bc6df5 | 1714 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; |
f3be524a | 1715 | |
41f170fd MT |
1716 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1717 | //printf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); | |
88bc6df5 | 1718 | LogPrintf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, newNotarizationTx.GetHash().GetHex().c_str()); |
989b1de1 | 1719 | //printf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, mntx.GetHash().GetHex().c_str()); |
f3be524a MT |
1720 | { |
1721 | LOCK(cs_main); | |
88bc6df5 | 1722 | for (auto input : newNotarizationTx.vin) |
f3be524a | 1723 | { |
1026ac58 | 1724 | LogPrintf("Earned notarization input n: %d, hash: %s, HaveCoins: %s\n", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? "true" : "false"); |
514fde1b | 1725 | //printf("Earned notarization input n: %d, hash: %s, HaveCoins: %s\n", input.prevout.n, input.prevout.hash.GetHex().c_str(), pcoinsTip->HaveCoins(input.prevout.hash) ? "true" : "false"); |
f3be524a MT |
1726 | } |
1727 | } | |
68b309c0 MT |
1728 | } |
1729 | ||
41f170fd | 1730 | pblock->vtx[0] = coinbaseTx; |
d247a5d1 | 1731 | pblocktemplate->vTxFees[0] = -nFees; |
88bc6df5 | 1732 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
48d800c2 | 1733 | |
1fae37f6 MT |
1734 | // if not Verus stake, setup nonce, otherwise, leave it alone |
1735 | if (!isStake || ASSETCHAINS_LWMAPOS == 0) | |
1736 | { | |
eb0a6550 | 1737 | // Randomize nonce |
1fae37f6 | 1738 | arith_uint256 nonce = UintToArith256(GetRandHash()); |
48d800c2 | 1739 | |
1fae37f6 MT |
1740 | // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters) |
1741 | nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO]; | |
1742 | nonce >>= 16; | |
1743 | pblock->nNonce = ArithToUint256(nonce); | |
1744 | } | |
e9e70b95 | 1745 | |
d247a5d1 JG |
1746 | // Fill in header |
1747 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
31a04d28 | 1748 | pblock->hashFinalSaplingRoot = sapling_tree.root(); |
0c8fa56a MT |
1749 | |
1750 | // all Verus PoS chains need this data in the block at all times | |
1751 | if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 ) | |
9a0f2798 | 1752 | { |
1753 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
1fae37f6 | 1754 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
9a0f2798 | 1755 | } |
12217420 | 1756 | |
4d068367 | 1757 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
af805d53 | 1758 | { |
28a62b60 | 1759 | uint32_t r; |
496f1fd2 | 1760 | CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
fa04bcf3 | 1761 | if ( pblock->nTime < pindexPrev->nTime+60 ) |
1762 | pblock->nTime = pindexPrev->nTime + 60; | |
16593898 | 1763 | if ( gpucount < 33 ) |
28a62b60 | 1764 | { |
55566f16 | 1765 | uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals; |
28a62b60 | 1766 | memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid); |
1767 | memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height); | |
1768 | memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock); | |
9a146fef | 1769 | vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n); |
55566f16 | 1770 | memcpy(&r,&randvals,sizeof(r)); |
1771 | pblock->nTime += (r % (33 - gpucount)*(33 - gpucount)); | |
28a62b60 | 1772 | } |
a893e994 | 1773 | if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 ) |
496f1fd2 | 1774 | { |
2d79309f | 1775 | CAmount txfees = 5000; |
496f1fd2 | 1776 | pblock->vtx.push_back(txNotary); |
1777 | pblocktemplate->vTxFees.push_back(txfees); | |
1778 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary)); | |
1779 | nFees += txfees; | |
2d79309f | 1780 | pblocktemplate->vTxFees[0] = -nFees; |
c881e52b | 1781 | //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees; |
f31815fc | 1782 | //fprintf(stderr,"added notaryvin\n"); |
0857c3d5 | 1783 | } |
1784 | else | |
1785 | { | |
1786 | fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n"); | |
1787 | return(0); | |
1788 | } | |
707b061c | 1789 | } |
809f2e25 | 1790 | else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) |
af805d53 | 1791 | { |
8fc79ac9 | 1792 | CValidationState state; |
809f2e25 | 1793 | //fprintf(stderr,"check validity\n"); |
1794 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks | |
8fc79ac9 | 1795 | { |
9feb4b9e | 1796 | throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
8fc79ac9 | 1797 | } |
809f2e25 | 1798 | //fprintf(stderr,"valid\n"); |
af805d53 | 1799 | } |
d247a5d1 | 1800 | } |
2a6a442a | 1801 | //fprintf(stderr,"done new block\n"); |
1685bba0 MT |
1802 | |
1803 | // setup the header and buid the Merkle tree | |
1804 | unsigned int extraNonce; | |
1805 | IncrementExtraNonce(pblock, pindexPrev, extraNonce); | |
1806 | ||
d247a5d1 JG |
1807 | return pblocktemplate.release(); |
1808 | } | |
32b915c9 | 1809 | |
1a31463b | 1810 | /* |
e9e70b95 | 1811 | #ifdef ENABLE_WALLET |
1812 | boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey) | |
1813 | #else | |
1814 | boost::optional<CScript> GetMinerScriptPubKey() | |
1815 | #endif | |
1816 | { | |
1817 | CKeyID keyID; | |
1818 | CBitcoinAddress addr; | |
1819 | if (addr.SetString(GetArg("-mineraddress", ""))) { | |
1820 | addr.GetKeyID(keyID); | |
1821 | } else { | |
1822 | #ifdef ENABLE_WALLET | |
1823 | CPubKey pubkey; | |
1824 | if (!reservekey.GetReservedKey(pubkey)) { | |
1825 | return boost::optional<CScript>(); | |
1826 | } | |
1827 | keyID = pubkey.GetID(); | |
1828 | #else | |
1829 | return boost::optional<CScript>(); | |
1830 | #endif | |
1831 | } | |
1832 | ||
1833 | CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
1834 | return scriptPubKey; | |
1835 | } | |
1836 | ||
1837 | #ifdef ENABLE_WALLET | |
1838 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) | |
1839 | { | |
1840 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey); | |
1841 | #else | |
1842 | CBlockTemplate* CreateNewBlockWithKey() | |
1843 | { | |
1844 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(); | |
1845 | #endif | |
1846 | ||
1847 | if (!scriptPubKey) { | |
1848 | return NULL; | |
1849 | } | |
1850 | return CreateNewBlock(*scriptPubKey); | |
1851 | }*/ | |
acfa0333 | 1852 | |
c1de826f JG |
1853 | ////////////////////////////////////////////////////////////////////////////// |
1854 | // | |
1855 | // Internal miner | |
1856 | // | |
1857 | ||
2cc0a252 | 1858 | #ifdef ENABLE_MINING |
c1de826f | 1859 | |
4a85e067 | 1860 | #ifdef ENABLE_WALLET |
acfa0333 WL |
1861 | ////////////////////////////////////////////////////////////////////////////// |
1862 | // | |
1863 | // Internal miner | |
1864 | // | |
acfa0333 | 1865 | |
5034d1c1 | 1866 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake) |
acfa0333 | 1867 | { |
9feb4b9e | 1868 | CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i; |
d9f176ac | 1869 | if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 ) |
1870 | { | |
1871 | scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG; | |
1872 | } | |
1873 | else if ( USE_EXTERNAL_PUBKEY != 0 ) | |
998397aa | 1874 | { |
7bfc207a | 1875 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 1876 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 1877 | } |
1878 | else | |
1879 | { | |
f1f6dfbb | 1880 | if (!isStake) |
1b5b89ba | 1881 | { |
f1f6dfbb | 1882 | if (!reservekey.GetReservedKey(pubkey)) |
1883 | { | |
1884 | return NULL; | |
1885 | } | |
1886 | scriptPubKey.resize(35); | |
1887 | ptr = (uint8_t *)pubkey.begin(); | |
1888 | scriptPubKey[0] = 33; | |
1889 | for (i=0; i<33; i++) | |
1890 | scriptPubKey[i+1] = ptr[i]; | |
1891 | scriptPubKey[34] = OP_CHECKSIG; | |
1892 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
1b5b89ba | 1893 | } |
f6c647ed | 1894 | } |
5034d1c1 | 1895 | return CreateNewBlock(scriptPubKey, gpucount, isStake); |
acfa0333 WL |
1896 | } |
1897 | ||
395f10cf | 1898 | void komodo_broadcast(CBlock *pblock,int32_t limit) |
1899 | { | |
1900 | int32_t n = 1; | |
1901 | //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1902 | { | |
1903 | LOCK(cs_vNodes); | |
1904 | BOOST_FOREACH(CNode* pnode, vNodes) | |
1905 | { | |
1906 | if ( pnode->hSocket == INVALID_SOCKET ) | |
1907 | continue; | |
1908 | if ( (rand() % n) == 0 ) | |
1909 | { | |
1910 | pnode->PushMessage("block", *pblock); | |
1911 | if ( n++ > limit ) | |
1912 | break; | |
1913 | } | |
1914 | } | |
1915 | } | |
1916 | //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1917 | } | |
945f015d | 1918 | |
269d8ba0 | 1919 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
8e8b6d70 JG |
1920 | #else |
1921 | static bool ProcessBlockFound(CBlock* pblock) | |
1922 | #endif // ENABLE_WALLET | |
d247a5d1 | 1923 | { |
572c763f | 1924 | int32_t height = chainActive.LastTip()->GetHeight()+1; |
81212588 | 1925 | LogPrintf("%s\n", pblock->ToString()); |
572c763f | 1926 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue), height); |
e9e70b95 | 1927 | |
d247a5d1 JG |
1928 | // Found a solution |
1929 | { | |
86131275 | 1930 | if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash()) |
ba8419c7 | 1931 | { |
1932 | uint256 hash; int32_t i; | |
1933 | hash = pblock->hashPrevBlock; | |
92266e99 | 1934 | for (i=31; i>=0; i--) |
ba8419c7 | 1935 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 1936 | fprintf(stderr," <- prev (stale)\n"); |
86131275 | 1937 | hash = chainActive.LastTip()->GetBlockHash(); |
92266e99 | 1938 | for (i=31; i>=0; i--) |
ba8419c7 | 1939 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 1940 | fprintf(stderr," <- chainTip (stale)\n"); |
e9e70b95 | 1941 | |
ffde1589 | 1942 | return error("VerusMiner: generated block is stale"); |
ba8419c7 | 1943 | } |
18e72167 | 1944 | } |
e9e70b95 | 1945 | |
8e8b6d70 | 1946 | #ifdef ENABLE_WALLET |
18e72167 | 1947 | // Remove key from key pool |
998397aa | 1948 | if ( IS_KOMODO_NOTARY == 0 ) |
945f015d | 1949 | { |
1950 | if (GetArg("-mineraddress", "").empty()) { | |
1951 | // Remove key from key pool | |
1952 | reservekey.KeepKey(); | |
1953 | } | |
8e8b6d70 | 1954 | } |
18e72167 | 1955 | // Track how many getdata requests this block gets |
438ba9c1 | 1956 | //if ( 0 ) |
18e72167 | 1957 | { |
d1bc3a75 | 1958 | //fprintf(stderr,"lock cs_wallet\n"); |
18e72167 PW |
1959 | LOCK(wallet.cs_wallet); |
1960 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 | 1961 | } |
8e8b6d70 | 1962 | #endif |
d1bc3a75 | 1963 | //fprintf(stderr,"process new block\n"); |
194ad5b8 | 1964 | |
18e72167 PW |
1965 | // Process this block the same as if we had received it from another node |
1966 | CValidationState state; | |
4b729ec5 | 1967 | if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL)) |
ffde1589 | 1968 | return error("VerusMiner: ProcessNewBlock, block not accepted"); |
e9e70b95 | 1969 | |
d793f94b | 1970 | TrackMinedBlock(pblock->GetHash()); |
395f10cf | 1971 | komodo_broadcast(pblock,16); |
d247a5d1 JG |
1972 | return true; |
1973 | } | |
1974 | ||
078f6af1 | 1975 | int32_t komodo_baseid(char *origbase); |
a30dd993 | 1976 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); |
13691369 | 1977 | arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); |
8ee93080 | 1978 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
99ba67a0 | 1979 | extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC; |
8b51b9e4 | 1980 | int32_t roundrobin_delay; |
18443f69 | 1981 | arith_uint256 HASHTarget,HASHTarget_POW; |
3363d1c0 | 1982 | int32_t komodo_longestchain(); |
078f6af1 | 1983 | |
5642c96c | 1984 | // wait for peers to connect |
12217420 | 1985 | void waitForPeers(const CChainParams &chainparams) |
5642c96c | 1986 | { |
1987 | if (chainparams.MiningRequiresPeers()) | |
1988 | { | |
3da69a31 MT |
1989 | bool fvNodesEmpty; |
1990 | { | |
00a7120e | 1991 | boost::this_thread::interruption_point(); |
3da69a31 MT |
1992 | LOCK(cs_vNodes); |
1993 | fvNodesEmpty = vNodes.empty(); | |
1994 | } | |
3363d1c0 | 1995 | int longestchain = komodo_longestchain(); |
1996 | int lastlongest = 0; | |
1997 | if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight())) | |
3da69a31 | 1998 | { |
af2e212d | 1999 | int loops = 0, blockDiff = 0, newDiff = 0; |
2000 | ||
3da69a31 | 2001 | do { |
64d6048f | 2002 | if (fvNodesEmpty) |
3da69a31 | 2003 | { |
69fa3d0e | 2004 | MilliSleep(1000 + rand() % 4000); |
00a7120e | 2005 | boost::this_thread::interruption_point(); |
3da69a31 MT |
2006 | LOCK(cs_vNodes); |
2007 | fvNodesEmpty = vNodes.empty(); | |
af2e212d | 2008 | loops = 0; |
2009 | blockDiff = 0; | |
3363d1c0 | 2010 | lastlongest = 0; |
af2e212d | 2011 | } |
3363d1c0 | 2012 | else if ((newDiff = IsNotInSync()) > 0) |
af2e212d | 2013 | { |
2014 | if (blockDiff != newDiff) | |
2015 | { | |
2016 | blockDiff = newDiff; | |
2017 | } | |
2018 | else | |
2019 | { | |
3363d1c0 | 2020 | if (++loops <= 5) |
af2e212d | 2021 | { |
2022 | MilliSleep(1000); | |
2023 | } | |
2024 | else break; | |
2025 | } | |
3363d1c0 | 2026 | lastlongest = 0; |
2027 | } | |
2028 | else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight()) | |
2029 | { | |
2030 | // the only thing may be that we are seeing a long chain that we'll never get | |
2031 | // don't wait forever | |
2032 | if (lastlongest == 0) | |
2033 | { | |
2034 | MilliSleep(3000); | |
2035 | lastlongest = longestchain; | |
2036 | } | |
3da69a31 | 2037 | } |
af2e212d | 2038 | } while (fvNodesEmpty || IsNotInSync()); |
0ba20651 | 2039 | MilliSleep(100 + rand() % 400); |
3da69a31 | 2040 | } |
5642c96c | 2041 | } |
2042 | } | |
2043 | ||
42181656 | 2044 | #ifdef ENABLE_WALLET |
d7e6718d MT |
2045 | CBlockIndex *get_chainactive(int32_t height) |
2046 | { | |
3c40a9a6 | 2047 | if ( chainActive.LastTip() != 0 ) |
d7e6718d | 2048 | { |
4b729ec5 | 2049 | if ( height <= chainActive.LastTip()->GetHeight() ) |
3c40a9a6 MT |
2050 | { |
2051 | LOCK(cs_main); | |
d7e6718d | 2052 | return(chainActive[height]); |
3c40a9a6 | 2053 | } |
4b729ec5 | 2054 | // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight()); |
d7e6718d MT |
2055 | } |
2056 | //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); | |
2057 | return(0); | |
2058 | } | |
2059 | ||
135fa24e | 2060 | /* |
2061 | * A separate thread to stake, while the miner threads mine. | |
2062 | */ | |
2063 | void static VerusStaker(CWallet *pwallet) | |
2064 | { | |
2065 | LogPrintf("Verus staker thread started\n"); | |
2066 | RenameThread("verus-staker"); | |
2067 | ||
2068 | const CChainParams& chainparams = Params(); | |
2d02c19e | 2069 | auto consensusParams = chainparams.GetConsensus(); |
135fa24e | 2070 | |
2071 | // Each thread has its own key | |
2072 | CReserveKey reservekey(pwallet); | |
2073 | ||
2074 | // Each thread has its own counter | |
2075 | unsigned int nExtraNonce = 0; | |
12217420 | 2076 | |
135fa24e | 2077 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2078 | ||
4b729ec5 | 2079 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
135fa24e | 2080 | { |
2081 | sleep(1); | |
2082 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2083 | break; | |
2084 | } | |
2085 | ||
2086 | // try a nice clean peer connection to start | |
bf9c36f4 MT |
2087 | CBlockIndex *pindexPrev, *pindexCur; |
2088 | do { | |
2089 | pindexPrev = chainActive.LastTip(); | |
2090 | MilliSleep(5000 + rand() % 5000); | |
2091 | waitForPeers(chainparams); | |
2092 | pindexCur = chainActive.LastTip(); | |
2093 | } while (pindexPrev != pindexCur); | |
c132b91a | 2094 | |
135fa24e | 2095 | try { |
0fc0dc56 | 2096 | static int32_t lastStakingHeight = 0; |
2097 | ||
135fa24e | 2098 | while (true) |
2099 | { | |
135fa24e | 2100 | waitForPeers(chainparams); |
4ca6678c | 2101 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
135fa24e | 2102 | |
2103 | // Create new block | |
2104 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
0fc0dc56 | 2105 | |
4b729ec5 | 2106 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
135fa24e | 2107 | { |
4b729ec5 | 2108 | Mining_height = pindexPrev->GetHeight()+1; |
135fa24e | 2109 | Mining_start = (uint32_t)time(NULL); |
2110 | } | |
2111 | ||
0fc0dc56 | 2112 | if ( Mining_height != lastStakingHeight ) |
2113 | { | |
2114 | printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL); | |
2115 | lastStakingHeight = Mining_height; | |
2116 | } | |
2117 | ||
1fae37f6 MT |
2118 | // Check for stop or if block needs to be rebuilt |
2119 | boost::this_thread::interruption_point(); | |
2120 | ||
135fa24e | 2121 | // try to stake a block |
1fae37f6 MT |
2122 | CBlockTemplate *ptr = NULL; |
2123 | if (Mining_height > VERUS_MIN_STAKEAGE) | |
5034d1c1 | 2124 | ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true); |
135fa24e | 2125 | |
2126 | if ( ptr == 0 ) | |
2127 | { | |
1fae37f6 | 2128 | // wait to try another staking block until after the tip moves again |
37ad6886 | 2129 | while ( chainActive.LastTip() == pindexPrev ) |
bab13dd2 | 2130 | MilliSleep(250); |
135fa24e | 2131 | continue; |
2132 | } | |
2133 | ||
2134 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
2135 | if (!pblocktemplate.get()) | |
2136 | { | |
2137 | if (GetArg("-mineraddress", "").empty()) { | |
1fae37f6 | 2138 | LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
135fa24e | 2139 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2140 | } else { | |
2141 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
1fae37f6 | 2142 | LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
135fa24e | 2143 | } |
2144 | return; | |
2145 | } | |
2146 | ||
2147 | CBlock *pblock = &pblocktemplate->block; | |
1fae37f6 | 2148 | LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
135fa24e | 2149 | // |
2150 | // Search | |
2151 | // | |
1fae37f6 MT |
2152 | int64_t nStart = GetTime(); |
2153 | ||
1fae37f6 MT |
2154 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
2155 | { | |
2156 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2157 | { | |
2158 | fprintf(stderr,"no nodes, attempting reconnect\n"); | |
2159 | continue; | |
2160 | } | |
2161 | } | |
2162 | ||
2163 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
2164 | { | |
2165 | fprintf(stderr,"timeout, retrying\n"); | |
2166 | continue; | |
2167 | } | |
135fa24e | 2168 | |
37ad6886 | 2169 | if ( pindexPrev != chainActive.LastTip() ) |
135fa24e | 2170 | { |
4b729ec5 | 2171 | printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight()); |
135fa24e | 2172 | MilliSleep(250); |
2173 | continue; | |
2174 | } | |
2175 | ||
1fae37f6 MT |
2176 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
2177 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
135fa24e | 2178 | |
1fae37f6 | 2179 | uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits)); |
135fa24e | 2180 | |
df756d24 | 2181 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b9956efc | 2182 | |
df756d24 | 2183 | UpdateTime(pblock, consensusParams, pindexPrev); |
b9956efc | 2184 | |
ed47e5ec MT |
2185 | if (ProcessBlockFound(pblock, *pwallet, reservekey)) |
2186 | { | |
2187 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
2188 | LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
2189 | printf("Found block %d \n", Mining_height ); | |
2190 | printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
2191 | arith_uint256 post; | |
2192 | post.SetCompact(pblock->GetVerusPOSTarget()); | |
2193 | pindexPrev = get_chainactive(Mining_height - 100); | |
2194 | CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1]; | |
2195 | printf("POS hash: %s \ntarget: %s\n", | |
2196 | 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()); | |
2197 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) | |
2198 | printf("- timelocked until block %i\n", unlockTime); | |
2199 | else | |
2200 | printf("\n"); | |
2201 | } | |
1fae37f6 | 2202 | else |
ed47e5ec MT |
2203 | { |
2204 | LogPrintf("Found block rejected at staking height: %d\n", Mining_height); | |
2205 | printf("Found block rejected at staking height: %d\n", Mining_height); | |
2206 | } | |
135fa24e | 2207 | |
1fae37f6 MT |
2208 | // Check for stop or if block needs to be rebuilt |
2209 | boost::this_thread::interruption_point(); | |
135fa24e | 2210 | |
bf9c36f4 | 2211 | sleep(3); |
3da69a31 | 2212 | |
1fae37f6 MT |
2213 | // In regression test mode, stop mining after a block is found. |
2214 | if (chainparams.MineBlocksOnDemand()) { | |
2215 | throw boost::thread_interrupted(); | |
135fa24e | 2216 | } |
2217 | } | |
2218 | } | |
2219 | catch (const boost::thread_interrupted&) | |
2220 | { | |
135fa24e | 2221 | LogPrintf("VerusStaker terminated\n"); |
2222 | throw; | |
2223 | } | |
2224 | catch (const std::runtime_error &e) | |
2225 | { | |
135fa24e | 2226 | LogPrintf("VerusStaker runtime error: %s\n", e.what()); |
2227 | return; | |
2228 | } | |
135fa24e | 2229 | } |
2230 | ||
fa7fdbc6 | 2231 | typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); |
2232 | bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
2233 | bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
2234 | ||
42181656 | 2235 | void static BitcoinMiner_noeq(CWallet *pwallet) |
2236 | #else | |
2237 | void static BitcoinMiner_noeq() | |
2238 | #endif | |
2239 | { | |
05f6e633 | 2240 | LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
05f6e633 | 2241 | RenameThread("verushash-miner"); |
42181656 | 2242 | |
2243 | #ifdef ENABLE_WALLET | |
2244 | // Each thread has its own key | |
2245 | CReserveKey reservekey(pwallet); | |
2246 | #endif | |
2247 | ||
2910478b | 2248 | const CChainParams& chainparams = Params(); |
42181656 | 2249 | // Each thread has its own counter |
2250 | unsigned int nExtraNonce = 0; | |
12217420 | 2251 | |
42181656 | 2252 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2253 | ||
4b729ec5 | 2254 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
42181656 | 2255 | { |
2256 | sleep(1); | |
2257 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2258 | break; | |
2259 | } | |
9f3e2213 | 2260 | |
3da69a31 MT |
2261 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2262 | ||
5642c96c | 2263 | // try a nice clean peer connection to start |
c132b91a | 2264 | CBlockIndex *pindexPrev, *pindexCur; |
9f3e2213 | 2265 | do { |
37ad6886 | 2266 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 2267 | MilliSleep(5000 + rand() % 5000); |
bf9c36f4 | 2268 | waitForPeers(chainparams); |
37ad6886 | 2269 | pindexCur = chainActive.LastTip(); |
c132b91a | 2270 | } while (pindexPrev != pindexCur); |
6176a421 | 2271 | |
a9f18272 | 2272 | // make sure that we have checked for PBaaS availability |
2273 | ConnectedChains.CheckVerusPBaaSAvailable(); | |
2274 | ||
dbe656fe MT |
2275 | // this will not stop printing more than once in all cases, but it will allow us to print in all cases |
2276 | // and print duplicates rarely without having to synchronize | |
2277 | static CBlockIndex *lastChainTipPrinted; | |
90198f71 | 2278 | static int32_t lastMiningHeight = 0; |
9f3e2213 | 2279 | |
42181656 | 2280 | miningTimer.start(); |
2281 | ||
2282 | try { | |
dbe656fe | 2283 | printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
08d46b7f | 2284 | |
08d46b7f | 2285 | // v2 hash writer |
2286 | CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION); | |
2287 | ||
42181656 | 2288 | while (true) |
2289 | { | |
68334c8d | 2290 | miningTimer.stop(); |
2291 | waitForPeers(chainparams); | |
dfcf8255 | 2292 | |
37ad6886 | 2293 | pindexPrev = chainActive.LastTip(); |
dfcf8255 | 2294 | |
f8f61a6d | 2295 | // prevent forking on startup before the diff algorithm kicks in, |
2296 | // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from | |
2297 | // their parent | |
57055854 | 2298 | if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip())) |
dfcf8255 MT |
2299 | { |
2300 | do { | |
37ad6886 | 2301 | pindexPrev = chainActive.LastTip(); |
2830db29 | 2302 | MilliSleep(2000 + rand() % 2000); |
37ad6886 | 2303 | } while (pindexPrev != chainActive.LastTip()); |
dfcf8255 | 2304 | } |
42181656 | 2305 | |
2306 | // Create new block | |
2307 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
4b729ec5 | 2308 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
42181656 | 2309 | { |
4b729ec5 | 2310 | Mining_height = pindexPrev->GetHeight()+1; |
90198f71 | 2311 | if (lastMiningHeight != Mining_height) |
2312 | { | |
2313 | lastMiningHeight = Mining_height; | |
dc74c06d | 2314 | printf("Mining %s at height %d\n", ASSETCHAINS_SYMBOL, Mining_height); |
90198f71 | 2315 | } |
42181656 | 2316 | Mining_start = (uint32_t)time(NULL); |
2317 | } | |
2318 | ||
dbe656fe | 2319 | miningTimer.start(); |
42181656 | 2320 | |
2321 | #ifdef ENABLE_WALLET | |
5034d1c1 | 2322 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0); |
42181656 | 2323 | #else |
2324 | CBlockTemplate *ptr = CreateNewBlockWithKey(); | |
2325 | #endif | |
2326 | if ( ptr == 0 ) | |
2327 | { | |
2328 | static uint32_t counter; | |
f6084562 MT |
2329 | if ( counter++ % 40 == 0 ) |
2330 | { | |
2331 | if (!IsVerusActive() && | |
2332 | ConnectedChains.IsVerusPBaaSAvailable() && | |
2333 | ConnectedChains.notaryChainHeight < ConnectedChains.ThisChain().startBlock) | |
2334 | { | |
2335 | fprintf(stderr,"Waiting for block %d on %s chain to start. Current block is %d\n", ConnectedChains.ThisChain().startBlock, | |
2336 | ConnectedChains.notaryChain.chainDefinition.name.c_str(), | |
2337 | ConnectedChains.notaryChainHeight); | |
2338 | } | |
2339 | else | |
2340 | { | |
2341 | fprintf(stderr,"Unable to create valid block... will continue to try\n"); | |
2342 | } | |
2343 | } | |
2830db29 | 2344 | MilliSleep(2000); |
42181656 | 2345 | continue; |
2346 | } | |
dbe656fe | 2347 | |
42181656 | 2348 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
2349 | if (!pblocktemplate.get()) | |
2350 | { | |
2351 | if (GetArg("-mineraddress", "").empty()) { | |
05f6e633 | 2352 | LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
2353 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
42181656 | 2354 | } else { |
2355 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
05f6e633 | 2356 | LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
42181656 | 2357 | } |
2358 | return; | |
2359 | } | |
2360 | CBlock *pblock = &pblocktemplate->block; | |
f8f61a6d | 2361 | |
2362 | uint32_t savebits; | |
2363 | bool mergeMining = false; | |
2364 | savebits = pblock->nBits; | |
2365 | ||
2366 | bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2; | |
2367 | bool verusSolutionV3 = CConstVerusSolutionVector::Version(pblock->nSolution) == CActivationHeight::SOLUTION_VERUSV3; | |
2368 | ||
42181656 | 2369 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2370 | { | |
2371 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) | |
2372 | { | |
2373 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2374 | { | |
2375 | static uint32_t counter; | |
2376 | if ( counter++ < 10 ) | |
2377 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2378 | sleep(10); | |
2379 | continue; | |
2380 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2381 | } | |
2382 | } | |
b2a98c42 | 2383 | |
1685bba0 MT |
2384 | // this builds the Merkle tree and sets our easiest target |
2385 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, false, &savebits); | |
b2a98c42 MT |
2386 | |
2387 | // update PBaaS header | |
f8f61a6d | 2388 | if (verusSolutionV3) |
b2a98c42 | 2389 | { |
2fd1f0fb | 2390 | if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable()) |
f8f61a6d | 2391 | { |
b2a98c42 | 2392 | |
2fd1f0fb | 2393 | UniValue params(UniValue::VARR); |
2394 | UniValue error(UniValue::VARR); | |
2395 | params.push_back(EncodeHexBlk(*pblock)); | |
2396 | params.push_back(ASSETCHAINS_SYMBOL); | |
2397 | params.push_back(ASSETCHAINS_RPCHOST); | |
2398 | params.push_back(ASSETCHAINS_RPCPORT); | |
2399 | params.push_back(ASSETCHAINS_RPCCREDENTIALS); | |
2400 | try | |
b2a98c42 | 2401 | { |
be17c611 | 2402 | ConnectedChains.lastSubmissionFailed = false; |
2fd1f0fb | 2403 | params = RPCCallRoot("addmergedblock", params); |
2404 | params = find_value(params, "result"); | |
2405 | error = find_value(params, "error"); | |
2406 | } catch (std::exception e) | |
2407 | { | |
2408 | printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
2409 | params = UniValue(e.what()); | |
b2a98c42 | 2410 | } |
2fd1f0fb | 2411 | if (mergeMining = (params.isNull() && error.isNull())) |
f8f61a6d | 2412 | { |
a1d91f89 | 2413 | printf("Merge mining %s with %s as the hashing chain\n", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str()); |
2414 | LogPrintf("Merge mining with %s as the hashing chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
f8f61a6d | 2415 | } |
b2a98c42 MT |
2416 | } |
2417 | } | |
2418 | ||
42181656 | 2419 | LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], |
2420 | pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); | |
2421 | // | |
2422 | // Search | |
2423 | // | |
f8f61a6d | 2424 | int64_t nStart = GetTime(); |
42181656 | 2425 | |
f8f61a6d | 2426 | arith_uint256 hashTarget = arith_uint256().SetCompact(savebits); |
fa7fdbc6 | 2427 | uint256 uintTarget = ArithToUint256(hashTarget); |
f8f61a6d | 2428 | arith_uint256 ourTarget; |
2429 | ourTarget.SetCompact(pblock->nBits); | |
2430 | ||
42181656 | 2431 | Mining_start = 0; |
ef70c5b2 | 2432 | |
37ad6886 | 2433 | if ( pindexPrev != chainActive.LastTip() ) |
05f6e633 | 2434 | { |
37ad6886 | 2435 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2436 | { |
37ad6886 | 2437 | lastChainTipPrinted = chainActive.LastTip(); |
4b729ec5 | 2438 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2439 | } |
f8f61a6d | 2440 | MilliSleep(100); |
05f6e633 | 2441 | continue; |
2442 | } | |
ef70c5b2 | 2443 | |
135fa24e | 2444 | if ( ASSETCHAINS_STAKED != 0 ) |
2445 | { | |
2446 | int32_t percPoS,z; | |
2447 | hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED); | |
2448 | for (z=31; z>=0; z--) | |
2449 | fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); | |
2450 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2451 | } | |
2452 | ||
2830db29 | 2453 | uint64_t count; |
2454 | uint64_t hashesToGo = 0; | |
2455 | uint64_t totalDone = 0; | |
2456 | ||
fa7fdbc6 | 2457 | if (!verusHashV2) |
458bfcab | 2458 | { |
fa7fdbc6 | 2459 | // must not be in sync |
2460 | printf("Mining on incorrect block version.\n"); | |
2461 | sleep(2); | |
2462 | continue; | |
458bfcab | 2463 | } |
2464 | ||
e29b5dd5 | 2465 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); |
fa7fdbc6 | 2466 | count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
db027133 | 2467 | CVerusHashV2 *vh2 = &ss2.GetState(); |
3b500530 | 2468 | u128 *hashKey; |
2469 | verusclhasher &vclh = vh2->vclh; | |
fa7fdbc6 | 2470 | minefunction mine_verus; |
2471 | mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port; | |
f21fad6a | 2472 | |
42181656 | 2473 | while (true) |
2474 | { | |
4dcb64c0 | 2475 | uint256 hashResult = uint256(); |
458bfcab | 2476 | |
e5fb645e | 2477 | unsigned char *curBuf; |
2478 | ||
f8f61a6d | 2479 | if (mergeMining) |
42181656 | 2480 | { |
c89d86ee | 2481 | // loop for a few minutes before refreshing the block |
e771a884 | 2482 | while (true) |
12217420 | 2483 | { |
93ff475b | 2484 | uint256 ourMerkle = pblock->hashMerkleRoot; |
a1d91f89 | 2485 | if ( pindexPrev != chainActive.LastTip() ) |
2486 | { | |
2487 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2488 | { | |
2489 | lastChainTipPrinted = chainActive.LastTip(); | |
2490 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); | |
2491 | arith_uint256 target; | |
2492 | target.SetCompact(lastChainTipPrinted->nBits); | |
93ff475b MT |
2493 | if (ourMerkle == lastChainTipPrinted->hashMerkleRoot) |
2494 | { | |
2495 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
607402ba | 2496 | printf("Found block %d \n", lastChainTipPrinted->GetHeight()); |
93ff475b MT |
2497 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); |
2498 | printf(" hash: %s\ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
2499 | } | |
a1d91f89 | 2500 | } |
2501 | break; | |
2502 | } | |
2503 | ||
e771a884 | 2504 | // if PBaaS is no longer available, we can't count on merge mining |
2505 | if (!ConnectedChains.IsVerusPBaaSAvailable()) | |
2506 | { | |
2507 | break; | |
2508 | } | |
f8f61a6d | 2509 | |
2510 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
458bfcab | 2511 | { |
f8f61a6d | 2512 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) |
fa7fdbc6 | 2513 | { |
f8f61a6d | 2514 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
2515 | break; | |
fa7fdbc6 | 2516 | } |
f8f61a6d | 2517 | } |
2518 | ||
a82942e4 | 2519 | // update every few minutes, regardless |
2520 | int64_t elapsed = GetTime() - nStart; | |
f8f61a6d | 2521 | |
a9663647 | 2522 | if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed) |
458bfcab | 2523 | { |
f8f61a6d | 2524 | break; |
458bfcab | 2525 | } |
a1d91f89 | 2526 | |
dc74c06d | 2527 | boost::this_thread::interruption_point(); |
a1d91f89 | 2528 | MilliSleep(500); |
458bfcab | 2529 | } |
ffde1589 | 2530 | break; |
f8f61a6d | 2531 | } |
2532 | else | |
2533 | { | |
2534 | // check NONCEMASK at a time | |
2535 | for (uint64_t i = 0; i < count; i++) | |
42181656 | 2536 | { |
2fd1f0fb | 2537 | // 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 | 2538 | // merge mined block, but not our own |
f8f61a6d | 2539 | bool blockFound; |
2540 | arith_uint256 arithHash; | |
2830db29 | 2541 | totalDone = 0; |
f8f61a6d | 2542 | do |
2543 | { | |
2fd1f0fb | 2544 | // pickup/remove any new/deleted headers |
71f97948 | 2545 | if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1)) |
2fd1f0fb | 2546 | { |
71f97948 | 2547 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, false, &savebits); |
1fa4454d | 2548 | |
2fd1f0fb | 2549 | hashTarget.SetCompact(savebits); |
2550 | uintTarget = ArithToUint256(hashTarget); | |
2551 | } | |
2552 | ||
f8f61a6d | 2553 | // hashesToGo gets updated with actual number run for metrics |
2554 | hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; | |
2830db29 | 2555 | uint64_t start = i * hashesToGo + totalDone; |
f8f61a6d | 2556 | hashesToGo -= totalDone; |
2557 | ||
2558 | if (verusSolutionV3) | |
2559 | { | |
2560 | // mine on canonical header for merge mining | |
2561 | CPBaaSPreHeader savedHeader(*pblock); | |
da97aa5c | 2562 | |
f8f61a6d | 2563 | pblock->ClearNonCanonicalData(); |
2564 | blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo); | |
2565 | savedHeader.SetBlockData(*pblock); | |
2566 | } | |
2567 | else | |
2568 | { | |
2569 | blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo); | |
2570 | } | |
2571 | ||
2572 | arithHash = UintToArith256(hashResult); | |
249e20e4 | 2573 | totalDone += hashesToGo + 1; |
f8f61a6d | 2574 | if (blockFound && IsVerusActive()) |
2575 | { | |
2576 | ConnectedChains.QueueNewBlockHeader(*pblock); | |
2577 | if (arithHash > ourTarget) | |
2578 | { | |
2579 | // all blocks qualified with this hash will be submitted | |
2580 | // until we redo the block, we might as well not try again with anything over this hash | |
2581 | hashTarget = arithHash; | |
2582 | uintTarget = ArithToUint256(hashTarget); | |
2583 | } | |
2584 | } | |
2fd1f0fb | 2585 | } while (blockFound && arithHash > ourTarget); |
c98efb5a | 2586 | |
f8f61a6d | 2587 | if (!blockFound || arithHash > ourTarget) |
4dcb64c0 | 2588 | { |
f8f61a6d | 2589 | // Check for stop or if block needs to be rebuilt |
2590 | boost::this_thread::interruption_point(); | |
ce40cf2e | 2591 | if ( pindexPrev != chainActive.LastTip() ) |
f8f61a6d | 2592 | { |
2593 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2594 | { | |
2595 | lastChainTipPrinted = chainActive.LastTip(); | |
2596 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); | |
2597 | } | |
2598 | break; | |
2599 | } | |
a1d91f89 | 2600 | else if ((i + 1) < count) |
f8f61a6d | 2601 | { |
a1d91f89 | 2602 | // if we'll not drop through, update hashcount |
f8f61a6d | 2603 | { |
2604 | LOCK(cs_metrics); | |
2830db29 | 2605 | nHashCount += totalDone; |
2606 | totalDone = 0; | |
f8f61a6d | 2607 | } |
f8f61a6d | 2608 | } |
4dcb64c0 | 2609 | } |
f8f61a6d | 2610 | else |
2611 | { | |
2612 | // Check for stop or if block needs to be rebuilt | |
2613 | boost::this_thread::interruption_point(); | |
4dcb64c0 | 2614 | |
f8f61a6d | 2615 | if (pblock->nSolution.size() != 1344) |
2616 | { | |
2617 | LogPrintf("ERROR: Block solution is not 1344 bytes as it should be"); | |
2618 | break; | |
2619 | } | |
42181656 | 2620 | |
f8f61a6d | 2621 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
2622 | ||
2623 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); | |
ef70c5b2 | 2624 | |
3363d1c0 | 2625 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2626 | std::string validateStr = hashResult.GetHex(); |
2627 | std::string hashStr = pblock->GetHash().GetHex(); | |
2628 | uint256 *bhalf1 = (uint256 *)vh2->CurBuffer(); | |
2629 | uint256 *bhalf2 = bhalf1 + 1; | |
3363d1c0 | 2630 | #else |
f8f61a6d | 2631 | std::string hashStr = hashResult.GetHex(); |
3363d1c0 | 2632 | #endif |
3af22e67 | 2633 | |
f8f61a6d | 2634 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2635 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex()); | |
2636 | printf("Found block %d \n", Mining_height ); | |
2637 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
3363d1c0 | 2638 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2639 | printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
2640 | printf("intermediate %lx\n", intermediate); | |
2641 | printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
2642 | bhalf1 = (uint256 *)verusclhasher_key.get(); | |
2643 | bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5); | |
2644 | printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
3363d1c0 | 2645 | #else |
f8f61a6d | 2646 | printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
3363d1c0 | 2647 | #endif |
f8f61a6d | 2648 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
2649 | printf(" - timelocked until block %i\n", unlockTime); | |
2650 | else | |
2651 | printf("\n"); | |
42181656 | 2652 | #ifdef ENABLE_WALLET |
f8f61a6d | 2653 | ProcessBlockFound(pblock, *pwallet, reservekey); |
42181656 | 2654 | #else |
f8f61a6d | 2655 | ProcessBlockFound(pblock); |
42181656 | 2656 | #endif |
f8f61a6d | 2657 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2658 | break; | |
2659 | } | |
42181656 | 2660 | } |
42181656 | 2661 | |
f8f61a6d | 2662 | { |
2663 | LOCK(cs_metrics); | |
2830db29 | 2664 | nHashCount += totalDone; |
f8f61a6d | 2665 | } |
69767347 | 2666 | } |
f8f61a6d | 2667 | |
69767347 | 2668 | |
42181656 | 2669 | // Check for stop or if block needs to be rebuilt |
2670 | boost::this_thread::interruption_point(); | |
2671 | ||
2672 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
2673 | { | |
2674 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2675 | { | |
ef70c5b2 | 2676 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
42181656 | 2677 | break; |
2678 | } | |
2679 | } | |
2680 | ||
dbe656fe | 2681 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
42181656 | 2682 | { |
dbe656fe | 2683 | fprintf(stderr,"timeout, retrying\n"); |
42181656 | 2684 | break; |
2685 | } | |
2686 | ||
37ad6886 | 2687 | if ( pindexPrev != chainActive.LastTip() ) |
42181656 | 2688 | { |
37ad6886 | 2689 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2690 | { |
37ad6886 | 2691 | lastChainTipPrinted = chainActive.LastTip(); |
90198f71 | 2692 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2693 | } |
42181656 | 2694 | break; |
2695 | } | |
2696 | ||
2830db29 | 2697 | // totalDone now has the number of hashes actually done since starting on one nonce mask worth |
ce40cf2e | 2698 | uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3; |
2830db29 | 2699 | if (!(totalDone < hashesPerNonceMask)) |
ce40cf2e | 2700 | { |
52cf66e1 | 2701 | #ifdef _WIN32 |
ce40cf2e | 2702 | printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2703 | #else |
ce40cf2e | 2704 | printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2705 | #endif |
ce40cf2e | 2706 | } |
4dcb64c0 | 2707 | break; |
8682e17a | 2708 | |
42181656 | 2709 | } |
2710 | } | |
2711 | } | |
2712 | catch (const boost::thread_interrupted&) | |
2713 | { | |
2714 | miningTimer.stop(); | |
5034d1c1 | 2715 | LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 2716 | throw; |
2717 | } | |
2718 | catch (const std::runtime_error &e) | |
2719 | { | |
2720 | miningTimer.stop(); | |
5034d1c1 | 2721 | LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what()); |
42181656 | 2722 | return; |
2723 | } | |
2724 | miningTimer.stop(); | |
2725 | } | |
2726 | ||
8e8b6d70 | 2727 | #ifdef ENABLE_WALLET |
d247a5d1 | 2728 | void static BitcoinMiner(CWallet *pwallet) |
8e8b6d70 JG |
2729 | #else |
2730 | void static BitcoinMiner() | |
2731 | #endif | |
d247a5d1 | 2732 | { |
2e500f50 | 2733 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 2734 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 2735 | RenameThread("komodo-miner"); |
bebe7282 | 2736 | const CChainParams& chainparams = Params(); |
e9e70b95 | 2737 | |
8e8b6d70 JG |
2738 | #ifdef ENABLE_WALLET |
2739 | // Each thread has its own key | |
d247a5d1 | 2740 | CReserveKey reservekey(pwallet); |
8e8b6d70 | 2741 | #endif |
e9e70b95 | 2742 | |
8e8b6d70 | 2743 | // Each thread has its own counter |
d247a5d1 | 2744 | unsigned int nExtraNonce = 0; |
e9e70b95 | 2745 | |
e9574728 JG |
2746 | unsigned int n = chainparams.EquihashN(); |
2747 | unsigned int k = chainparams.EquihashK(); | |
16593898 | 2748 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1; |
99ba67a0 | 2749 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) |
755ead98 | 2750 | { |
2751 | sleep(1); | |
4e624c04 | 2752 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
2753 | break; | |
755ead98 | 2754 | } |
32b0978b | 2755 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
4b729ec5 | 2756 | komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); |
28a62b60 | 2757 | if ( notaryid != My_notaryid ) |
2758 | My_notaryid = notaryid; | |
755ead98 | 2759 | std::string solver; |
e1e65cef | 2760 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
e9e70b95 | 2761 | solver = "tromp"; |
e1e65cef | 2762 | //else solver = "default"; |
5f0009b2 | 2763 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 2764 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 2765 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 2766 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
2767 | std::mutex m_cs; |
2768 | bool cancelSolver = false; | |
2769 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
e9e70b95 | 2770 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { |
2771 | std::lock_guard<std::mutex> lock{m_cs}; | |
2772 | cancelSolver = true; | |
2773 | } | |
2774 | ); | |
07be8f7e | 2775 | miningTimer.start(); |
e9e70b95 | 2776 | |
0655fac0 | 2777 | try { |
ad84148d | 2778 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 2779 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 2780 | while (true) |
2781 | { | |
4b729ec5 | 2782 | if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 && |
e725f1cb | 2783 | { |
4b729ec5 | 2784 | //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 ) |
a96fd7b5 | 2785 | // break; |
0655fac0 PK |
2786 | // Busy-wait for the network to come online so we don't waste time mining |
2787 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
07be8f7e | 2788 | miningTimer.stop(); |
bba7c249 GM |
2789 | do { |
2790 | bool fvNodesEmpty; | |
2791 | { | |
373668be | 2792 | //LOCK(cs_vNodes); |
bba7c249 GM |
2793 | fvNodesEmpty = vNodes.empty(); |
2794 | } | |
269fe243 | 2795 | if (!fvNodesEmpty )//&& !IsInitialBlockDownload()) |
bba7c249 | 2796 | break; |
6e78d3df | 2797 | MilliSleep(15000); |
ad84148d | 2798 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
e9e70b95 | 2799 | |
bba7c249 | 2800 | } while (true); |
ad84148d | 2801 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
07be8f7e | 2802 | miningTimer.start(); |
0655fac0 | 2803 | } |
0655fac0 PK |
2804 | // |
2805 | // Create new block | |
2806 | // | |
2807 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
86131275 | 2808 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
4b729ec5 | 2809 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
4940066c | 2810 | { |
4b729ec5 | 2811 | Mining_height = pindexPrev->GetHeight()+1; |
4940066c | 2812 | Mining_start = (uint32_t)time(NULL); |
2813 | } | |
8e9ef91c | 2814 | if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) |
2825c0b5 | 2815 | { |
40304479 | 2816 | //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
5a7fd132 | 2817 | //sleep(3); |
2825c0b5 | 2818 | } |
135fa24e | 2819 | |
8e8b6d70 | 2820 | #ifdef ENABLE_WALLET |
135fa24e | 2821 | // notaries always default to staking |
4b729ec5 | 2822 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); |
8e8b6d70 | 2823 | #else |
945f015d | 2824 | CBlockTemplate *ptr = CreateNewBlockWithKey(); |
8e8b6d70 | 2825 | #endif |
08d0b73c | 2826 | if ( ptr == 0 ) |
2827 | { | |
d0f7ead0 | 2828 | static uint32_t counter; |
5bb3d0fe | 2829 | if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) |
1b5b89ba | 2830 | fprintf(stderr,"created illegal block, retry\n"); |
8fc79ac9 | 2831 | sleep(1); |
d0f7ead0 | 2832 | continue; |
08d0b73c | 2833 | } |
2a6a442a | 2834 | //fprintf(stderr,"get template\n"); |
08d0b73c | 2835 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
0655fac0 | 2836 | if (!pblocktemplate.get()) |
6c37f7fd | 2837 | { |
8e8b6d70 | 2838 | if (GetArg("-mineraddress", "").empty()) { |
945f015d | 2839 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
8e8b6d70 JG |
2840 | } else { |
2841 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
945f015d | 2842 | LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n"); |
8e8b6d70 | 2843 | } |
0655fac0 | 2844 | return; |
6c37f7fd | 2845 | } |
0655fac0 | 2846 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 2847 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2848 | { | |
42181656 | 2849 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) |
16c7bf6b | 2850 | { |
8683bd8d | 2851 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
2852 | { | |
2853 | static uint32_t counter; | |
2854 | if ( counter++ < 10 ) | |
2855 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2856 | sleep(10); | |
2857 | continue; | |
2858 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2859 | } | |
16c7bf6b | 2860 | } |
0655fac0 | 2861 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2a6a442a | 2862 | //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size()); |
2e500f50 | 2863 | 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 |
2864 | // |
2865 | // Search | |
2866 | // | |
2ba9de01 | 2867 | 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 | 2868 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
404391b5 | 2869 | savebits = pblock->nBits; |
d5614a76 | 2870 | HASHTarget = arith_uint256().SetCompact(savebits); |
f0100e72 | 2871 | roundrobin_delay = ROUNDROBIN_DELAY; |
3e7e3109 | 2872 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 ) |
5203fc4b | 2873 | { |
fda5f849 | 2874 | j = 65; |
67df454d | 2875 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) |
fb6c7505 | 2876 | { |
4fff8a63 | 2877 | int32_t dispflag = 0; |
ef70c5b2 | 2878 | if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) |
4fff8a63 | 2879 | dispflag = 1; |
4b729ec5 | 2880 | komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); |
29e60e48 | 2881 | if ( nonzpkeys > 0 ) |
2882 | { | |
ccb71a6e | 2883 | for (i=0; i<33; i++) |
2884 | if( pubkeys[0][i] != 0 ) | |
2885 | break; | |
2886 | if ( i == 33 ) | |
2887 | externalflag = 1; | |
2888 | else externalflag = 0; | |
4d068367 | 2889 | if ( IS_KOMODO_NOTARY != 0 ) |
b176c125 | 2890 | { |
345e545e | 2891 | for (i=1; i<66; i++) |
2892 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
2893 | break; | |
6494f040 | 2894 | if ( externalflag == 0 && i != 66 && mids[i] >= 0 ) |
2895 | printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]); | |
2c7ad758 | 2896 | for (j=gpucount=0; j<65; j++) |
2897 | { | |
4fff8a63 | 2898 | if ( dispflag != 0 ) |
e4a383e3 | 2899 | { |
2900 | if ( mids[j] >= 0 ) | |
2901 | fprintf(stderr,"%d ",mids[j]); | |
2902 | else fprintf(stderr,"GPU "); | |
2903 | } | |
2c7ad758 | 2904 | if ( mids[j] == -1 ) |
2905 | gpucount++; | |
2906 | } | |
4fff8a63 | 2907 | if ( dispflag != 0 ) |
4b729ec5 | 2908 | 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 | 2909 | } |
29e60e48 | 2910 | for (j=0; j<65; j++) |
2911 | if ( mids[j] == notaryid ) | |
2912 | break; | |
49b49585 | 2913 | if ( j == 65 ) |
2914 | KOMODO_LASTMINED = 0; | |
965f0f7e | 2915 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 2916 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 2917 | { |
88287857 | 2918 | HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); |
4b729ec5 | 2919 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1); |
fda5f849 | 2920 | } //else fprintf(stderr,"duplicate at j.%d\n",j); |
fb6c7505 | 2921 | } else Mining_start = 0; |
d7d27bb3 | 2922 | } else Mining_start = 0; |
2ba9de01 | 2923 | if ( ASSETCHAINS_STAKED != 0 ) |
e725f1cb | 2924 | { |
ed3d0a05 | 2925 | int32_t percPoS,z; bool fNegative,fOverflow; |
18443f69 | 2926 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
f108acf9 | 2927 | HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); |
f2c1ac06 | 2928 | if ( ASSETCHAINS_STAKED < 100 ) |
2929 | { | |
2930 | for (z=31; z>=0; z--) | |
2931 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); | |
2932 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2933 | } | |
deba7f20 | 2934 | } |
e725f1cb | 2935 | while (true) |
2936 | { | |
99ba67a0 | 2937 | if ( KOMODO_INSYNC == 0 ) |
2938 | { | |
e9d56b2c | 2939 | fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); |
2940 | if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) | |
a02c45db | 2941 | KOMODO_INSYNC = 1; |
99ba67a0 | 2942 | sleep(3); |
2943 | } | |
7213c0b1 | 2944 | // Hash state |
8c22eb46 | 2945 | KOMODO_CHOSEN_ONE = 0; |
42181656 | 2946 | |
7213c0b1 | 2947 | crypto_generichash_blake2b_state state; |
e9574728 | 2948 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
2949 | // I = the block header minus nonce and solution. |
2950 | CEquihashInput I{*pblock}; | |
2951 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
2952 | ss << I; | |
7213c0b1 JG |
2953 | // H(I||... |
2954 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
2955 | // H(I||V||... |
2956 | crypto_generichash_blake2b_state curr_state; | |
2957 | curr_state = state; | |
7a4c01c9 | 2958 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 2959 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 2960 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
18443f69 | 2961 | arith_uint256 hashTarget; |
6e78d3df | 2962 | if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 ) |
18443f69 | 2963 | hashTarget = HASHTarget_POW; |
2964 | else hashTarget = HASHTarget; | |
5be6abbf | 2965 | std::function<bool(std::vector<unsigned char>)> validBlock = |
8e8b6d70 | 2966 | #ifdef ENABLE_WALLET |
e9e70b95 | 2967 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 2968 | #else |
e9e70b95 | 2969 | [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 2970 | #endif |
e9e70b95 | 2971 | (std::vector<unsigned char> soln) { |
c21c6306 | 2972 | int32_t z; arith_uint256 h; CBlock B; |
51eb5273 JG |
2973 | // Write the solution to the hash and compute the result. |
2974 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 2975 | pblock->nSolution = soln; |
e7d59bbc | 2976 | solutionTargetChecks.increment(); |
eff2c3a3 | 2977 | B = *pblock; |
2978 | h = UintToArith256(B.GetHash()); | |
eff2c3a3 | 2979 | /*for (z=31; z>=16; z--) |
02c30aac | 2980 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); |
aea2d1aa | 2981 | fprintf(stderr," mined "); |
2982 | for (z=31; z>=16; z--) | |
18443f69 | 2983 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); |
aea2d1aa | 2984 | fprintf(stderr," hashTarget "); |
2985 | for (z=31; z>=16; z--) | |
18443f69 | 2986 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); |
eff2c3a3 | 2987 | fprintf(stderr," POW\n");*/ |
265f4e96 | 2988 | if ( h > hashTarget ) |
40df8d84 | 2989 | { |
6e78d3df | 2990 | //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 ) |
afa90f17 | 2991 | // sleep(1); |
265f4e96 | 2992 | return false; |
40df8d84 | 2993 | } |
41e9c815 | 2994 | if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() ) |
d7d27bb3 | 2995 | { |
45ee62cb | 2996 | //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime())); |
596b05ba | 2997 | while ( GetAdjustedTime() < B.nTime-2 ) |
8e9ef91c | 2998 | { |
eb1ba5a0 | 2999 | sleep(1); |
4b729ec5 | 3000 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
4cc387ec | 3001 | { |
3002 | fprintf(stderr,"new block arrived\n"); | |
3003 | return(false); | |
3004 | } | |
8e9ef91c | 3005 | } |
eb1ba5a0 | 3006 | } |
8e9ef91c | 3007 | if ( ASSETCHAINS_STAKED == 0 ) |
d7d27bb3 | 3008 | { |
4d068367 | 3009 | if ( IS_KOMODO_NOTARY != 0 ) |
8e9ef91c | 3010 | { |
26810a26 | 3011 | int32_t r; |
9703f8a0 | 3012 | if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 ) |
596b05ba | 3013 | MilliSleep((rand() % (r * 1000)) + 1000); |
ef70c5b2 | 3014 | } |
e5430f52 | 3015 | } |
8e9ef91c | 3016 | else |
d7d27bb3 | 3017 | { |
0c35569b | 3018 | while ( B.nTime-57 > GetAdjustedTime() ) |
deba7f20 | 3019 | { |
afa90f17 | 3020 | sleep(1); |
4b729ec5 | 3021 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
afa90f17 | 3022 | return(false); |
68d0354d | 3023 | } |
4d068367 | 3024 | uint256 tmp = B.GetHash(); |
3025 | int32_t z; for (z=31; z>=0; z--) | |
3026 | fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); | |
01e50e73 | 3027 | fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height); |
d7d27bb3 | 3028 | } |
8fc79ac9 | 3029 | CValidationState state; |
86131275 | 3030 | if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false)) |
d2d3c766 | 3031 | { |
8fc79ac9 | 3032 | h = UintToArith256(B.GetHash()); |
3033 | for (z=31; z>=0; z--) | |
3034 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); | |
3035 | fprintf(stderr," Invalid block mined, try again\n"); | |
3036 | return(false); | |
d2d3c766 | 3037 | } |
b3183e3e | 3038 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
3039 | // Found a solution |
3040 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 3041 | LogPrintf("KomodoMiner:\n"); |
eff2c3a3 | 3042 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); |
8e8b6d70 | 3043 | #ifdef ENABLE_WALLET |
eff2c3a3 | 3044 | if (ProcessBlockFound(&B, *pwallet, reservekey)) { |
8e8b6d70 | 3045 | #else |
eff2c3a3 | 3046 | if (ProcessBlockFound(&B)) { |
8e8b6d70 | 3047 | #endif |
e9e70b95 | 3048 | // Ignore chain updates caused by us |
3049 | std::lock_guard<std::mutex> lock{m_cs}; | |
3050 | cancelSolver = false; | |
3051 | } | |
3052 | KOMODO_CHOSEN_ONE = 0; | |
3053 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
3054 | // In regression test mode, stop mining after a block is found. | |
3055 | if (chainparams.MineBlocksOnDemand()) { | |
3056 | // Increment here because throwing skips the call below | |
3057 | ehSolverRuns.increment(); | |
3058 | throw boost::thread_interrupted(); | |
3059 | } | |
e9e70b95 | 3060 | return true; |
3061 | }; | |
3062 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
a6a0d913 | 3063 | std::lock_guard<std::mutex> lock{m_cs}; |
e9e70b95 | 3064 | return cancelSolver; |
3065 | }; | |
3066 | ||
3067 | // TODO: factor this out into a function with the same API for each solver. | |
3068 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { | |
3069 | // Create solver and initialize it. | |
3070 | equi eq(1); | |
3071 | eq.setstate(&curr_state); | |
3072 | ||
3073 | // Initialization done, start algo driver. | |
3074 | eq.digit0(0); | |
c7aaab7a | 3075 | eq.xfull = eq.bfull = eq.hfull = 0; |
e9e70b95 | 3076 | eq.showbsizes(0); |
3077 | for (u32 r = 1; r < WK; r++) { | |
3078 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
3079 | eq.xfull = eq.bfull = eq.hfull = 0; | |
3080 | eq.showbsizes(r); | |
c7aaab7a | 3081 | } |
e9e70b95 | 3082 | eq.digitK(0); |
3083 | ehSolverRuns.increment(); | |
3084 | ||
3085 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
3086 | for (size_t s = 0; s < eq.nsols; s++) { | |
3087 | LogPrint("pow", "Checking solution %d\n", s+1); | |
3088 | std::vector<eh_index> index_vector(PROOFSIZE); | |
3089 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
3090 | index_vector[i] = eq.sols[s][i]; | |
3091 | } | |
3092 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
3093 | ||
3094 | if (validBlock(sol_char)) { | |
3095 | // If we find a POW solution, do not try other solutions | |
3096 | // because they become invalid as we created a new block in blockchain. | |
3097 | break; | |
3098 | } | |
3099 | } | |
3100 | } else { | |
3101 | try { | |
3102 | // If we find a valid block, we rebuild | |
3103 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); | |
3104 | ehSolverRuns.increment(); | |
3105 | if (found) { | |
997ddd92 | 3106 | int32_t i; uint256 hash = pblock->GetHash(); |
e9e70b95 | 3107 | for (i=0; i<32; i++) |
3108 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
3109 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
3110 | FOUND_BLOCK = 1; | |
3111 | KOMODO_MAYBEMINED = Mining_height; | |
3112 | break; | |
3113 | } | |
3114 | } catch (EhSolverCancelledException&) { | |
3115 | LogPrint("pow", "Equihash solver cancelled\n"); | |
3116 | std::lock_guard<std::mutex> lock{m_cs}; | |
3117 | cancelSolver = false; | |
c7aaab7a DH |
3118 | } |
3119 | } | |
e9e70b95 | 3120 | |
3121 | // Check for stop or if block needs to be rebuilt | |
3122 | boost::this_thread::interruption_point(); | |
3123 | // Regtest mode doesn't require peers | |
3124 | if ( FOUND_BLOCK != 0 ) | |
3125 | { | |
3126 | FOUND_BLOCK = 0; | |
3127 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
3128 | //sleep(2000); | |
3129 | } | |
3130 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
3131 | { | |
3132 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) | |
3133 | { | |
3134 | fprintf(stderr,"no nodes, break\n"); | |
c7aaab7a | 3135 | break; |
a6df7ab5 | 3136 | } |
c7aaab7a | 3137 | } |
997ddd92 | 3138 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
10694486 | 3139 | { |
e9e70b95 | 3140 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
3141 | fprintf(stderr,"0xffff, break\n"); | |
d90cef0b | 3142 | break; |
10694486 | 3143 | } |
e9e70b95 | 3144 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
3145 | { | |
3146 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3147 | fprintf(stderr,"timeout, break\n"); | |
3148 | break; | |
3149 | } | |
86131275 | 3150 | if ( pindexPrev != chainActive.LastTip() ) |
e9e70b95 | 3151 | { |
3152 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3153 | fprintf(stderr,"Tip advanced, break\n"); | |
3154 | break; | |
3155 | } | |
3156 | // Update nNonce and nTime | |
3157 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
3158 | pblock->nBits = savebits; | |
18dd6a3b | 3159 | /*if ( NOTARY_PUBKEY33[0] == 0 ) |
e9e70b95 | 3160 | { |
f8f740a9 | 3161 | int32_t percPoS; |
df756d24 MT |
3162 | UpdateTime(pblock, consensusParams, pindexPrev); |
3163 | if (consensusParams.fPowAllowMinDifficultyBlocks) | |
23fc88bb | 3164 | { |
3165 | // Changing pblock->nTime can change work required on testnet: | |
3166 | HASHTarget.SetCompact(pblock->nBits); | |
18443f69 | 3167 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
23fc88bb | 3168 | } |
18dd6a3b | 3169 | }*/ |
48265f3c | 3170 | } |
d247a5d1 JG |
3171 | } |
3172 | } | |
e9e70b95 | 3173 | catch (const boost::thread_interrupted&) |
3174 | { | |
3175 | miningTimer.stop(); | |
3176 | c.disconnect(); | |
3177 | LogPrintf("KomodoMiner terminated\n"); | |
3178 | throw; | |
3179 | } | |
3180 | catch (const std::runtime_error &e) | |
3181 | { | |
3182 | miningTimer.stop(); | |
3183 | c.disconnect(); | |
3184 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); | |
3185 | return; | |
3186 | } | |
07be8f7e | 3187 | miningTimer.stop(); |
5e9b555f | 3188 | c.disconnect(); |
bba7c249 | 3189 | } |
e9e70b95 | 3190 | |
8e8b6d70 | 3191 | #ifdef ENABLE_WALLET |
e9e70b95 | 3192 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
8e8b6d70 | 3193 | #else |
e9e70b95 | 3194 | void GenerateBitcoins(bool fGenerate, int nThreads) |
8e8b6d70 | 3195 | #endif |
d247a5d1 | 3196 | { |
f8f61a6d | 3197 | if (!AreParamsInitialized()) |
3198 | { | |
3199 | return; | |
3200 | } | |
3201 | ||
10214558 | 3202 | // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at |
3203 | // initialization, and this is the first time we can get it. store the Sapling address here | |
3204 | extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher; | |
3205 | extern std::string VERUS_CHEATCATCHER; | |
3206 | libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER); | |
3207 | if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr)) | |
3208 | { | |
99c94fc3 | 3209 | try |
3210 | { | |
3211 | cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr); | |
3212 | } | |
3213 | catch (...) | |
3214 | { | |
3215 | } | |
10214558 | 3216 | } |
bd6639fd | 3217 | |
b20c38cc | 3218 | VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0); |
bd6639fd | 3219 | |
89cd7b59 | 3220 | if (fGenerate == true || VERUS_MINTBLOCKS) |
10214558 | 3221 | { |
89cd7b59 MT |
3222 | mapArgs["-gen"] = "1"; |
3223 | ||
3224 | if (VERUS_CHEATCATCHER.size() > 0) | |
99c94fc3 | 3225 | { |
89cd7b59 MT |
3226 | if (cheatCatcher == boost::none) |
3227 | { | |
3228 | LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n"); | |
3229 | fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n"); | |
3230 | } | |
3231 | else | |
3232 | { | |
3233 | LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3234 | fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3235 | } | |
99c94fc3 | 3236 | } |
3237 | } | |
10214558 | 3238 | |
e9e70b95 | 3239 | static boost::thread_group* minerThreads = NULL; |
28424e9f | 3240 | |
e9e70b95 | 3241 | if (nThreads < 0) |
3242 | nThreads = GetNumCores(); | |
3243 | ||
3244 | if (minerThreads != NULL) | |
3245 | { | |
3246 | minerThreads->interrupt_all(); | |
3247 | delete minerThreads; | |
3248 | minerThreads = NULL; | |
3249 | } | |
135fa24e | 3250 | |
afaeb54b | 3251 | //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate); |
5034d1c1 | 3252 | if ( nThreads == 0 && ASSETCHAINS_STAKED ) |
3a446d9f | 3253 | nThreads = 1; |
5034d1c1 | 3254 | |
28424e9f | 3255 | if (!fGenerate) |
e9e70b95 | 3256 | return; |
135fa24e | 3257 | |
e9e70b95 | 3258 | minerThreads = new boost::thread_group(); |
135fa24e | 3259 | |
85c51d62 | 3260 | // add the PBaaS thread when mining or staking |
3261 | minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub)); | |
3262 | ||
135fa24e | 3263 | #ifdef ENABLE_WALLET |
b20c38cc | 3264 | if (VERUS_MINTBLOCKS && pwallet != NULL) |
135fa24e | 3265 | { |
3266 | minerThreads->create_thread(boost::bind(&VerusStaker, pwallet)); | |
3267 | } | |
3268 | #endif | |
3269 | ||
e9e70b95 | 3270 | for (int i = 0; i < nThreads; i++) { |
135fa24e | 3271 | |
8e8b6d70 | 3272 | #ifdef ENABLE_WALLET |
135fa24e | 3273 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3274 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
3275 | else | |
3276 | minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet)); | |
8e8b6d70 | 3277 | #else |
135fa24e | 3278 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3279 | minerThreads->create_thread(&BitcoinMiner); | |
3280 | else | |
3281 | minerThreads->create_thread(&BitcoinMiner_noeq); | |
8e8b6d70 | 3282 | #endif |
e9e70b95 | 3283 | } |
8e8b6d70 | 3284 | } |
e9e70b95 | 3285 | |
2cc0a252 | 3286 | #endif // ENABLE_MINING |