]>
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(); | |
a1a4dc8b | 331 | CCoinbaseCurrencyState currencyState = CCoinbaseCurrencyState(CCurrencyState(thisChain.conversion, thisChain.premine, 0, 0, 0), 0, 0, CReserveOutput(), 0, 0, 0); |
41f170fd MT |
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 | { |
68b309c0 | 668 | // if we don't have a connected root PBaaS chain, we can't properly check |
41f170fd | 669 | // and notarize the start block, so we have to pass the notarization and cross chain steps |
989b1de1 | 670 | bool notaryConnected = ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK; |
e7e14f44 | 671 | |
e7c700b5 | 672 | // get current currency state differently, depending on height |
e7e14f44 MT |
673 | if (nHeight == 1) |
674 | { | |
5b122537 | 675 | blockSubsidy -= GetBlockOnePremine(); // separate subsidy, which can go to miner, from premine |
676 | ||
e7e14f44 MT |
677 | if (!notaryConnected) |
678 | { | |
e7c700b5 | 679 | // cannt make block 1 unless we can properly notarize that the launch chain is past the start block |
e7e14f44 MT |
680 | return NULL; |
681 | } | |
682 | ||
e7c700b5 | 683 | // if some amount of pre-conversion was allowed |
e7e14f44 MT |
684 | if (thisChain.maxpreconvert) |
685 | { | |
686 | // this is invalid | |
687 | if (thisChain.conversion <= 0) | |
688 | { | |
689 | return NULL; | |
690 | } | |
691 | ||
692 | // get the total amount pre-converted | |
693 | UniValue params(UniValue::VARR); | |
694 | params.push_back(ASSETCHAINS_CHAINID.GetHex()); | |
695 | ||
696 | UniValue result; | |
697 | try | |
698 | { | |
699 | result = find_value(RPCCallRoot("getinitialcurrencystate", params), "result"); | |
700 | } catch (exception e) | |
701 | { | |
702 | result = NullUniValue; | |
703 | } | |
704 | ||
58148aef | 705 | if (!result.isNull()) |
706 | { | |
707 | currencyState = CCoinbaseCurrencyState(result); | |
708 | } | |
709 | ||
710 | if (result.isNull() || !currencyState.IsValid()) | |
e7e14f44 MT |
711 | { |
712 | // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail | |
713 | LogPrintf("Unable to get initial currency state to create block.\n"); | |
714 | printf("Failure to get initial currency state. Cannot create block.\n"); | |
715 | return NULL; | |
716 | } | |
44bbca51 | 717 | |
718 | if (currencyState.ReserveIn < ConnectedChains.ThisChain().minpreconvert) | |
719 | { | |
720 | // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail | |
721 | LogPrintf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n"); | |
722 | printf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n"); | |
723 | return NULL; | |
724 | } | |
e7e14f44 | 725 | } |
41f170fd MT |
726 | |
727 | // add needed block one coinbase outputs | |
88bc6df5 | 728 | // send normal reward to the miner, premine to the address in the chain definition, and pre-converted to the |
41f170fd | 729 | // import thread out |
dd4f0fdd | 730 | if (GetBlockOnePremine()) |
e7e14f44 | 731 | { |
41f170fd MT |
732 | premineOut = CTxOut(GetBlockOnePremine(), GetScriptForDestination(CTxDestination(ConnectedChains.ThisChain().address))); |
733 | coinbaseTx.vout.push_back(premineOut); | |
e7e14f44 | 734 | } |
41f170fd MT |
735 | |
736 | // chain definition - always | |
737 | // make the chain definition output | |
738 | vKeys.clear(); | |
739 | cp = CCinit(&CC, EVAL_PBAASDEFINITION); | |
740 | ||
741 | // send this to EVAL_PBAASDEFINITION address as a destination, locked by the default pubkey | |
c3250dcd | 742 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
41f170fd MT |
743 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_PBAASDEFINITION))); |
744 | thisChain.preconverted = currencyState.ReserveIn; // update known, preconverted amount | |
715182a4 | 745 | |
c3250dcd | 746 | chainDefinitionOut = MakeCC1of1Vout(EVAL_PBAASDEFINITION, 0, pkCC, vKeys, thisChain); |
41f170fd MT |
747 | coinbaseTx.vout.push_back(chainDefinitionOut); |
748 | ||
749 | // import - only spendable for reserve currency or currency with preconversion to allow import of conversions, this output will include | |
90100fac | 750 | // all pre-converted coins and all pre-conversion fees, denominated in Verus reserve currency |
41f170fd MT |
751 | // chain definition - always |
752 | // make the chain definition output | |
753 | vKeys.clear(); | |
754 | cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT); | |
755 | ||
c3250dcd MT |
756 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
757 | ||
758 | // import thread is specific to the chain importing from | |
759 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetChainID(), EVAL_CROSSCHAIN_IMPORT))); | |
41f170fd | 760 | |
1b268198 | 761 | // log import of all reserve in as well as the fees that are passed through the initial ReserveOut in the initial import |
41f170fd | 762 | importThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_IMPORT, |
c3250dcd | 763 | currencyState.ReserveToNative(thisChain.preconverted, thisChain.conversion), pkCC, vKeys, |
1b268198 | 764 | CCrossChainImport(ConnectedChains.NotaryChain().GetChainID(), currencyState.ReserveIn + currencyState.ReserveOut.nValue)); |
c3250dcd | 765 | |
41f170fd MT |
766 | coinbaseTx.vout.push_back(importThreadOut); |
767 | ||
768 | // export - currently only spendable for reserve currency, but added for future capabilities | |
769 | vKeys.clear(); | |
770 | cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT); | |
771 | ||
c3250dcd | 772 | pkCC = CPubKey(ParseHex(CC.CChexstr)); |
85ed4204 | 773 | vKeys.push_back(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_EXPORT))); |
41f170fd | 774 | |
c3250dcd | 775 | exportThreadOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_EXPORT, 0, pkCC, vKeys, |
41f170fd MT |
776 | CCrossChainExport(ConnectedChains.NotaryChain().GetChainID(), 0, 0, 0)); |
777 | coinbaseTx.vout.push_back(exportThreadOut); | |
e7e14f44 MT |
778 | } |
779 | else | |
989b1de1 | 780 | { |
e7e14f44 | 781 | CBlock block; |
e7c700b5 | 782 | assert(nHeight > 1); |
41f170fd | 783 | currencyState = ConnectedChains.GetCurrencyState(nHeight - 1); |
1f15dff1 | 784 | currencyState.Fees = 0; |
5b122537 | 785 | currencyState.ConversionFees = 0; |
1f15dff1 | 786 | currencyState.NativeIn = 0; |
787 | currencyState.ReserveIn = 0; | |
788 | currencyState.ReserveOut.nValue = 0; | |
789 | ||
41f170fd | 790 | if (!currencyState.IsValid()) |
e7e14f44 | 791 | { |
41f170fd MT |
792 | // we should be able to get a valid currency state, if not, fail |
793 | LogPrintf("Unable to get initial currency state to create block #%d.\n", nHeight); | |
794 | printf("Failure to get initial currency state. Cannot create block #%d.\n", nHeight); | |
795 | return NULL; | |
e7e14f44 | 796 | } |
989b1de1 MT |
797 | } |
798 | ||
34d1aa13 | 799 | // update the currency state to include emissions before calculating conversions |
58148aef | 800 | // premine is an emission that is factored in before this |
34d1aa13 MT |
801 | currencyState.UpdateWithEmission(totalEmission); |
802 | ||
41f170fd MT |
803 | // always add currency state output for coinbase |
804 | vKeys.clear(); | |
805 | cp = CCinit(&CC, EVAL_CURRENCYSTATE); | |
806 | ||
7b961d96 | 807 | CPubKey currencyOutPK(ParseHex(cp->CChexstr)); |
41f170fd | 808 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_CURRENCYSTATE)))); |
41f170fd MT |
809 | |
810 | // make an output that either carries zero coins pre-converting, or the initial supply for block 1, conversion amounts will be adjusted later | |
7b961d96 | 811 | currencyStateOut = MakeCC1of1Vout(EVAL_CURRENCYSTATE, 0, currencyOutPK, vKeys, currencyState); |
41f170fd MT |
812 | |
813 | coinbaseTx.vout.push_back(currencyStateOut); | |
814 | ||
989b1de1 | 815 | if (notaryConnected) |
4fa3b13d | 816 | { |
41f170fd | 817 | // if we have access to our notary daemon |
1fa4454d | 818 | // create a notarization if we would qualify, and add it to the mempool and block |
687e93d5 | 819 | CTransaction prevTx, crossTx, lastConfirmed, lastImportTx; |
4fa3b13d | 820 | ChainMerkleMountainView mmv = chainActive.GetMMV(); |
8577896f | 821 | mmrRoot = mmv.GetRoot(); |
1fa4454d MT |
822 | int32_t confirmedInput = -1; |
823 | CTxDestination confirmedDest; | |
687e93d5 | 824 | if (CreateEarnedNotarization(newNotarizationTx, notarizationInputs, prevTx, crossTx, lastConfirmed, nHeight, &confirmedInput, &confirmedDest)) |
4fa3b13d | 825 | { |
1fa4454d MT |
826 | // we have a valid, earned notarization transaction. we still need to complete it as follows: |
827 | // 1. Add an instant-spend input from the coinbase transaction to fund the finalization output | |
828 | // | |
829 | // 2. if we are spending finalization outputs, create an output of the same amount as a finalization output | |
830 | // plus and any excess from the other, orphaned finalizations to the creator of the confirmed notarization | |
831 | // | |
e7e14f44 MT |
832 | // 3. make sure the currency state is correct |
833 | ||
1fa4454d | 834 | // input should either be 0 or PBAAS_MINNOTARIZATIONOUTPUT + all finalized outputs |
41f170fd | 835 | // 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 |
836 | for (const CTxIn& txin : newNotarizationTx.vin) |
837 | { | |
838 | const uint256& prevHash = txin.prevout.hash; | |
1fa4454d | 839 | const CCoins *pcoins = view.AccessCoins(prevHash); |
68b309c0 MT |
840 | pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0; |
841 | } | |
eb0a6550 | 842 | |
1fa4454d MT |
843 | // calculate the amount that will be sent to the confirmed notary address |
844 | // this will only be non-zero if we have finalized inputs | |
845 | if (pbaasTransparentIn > 0) | |
eb0a6550 | 846 | { |
1fa4454d | 847 | pbaasTransparentOut = pbaasTransparentIn - PBAAS_MINNOTARIZATIONOUTPUT; |
eb0a6550 | 848 | } |
849 | ||
1fa4454d | 850 | if (pbaasTransparentOut) |
eb0a6550 | 851 | { |
1fa4454d MT |
852 | // if we are on a non-fungible chain, reward out must be unspendable |
853 | // make a normal output to the confirmed notary with the excess right behind the op_return | |
854 | // TODO: make this a cc out to only allow spending on a fungible chain | |
855 | CTxOut rewardOut = CTxOut(pbaasTransparentOut, GetScriptForDestination(confirmedDest)); | |
856 | newNotarizationTx.vout.insert(newNotarizationTx.vout.begin() + newNotarizationTx.vout.size() - 1, rewardOut); | |
eb0a6550 | 857 | } |
41f170fd MT |
858 | |
859 | // make the earned notarization coinbase output | |
860 | vKeys.clear(); | |
861 | cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION); | |
862 | ||
863 | // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey | |
c3250dcd | 864 | pkCC = CPubKey(ParseHex(cp->CChexstr)); |
6b732553 | 865 | vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION)))); |
41f170fd MT |
866 | |
867 | int64_t needed = nHeight == 1 ? PBAAS_MINNOTARIZATIONOUTPUT << 1 : PBAAS_MINNOTARIZATIONOUTPUT; | |
868 | ||
869 | // output duplicate notarization as coinbase output for instant spend to notarization | |
870 | // the output amount is considered part of the total value of this coinbase | |
871 | CPBaaSNotarization pbn(newNotarizationTx); | |
c3250dcd | 872 | notarizationOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pkCC, vKeys, pbn); |
41f170fd MT |
873 | coinbaseTx.vout.push_back(notarizationOut); |
874 | ||
bb6c3482 | 875 | // place the notarization |
876 | pblock->vtx.push_back(CTransaction(newNotarizationTx)); | |
877 | pblocktemplate->vTxFees.push_back(0); | |
878 | pblocktemplate->vTxSigOps.push_back(-1); // updated at end | |
879 | nBlockSize += GetSerializeSize(newNotarizationTx, SER_NETWORK, PROTOCOL_VERSION); | |
880 | notarizationTxIndex = pblock->vtx.size() - 1; | |
881 | nBlockTx++; | |
68b309c0 MT |
882 | } |
883 | else if (nHeight == 1) | |
884 | { | |
885 | // failed to notarize at block 1 | |
886 | return NULL; | |
4fa3b13d | 887 | } |
687e93d5 MT |
888 | |
889 | // if we have a last confirmed notarization, then check for new imports from the notary chain | |
890 | if (lastConfirmed.vout.size()) | |
891 | { | |
892 | // we need to find the last unspent import transaction | |
893 | std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue> > unspentOutputs; | |
894 | ||
895 | bool found = false; | |
896 | ||
897 | // we cannot get export to a chain that has shut down | |
898 | // if the chain definition is spent, a chain is inactive | |
899 | if (GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetChainID(), EVAL_CROSSCHAIN_IMPORT)), 1, unspentOutputs)) | |
900 | { | |
0c21c983 | 901 | // if one spends the prior one, get the one that is not spent |
687e93d5 MT |
902 | for (auto txidx : unspentOutputs) |
903 | { | |
687e93d5 MT |
904 | uint256 blkHash; |
905 | CTransaction itx; | |
906 | if (myGetTransaction(txidx.first.txhash, lastImportTx, blkHash) && | |
907 | CCrossChainImport(lastImportTx).IsValid() && | |
908 | (lastImportTx.IsCoinBase() || | |
909 | (myGetTransaction(lastImportTx.vin[0].prevout.hash, itx, blkHash) && | |
910 | CCrossChainImport(itx).IsValid()))) | |
911 | { | |
912 | found = true; | |
0c21c983 | 913 | break; |
687e93d5 MT |
914 | } |
915 | } | |
916 | } | |
917 | ||
67aac3cf | 918 | if (found && pwalletMain) |
687e93d5 MT |
919 | { |
920 | UniValue params(UniValue::VARR); | |
921 | UniValue param(UniValue::VOBJ); | |
922 | ||
4f86f9ca | 923 | CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); |
924 | int i; | |
925 | for (i = 0; i < lastImportTx.vout.size(); i++) | |
687e93d5 | 926 | { |
4f86f9ca | 927 | COptCCParams p; |
928 | if (lastImportTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.evalCode == EVAL_CROSSCHAIN_IMPORT) | |
929 | { | |
930 | txTemplate.vin.push_back(CTxIn(lastImportTx.GetHash(), (uint32_t)i)); | |
931 | break; | |
932 | } | |
933 | } | |
934 | ||
935 | UniValue result = NullUniValue; | |
936 | if (i < lastImportTx.vout.size()) | |
687e93d5 | 937 | { |
4f86f9ca | 938 | param.push_back(Pair("name", thisChain.name)); |
939 | param.push_back(Pair("lastimporttx", EncodeHexTx(lastImportTx))); | |
940 | param.push_back(Pair("lastconfirmednotarization", EncodeHexTx(lastConfirmed))); | |
5e346982 | 941 | param.push_back(Pair("importtxtemplate", EncodeHexTx(txTemplate))); |
05075a67 | 942 | param.push_back(Pair("totalimportavailable", lastImportTx.vout[txTemplate.vin[0].prevout.n].nValue)); |
4f86f9ca | 943 | params.push_back(param); |
944 | ||
945 | try | |
946 | { | |
947 | result = find_value(RPCCallRoot("getlatestimportsout", params), "result"); | |
948 | } catch (exception e) | |
949 | { | |
950 | printf("Could not get latest imports from notary chain\n"); | |
951 | } | |
687e93d5 MT |
952 | } |
953 | ||
67aac3cf | 954 | if (result.isArray() && result.size()) |
687e93d5 MT |
955 | { |
956 | LOCK(pwalletMain->cs_wallet); | |
957 | ||
958 | uint256 lastImportHash = lastImportTx.GetHash(); | |
959 | for (int i = 0; i < result.size(); i++) | |
960 | { | |
961 | CTransaction itx; | |
962 | if (result[i].isStr() && DecodeHexTx(itx, result[i].get_str()) && itx.vin.size() && itx.vin[0].prevout.hash == lastImportHash) | |
963 | { | |
0574c740 | 964 | // sign the transaction spending the last import and add to mempool |
687e93d5 MT |
965 | CMutableTransaction mtx(itx); |
966 | CCrossChainImport cci(lastImportTx); | |
967 | ||
968 | bool signSuccess; | |
969 | SignatureData sigdata; | |
970 | CAmount value; | |
971 | const CScript *pScriptPubKey; | |
972 | ||
687e93d5 | 973 | signSuccess = ProduceSignature( |
67aac3cf | 974 | 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 | 975 | |
0574c740 | 976 | if (!signSuccess) |
687e93d5 | 977 | { |
0574c740 | 978 | break; |
687e93d5 MT |
979 | } |
980 | ||
0574c740 | 981 | UpdateTransaction(mtx, 0, sigdata); |
9a91da5a | 982 | itx = CTransaction(mtx); |
0574c740 | 983 | |
687e93d5 MT |
984 | // commit to mempool and remove any conflicts |
985 | std::list<CTransaction> removed; | |
986 | mempool.removeConflicts(itx, removed); | |
987 | CValidationState state; | |
988 | if (!myAddtomempool(itx, &state)) | |
989 | { | |
bb6c3482 | 990 | LogPrintf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); |
991 | printf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str()); | |
687e93d5 MT |
992 | break; // if we failed to add one, the others will fail to spend it |
993 | } | |
0574c740 | 994 | |
995 | lastImportTx = itx; | |
996 | lastImportHash = itx.GetHash(); | |
687e93d5 MT |
997 | } |
998 | } | |
999 | } | |
1000 | } | |
1001 | } | |
4fa3b13d | 1002 | } |
e7e14f44 | 1003 | } |
34d1aa13 MT |
1004 | else |
1005 | { | |
1006 | currencyState.UpdateWithEmission(totalEmission); | |
1007 | } | |
e7e14f44 | 1008 | |
41f170fd MT |
1009 | // coinbase should have all necessary outputs (TODO: timelock is not supported or finished yet) |
1010 | uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION); | |
1011 | nBlockSize += nCoinbaseSize; | |
e7c700b5 | 1012 | |
41f170fd MT |
1013 | // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later |
1014 | bool haveReserveTransactions = false; | |
1015 | uint32_t reserveExchangeLimitSize = 0; | |
1016 | std::vector<const CTransaction *> limitOrders; | |
e7e14f44 | 1017 | |
41f170fd | 1018 | // now add transactions from the mem pool to the priority heap |
e328fa32 | 1019 | for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin(); |
4d707d51 | 1020 | mi != mempool.mapTx.end(); ++mi) |
d247a5d1 | 1021 | { |
e328fa32 | 1022 | const CTransaction& tx = mi->GetTx(); |
41f170fd | 1023 | uint256 hash = tx.GetHash(); |
e9e70b95 | 1024 | |
a1d3c6fb | 1025 | int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) |
e9e70b95 | 1026 | ? nMedianTimePast |
1027 | : pblock->GetBlockTime(); | |
9c034267 | 1028 | |
9bb37bf0 | 1029 | if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) |
61f8caf2 | 1030 | { |
51376f3c | 1031 | //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight)); |
14aa6cc0 | 1032 | continue; |
61f8caf2 | 1033 | } |
9c034267 | 1034 | |
161f617d | 1035 | if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) |
6ff77181 | 1036 | { |
64b45b71 | 1037 | //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 | 1038 | continue; |
14aa6cc0 | 1039 | } |
df756d24 | 1040 | |
d247a5d1 JG |
1041 | COrphan* porphan = NULL; |
1042 | double dPriority = 0; | |
a372168e | 1043 | CAmount nTotalIn = 0; |
e7e14f44 | 1044 | CAmount nTotalReserveIn = 0; |
d247a5d1 | 1045 | bool fMissingInputs = false; |
41f170fd MT |
1046 | CReserveTransactionDescriptor rtxd; |
1047 | bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd); | |
e7e14f44 | 1048 | |
0cb91a8d | 1049 | if (tx.IsCoinImport()) |
d247a5d1 | 1050 | { |
0cb91a8d SS |
1051 | CAmount nValueIn = GetCoinImportValue(tx); |
1052 | nTotalIn += nValueIn; | |
1053 | dPriority += (double)nValueIn * 1000; // flat multiplier | |
1054 | } else { | |
41f170fd | 1055 | // 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 | 1056 | if (isReserve && rtxd.IsReserveExchange() && rtxd.IsLimit()) |
41f170fd MT |
1057 | { |
1058 | // if we might expire, refresh and check again | |
1059 | if (rtxd.IsFillOrKill()) | |
1060 | { | |
1061 | rtxd = CReserveTransactionDescriptor(tx, view, nHeight); | |
1062 | mempool.PrioritiseReserveTransaction(rtxd, currencyState); | |
1063 | } | |
1064 | ||
1065 | // if is is a failed conversion, drop through | |
1066 | if (!rtxd.IsFillOrKillFail()) | |
1067 | { | |
1068 | limitOrders.push_back(&tx); | |
1069 | reserveExchangeLimitSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd MT |
1070 | continue; |
1071 | } | |
1072 | } | |
1073 | if (isReserve) | |
1074 | { | |
1075 | nTotalIn += rtxd.nativeIn; | |
1076 | nTotalReserveIn += rtxd.reserveIn; | |
1077 | } | |
0cb91a8d | 1078 | BOOST_FOREACH(const CTxIn& txin, tx.vin) |
d247a5d1 | 1079 | { |
41f170fd MT |
1080 | CAmount nValueIn = 0, nReserveValueIn = 0; |
1081 | ||
0cb91a8d SS |
1082 | // Read prev transaction |
1083 | if (!view.HaveCoins(txin.prevout.hash)) | |
d247a5d1 | 1084 | { |
0cb91a8d SS |
1085 | // This should never happen; all transactions in the memory |
1086 | // pool should connect to either transactions in the chain | |
1087 | // or other transactions in the memory pool. | |
1088 | if (!mempool.mapTx.count(txin.prevout.hash)) | |
1089 | { | |
1090 | LogPrintf("ERROR: mempool transaction missing input\n"); | |
1091 | if (fDebug) assert("mempool transaction missing input" == 0); | |
1092 | fMissingInputs = true; | |
1093 | if (porphan) | |
1094 | vOrphan.pop_back(); | |
1095 | break; | |
1096 | } | |
1097 | ||
1098 | // Has to wait for dependencies | |
1099 | if (!porphan) | |
1100 | { | |
1101 | // Use list for automatic deletion | |
1102 | vOrphan.push_back(COrphan(&tx)); | |
1103 | porphan = &vOrphan.back(); | |
1104 | } | |
1105 | mapDependers[txin.prevout.hash].push_back(porphan); | |
1106 | porphan->setDependsOn.insert(txin.prevout.hash); | |
e7e14f44 MT |
1107 | |
1108 | const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx(); | |
e7e14f44 | 1109 | // consider reserve outputs and set priority according to their value here as well |
71a3314d | 1110 | if (!isReserve) |
e7e14f44 | 1111 | { |
71a3314d | 1112 | nTotalIn += otx.vout[txin.prevout.n].nValue; |
e7e14f44 | 1113 | } |
0cb91a8d | 1114 | continue; |
d247a5d1 | 1115 | } |
0cb91a8d SS |
1116 | const CCoins* coins = view.AccessCoins(txin.prevout.hash); |
1117 | assert(coins); | |
1118 | ||
e7e14f44 | 1119 | // consider reserve outputs and set priority according to their value here as well |
41f170fd | 1120 | if (isReserve) |
e7e14f44 | 1121 | { |
41f170fd | 1122 | nReserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue(); |
e7e14f44 | 1123 | } |
0cb91a8d | 1124 | |
41f170fd | 1125 | nValueIn = coins->vout[txin.prevout.n].nValue; |
0cb91a8d SS |
1126 | int nConf = nHeight - coins->nHeight; |
1127 | ||
41f170fd | 1128 | dPriority += ((double)((nReserveValueIn ? currencyState.ReserveToNative(nReserveValueIn) : 0) + nValueIn)) * nConf; |
71a3314d | 1129 | |
1130 | // reserve is totaled differently | |
1131 | if (!isReserve) | |
1132 | { | |
1133 | nTotalIn += nValueIn; | |
1134 | nTotalReserveIn += nReserveValueIn; | |
1135 | } | |
d247a5d1 | 1136 | } |
9feb4b9e | 1137 | nTotalIn += tx.GetShieldedValueIn(); |
d247a5d1 | 1138 | } |
0cb91a8d | 1139 | |
d247a5d1 | 1140 | if (fMissingInputs) continue; |
e9e70b95 | 1141 | |
d6eb2599 | 1142 | // Priority is sum(valuein * age) / modified_txsize |
d247a5d1 | 1143 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); |
4d707d51 | 1144 | dPriority = tx.ComputePriority(dPriority, nTxSize); |
e9e70b95 | 1145 | |
41f170fd MT |
1146 | CAmount nDeltaValueIn = nTotalIn + (nTotalReserveIn ? currencyState.ReserveToNative(nTotalReserveIn) : 0); |
1147 | CAmount nFeeValueIn = nDeltaValueIn; | |
1148 | mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn); | |
e7e14f44 | 1149 | |
71a3314d | 1150 | CAmount nativeEquivalentOut = 0; |
e7e14f44 MT |
1151 | |
1152 | // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly | |
41f170fd | 1153 | if (isReserve & rtxd.reserveOut) |
e7e14f44 MT |
1154 | { |
1155 | // if this has reserve currency out, convert it to native currency for fee calculation | |
71a3314d | 1156 | nativeEquivalentOut = currencyState.ReserveToNative(rtxd.reserveOut); |
e7e14f44 MT |
1157 | } |
1158 | ||
a1a4dc8b | 1159 | CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) + currencyState.ReserveToNative(rtxd.reserveConversionFees) + rtxd.nativeConversionFees : nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize); |
e7e14f44 | 1160 | |
d247a5d1 JG |
1161 | if (porphan) |
1162 | { | |
1163 | porphan->dPriority = dPriority; | |
c6cb21d1 | 1164 | porphan->feeRate = feeRate; |
d247a5d1 JG |
1165 | } |
1166 | else | |
e328fa32 | 1167 | vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); |
d247a5d1 | 1168 | } |
df756d24 | 1169 | |
41f170fd MT |
1170 | // |
1171 | // NOW -- REALLY START TO FILL THE BLOCK | |
bb6c3482 | 1172 | // |
41f170fd | 1173 | // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required |
e7c700b5 | 1174 | |
41f170fd | 1175 | int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize); |
e7e14f44 | 1176 | |
355ca565 | 1177 | int64_t interest; |
d247a5d1 | 1178 | bool fSortedByFee = (nBlockPrioritySize <= 0); |
41f170fd | 1179 | |
d247a5d1 JG |
1180 | TxPriorityCompare comparer(fSortedByFee); |
1181 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
41f170fd MT |
1182 | |
1183 | std::vector<int> reservePositions; | |
1184 | ||
1185 | // now loop and fill the block, leaving space for reserve exchange limit transactions | |
d247a5d1 JG |
1186 | while (!vecPriority.empty()) |
1187 | { | |
1188 | // Take highest priority transaction off the priority queue: | |
1189 | double dPriority = vecPriority.front().get<0>(); | |
c6cb21d1 | 1190 | CFeeRate feeRate = vecPriority.front().get<1>(); |
4d707d51 | 1191 | const CTransaction& tx = *(vecPriority.front().get<2>()); |
e9e70b95 | 1192 | |
d247a5d1 JG |
1193 | std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1194 | vecPriority.pop_back(); | |
e9e70b95 | 1195 | |
d247a5d1 JG |
1196 | // Size limits |
1197 | unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); | |
41f170fd | 1198 | if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx |
61f8caf2 | 1199 | { |
41f170fd | 1200 | //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize); |
d247a5d1 | 1201 | continue; |
61f8caf2 | 1202 | } |
e9e70b95 | 1203 | |
d247a5d1 JG |
1204 | // Legacy limits on sigOps: |
1205 | unsigned int nTxSigOps = GetLegacySigOpCount(tx); | |
a4a40a38 | 1206 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) |
61f8caf2 | 1207 | { |
51376f3c | 1208 | //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 | 1209 | continue; |
61f8caf2 | 1210 | } |
d247a5d1 | 1211 | // Skip free transactions if we're past the minimum block size: |
805344dc | 1212 | const uint256& hash = tx.GetHash(); |
2a72d459 | 1213 | double dPriorityDelta = 0; |
a372168e | 1214 | CAmount nFeeDelta = 0; |
2a72d459 | 1215 | mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); |
13fc83c7 | 1216 | if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) |
61f8caf2 | 1217 | { |
51376f3c | 1218 | //fprintf(stderr,"fee rate skip\n"); |
d247a5d1 | 1219 | continue; |
61f8caf2 | 1220 | } |
41f170fd | 1221 | |
2a72d459 | 1222 | // Prioritise by fee once past the priority size or we run out of high-priority |
d247a5d1 JG |
1223 | // transactions: |
1224 | if (!fSortedByFee && | |
1225 | ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority))) | |
1226 | { | |
1227 | fSortedByFee = true; | |
1228 | comparer = TxPriorityCompare(fSortedByFee); | |
1229 | std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); | |
1230 | } | |
e9e70b95 | 1231 | |
d247a5d1 | 1232 | if (!view.HaveInputs(tx)) |
61f8caf2 | 1233 | { |
51376f3c | 1234 | //fprintf(stderr,"dont have inputs\n"); |
d247a5d1 | 1235 | continue; |
61f8caf2 | 1236 | } |
41f170fd MT |
1237 | CAmount nTxFees; |
1238 | CReserveTransactionDescriptor txDesc; | |
1239 | bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc); | |
1240 | ||
88bc6df5 MT |
1241 | nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut(); |
1242 | ||
1243 | nTxSigOps += GetP2SHSigOpCount(tx, view); | |
1244 | if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) | |
41f170fd | 1245 | { |
88bc6df5 MT |
1246 | //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS); |
1247 | continue; | |
61f8caf2 | 1248 | } |
41f170fd | 1249 | |
68f7d1d7 PT |
1250 | // Note that flags: we don't want to set mempool/IsStandard() |
1251 | // policy here, but we still have to ensure that the block we | |
1252 | // create only contains transactions that are valid in new blocks. | |
d247a5d1 | 1253 | CValidationState state; |
6514771a | 1254 | PrecomputedTransactionData txdata(tx); |
be126699 | 1255 | if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) |
61f8caf2 | 1256 | { |
51376f3c | 1257 | //fprintf(stderr,"context failure\n"); |
d247a5d1 | 1258 | continue; |
61f8caf2 | 1259 | } |
e7e14f44 | 1260 | |
8cb98d91 | 1261 | UpdateCoins(tx, view, nHeight); |
d247a5d1 | 1262 | |
41f170fd MT |
1263 | if (isReserve) |
1264 | { | |
88bc6df5 | 1265 | nTxFees = 0; // we will adjust all reserve transaction fees when we get an accurate conversion rate |
41f170fd MT |
1266 | reservePositions.push_back(nBlockTx); |
1267 | haveReserveTransactions = true; | |
1268 | } | |
1269 | ||
31a04d28 SB |
1270 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1271 | sapling_tree.append(outDescription.cm); | |
1272 | } | |
1273 | ||
d247a5d1 JG |
1274 | // Added |
1275 | pblock->vtx.push_back(tx); | |
1276 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1277 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1278 | nBlockSize += nTxSize; | |
1279 | ++nBlockTx; | |
1280 | nBlockSigOps += nTxSigOps; | |
1281 | nFees += nTxFees; | |
e9e70b95 | 1282 | |
d247a5d1 JG |
1283 | if (fPrintPriority) |
1284 | { | |
3f0813b3 | 1285 | LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); |
d247a5d1 | 1286 | } |
e9e70b95 | 1287 | |
d247a5d1 JG |
1288 | // Add transactions that depend on this one to the priority queue |
1289 | if (mapDependers.count(hash)) | |
1290 | { | |
1291 | BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) | |
1292 | { | |
1293 | if (!porphan->setDependsOn.empty()) | |
1294 | { | |
1295 | porphan->setDependsOn.erase(hash); | |
1296 | if (porphan->setDependsOn.empty()) | |
1297 | { | |
c6cb21d1 | 1298 | vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx)); |
d247a5d1 JG |
1299 | std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); |
1300 | } | |
1301 | } | |
1302 | } | |
1303 | } | |
1304 | } | |
e7c700b5 | 1305 | |
41f170fd MT |
1306 | // if we have reserve transactions or limit transactions to add: |
1307 | // 1. collect all the reserve transactions from the block and add them to the reserveFills vector | |
1308 | // 2. add all limit transactions to the orders vector | |
1309 | // 3. match orders to include all limit transactions that qualify and will fit | |
a1a4dc8b | 1310 | CAmount conversionFees = 0; |
1311 | ||
41f170fd MT |
1312 | if (haveReserveTransactions) |
1313 | { | |
1314 | std::vector<CReserveTransactionDescriptor> reserveFills; | |
1315 | std::vector<const CTransaction *> expiredFillOrKills; | |
1316 | std::vector<const CTransaction *> noFills; | |
1317 | std::vector<const CTransaction *> rejects; | |
e7c700b5 | 1318 | |
41f170fd MT |
1319 | // identify all reserve transactions in the block to calculate fees |
1320 | for (int i = 0; i < reservePositions.size(); i++) | |
1321 | { | |
1322 | CReserveTransactionDescriptor txDesc; | |
0059e3a5 | 1323 | if (mempool.IsKnownReserveTransaction(pblock->vtx[reservePositions[i]].GetHash(), txDesc)) |
41f170fd MT |
1324 | { |
1325 | reserveFills.push_back(txDesc); | |
1326 | } | |
1327 | } | |
135fa24e | 1328 | |
41f170fd MT |
1329 | // now, we need to have room for the transaction which will spend the coinbase |
1330 | // and output all conversions mined/staked | |
1331 | newConversionOutputTx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight); | |
9e87ac50 | 1332 | newConversionOutputTx.vin.resize(1); // placeholder for size calculation |
41f170fd MT |
1333 | |
1334 | int64_t newBlockSize = nBlockSize; | |
88bc6df5 | 1335 | |
47aecf2f | 1336 | // TODO:PBAAS - NEED TO ADD SIGOPS LIMIT TO THIS FOR HARDENING |
1337 | CCoinbaseCurrencyState newState = currencyState.MatchOrders(limitOrders, | |
1338 | reserveFills, | |
1339 | expiredFillOrKills, | |
1340 | noFills, | |
1341 | rejects, | |
1342 | exchangeRate, nHeight, conversionInputs, | |
1343 | nBlockMaxSize - autoTxSize, &newBlockSize, &newConversionOutputTx); | |
88bc6df5 | 1344 | |
a1a4dc8b | 1345 | // TODO:PBAAS - account for the edge case where we have too large expected fills and have no room |
1346 | // for transactions that we would otherwise take | |
88bc6df5 | 1347 | assert(reserveFills.size() >= reservePositions.size()); |
41f170fd MT |
1348 | |
1349 | // create the conversion transaction and all outputs indicated by every single mined transaction | |
41f170fd MT |
1350 | if (reserveFills.size()) |
1351 | { | |
607402ba | 1352 | currencyState = newState; |
41f170fd | 1353 | } |
86e31e3d | 1354 | |
88bc6df5 | 1355 | int oldRPSize = reservePositions.size(); |
41f170fd | 1356 | |
88bc6df5 MT |
1357 | // add the rest of the reserve fills that have not yet been added to the block, |
1358 | for (int i = oldRPSize; i < reserveFills.size(); i++) | |
1f722359 | 1359 | { |
88bc6df5 MT |
1360 | // add these transactions to the block |
1361 | reservePositions.push_back(nBlockTx); | |
1362 | pblock->vtx.push_back(*reserveFills[i].ptx); | |
1363 | const CTransaction &tx = pblock->vtx.back(); | |
cd230e37 | 1364 | |
88bc6df5 | 1365 | UpdateCoins(tx, view, nHeight); |
41f170fd | 1366 | |
88bc6df5 MT |
1367 | BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) { |
1368 | sapling_tree.append(outDescription.cm); | |
1369 | } | |
41f170fd | 1370 | |
88bc6df5 MT |
1371 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); |
1372 | uint32_t nTxSigOps = GetLegacySigOpCount(tx); | |
41f170fd | 1373 | |
88bc6df5 MT |
1374 | // size was already updated |
1375 | pblocktemplate->vTxFees.push_back(nTxFees); | |
1376 | pblocktemplate->vTxSigOps.push_back(nTxSigOps); | |
1377 | ++nBlockTx; | |
1378 | nBlockSigOps += nTxSigOps; | |
1379 | nFees += nTxFees; | |
1f722359 | 1380 | } |
41f170fd | 1381 | |
88bc6df5 MT |
1382 | // update block size with the calculation from the function called, which includes all additional transactions, |
1383 | // but does not include the conversion transaction, since its final size is still unknown | |
1384 | nBlockSize = newBlockSize; | |
41f170fd | 1385 | |
88bc6df5 MT |
1386 | // fixup the transaction block template fees that were added before we knew the correct exchange rate and |
1387 | // add them to the block fee total | |
1388 | for (int i = 0; i < oldRPSize; i++) | |
1389 | { | |
1390 | assert(pblocktemplate->vTxFees.size() > reservePositions[i]); | |
1391 | CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate); | |
1392 | pblocktemplate->vTxFees[reservePositions[i]] = nTxFees; | |
1393 | nFees += nTxFees; | |
1f722359 MT |
1394 | } |
1395 | ||
88bc6df5 | 1396 | // remake the newConversionOutputTx, right now, it has dummy inputs and placeholder outputs, just remake it correctly |
9e87ac50 | 1397 | newConversionOutputTx.vin.resize(1); |
88bc6df5 | 1398 | newConversionOutputTx.vout.clear(); |
0574c740 | 1399 | conversionInputs.clear(); |
1400 | ||
9e87ac50 | 1401 | // keep one placeholder for txCoinbase output as input and remake with the correct exchange rate |
88bc6df5 | 1402 | for (auto fill : reserveFills) |
a4a40a38 | 1403 | { |
0574c740 | 1404 | fill.AddConversionInOuts(newConversionOutputTx, conversionInputs, exchangeRate, ¤cyState); |
41f170fd | 1405 | } |
a4a40a38 | 1406 | } |
abb90a89 | 1407 | |
05ece4c3 | 1408 | // first calculate and distribute block rewards, including fees in the minerOutputs vector |
88bc6df5 | 1409 | CAmount rewardTotalShareAmount = 0; |
a1a4dc8b | 1410 | CAmount rewardTotal = blockSubsidy + currencyState.ConversionFees + nFees; |
1411 | ||
d6f7d693 | 1412 | CAmount rewardLeft = notarizationTxIndex ? rewardTotal - notarizationOut.nValue : rewardTotal; |
41f170fd | 1413 | |
88bc6df5 MT |
1414 | for (auto &outputShare : minerOutputs) |
1415 | { | |
1416 | rewardTotalShareAmount += outputShare.first; | |
1417 | } | |
41f170fd | 1418 | |
88bc6df5 MT |
1419 | int cbOutIdx; |
1420 | for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++) | |
1421 | { | |
1422 | CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].first) / arith_uint256(rewardTotalShareAmount)).GetLow64(); | |
1423 | if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size()) | |
1424 | { | |
1425 | amount = rewardLeft; | |
1426 | } | |
1427 | rewardLeft -= amount; | |
1428 | coinbaseTx.vout[cbOutIdx].nValue = amount; | |
1429 | // the only valid CC output we currently support on coinbases is stake guard, which does not need to be modified for this | |
1430 | } | |
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 | ||
05ece4c3 | 1465 | if (conversionInputs.size()) |
90888b8a | 1466 | { |
90888b8a | 1467 | CTransaction convertTx(newConversionOutputTx); |
93440330 | 1468 | currencyStateOut.nValue = convertTx.GetValueOut(); |
1469 | currencyState.ReserveOut.nValue = convertTx.GetReserveValueOut(); | |
45d7e5d5 | 1470 | |
90888b8a | 1471 | // the coinbase is not finished, store index placeholder here now and fixup hash later |
1472 | newConversionOutputTx.vin[0] = CTxIn(uint256(), cbOutIdx); | |
1473 | } | |
05ece4c3 | 1474 | else |
1475 | { | |
1476 | newConversionOutputTx.vin.clear(); | |
1477 | newConversionOutputTx.vout.clear(); | |
1478 | } | |
88bc6df5 MT |
1479 | |
1480 | coinbaseTx.vout[cbOutIdx] = currencyStateOut; | |
88bc6df5 MT |
1481 | cbOutIdx++; |
1482 | } | |
06f41160 | 1483 | |
88bc6df5 MT |
1484 | // notarizationOut - update currencyState in notarization |
1485 | if (notarizationTxIndex) | |
06f41160 | 1486 | { |
88bc6df5 MT |
1487 | COptCCParams p; |
1488 | int i; | |
1489 | for (i = 0; i < newNotarizationTx.vout.size(); i++) | |
06f41160 | 1490 | { |
88bc6df5 | 1491 | if (newNotarizationTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.evalCode == EVAL_EARNEDNOTARIZATION) |
86e31e3d | 1492 | { |
88bc6df5 | 1493 | break; |
86e31e3d | 1494 | } |
1495 | } | |
88bc6df5 | 1496 | if (i >= newNotarizationTx.vout.size()) |
86e31e3d | 1497 | { |
88bc6df5 MT |
1498 | LogPrintf("CreateNewBlock: bad notarization\n"); |
1499 | fprintf(stderr,"CreateNewBlock: bad notarization\n"); | |
1500 | return NULL; | |
ebee7b5b | 1501 | } |
88bc6df5 MT |
1502 | CPBaaSNotarization nz(p.vData[0]); |
1503 | nz.currencyState = currencyState; | |
1504 | p.vData[0] = nz.AsVector(); | |
1505 | newNotarizationTx.vout[i].scriptPubKey.ReplaceCCParams(p); | |
1506 | ||
1507 | notarizationOut.scriptPubKey.IsPayToCryptoCondition(p); | |
1508 | p.vData[0] = nz.AsVector(); | |
1509 | notarizationOut.scriptPubKey.ReplaceCCParams(p); | |
1510 | ||
1511 | coinbaseTx.vout[cbOutIdx] = notarizationOut; | |
1512 | ||
1513 | // now that the coinbase is finished, finish and place conversion transaction before the stake transaction | |
1514 | newNotarizationTx.vin.push_back(CTxIn(uint256(), cbOutIdx)); | |
1515 | ||
1516 | cbOutIdx++; | |
1517 | ||
1518 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; | |
ebee7b5b | 1519 | } |
06f41160 | 1520 | |
88bc6df5 MT |
1521 | // this should be the end of the outputs |
1522 | assert(cbOutIdx == coinbaseTx.vout.size()); | |
1523 | ||
1524 | nLastBlockTx = nBlockTx; | |
1525 | nLastBlockSize = nBlockSize; | |
1526 | ||
1527 | blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime()); | |
1528 | ||
1529 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); | |
1530 | ||
41f170fd | 1531 | coinbaseTx.nExpiryHeight = 0; |
88bc6df5 | 1532 | coinbaseTx.nLockTime = blocktime; |
abb90a89 | 1533 | |
e0bc68e6 | 1534 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
41f170fd | 1535 | coinbaseTx.vout[0].nValue += 5000; |
5034d1c1 | 1536 | |
88bc6df5 | 1537 | /* |
29bd53a1 | 1538 | // check if coinbase transactions must be time locked at current subsidy and prepend the time lock |
a0dd01bc | 1539 | // to transaction if so, cast for GTE operator |
ebee7b5b | 1540 | CAmount cbValueOut = 0; |
41f170fd | 1541 | for (auto txout : coinbaseTx.vout) |
ebee7b5b MT |
1542 | { |
1543 | cbValueOut += txout.nValue; | |
1544 | } | |
1545 | if (cbValueOut >= ASSETCHAINS_TIMELOCKGTE) | |
abb90a89 MT |
1546 | { |
1547 | int32_t opretlen, p2shlen, scriptlen; | |
29bd53a1 | 1548 | CScriptExt opretScript = CScriptExt(); |
abb90a89 | 1549 | |
41f170fd | 1550 | coinbaseTx.vout.push_back(CTxOut()); |
abb90a89 | 1551 | |
29bd53a1 MT |
1552 | // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins |
1553 | // protected only by the time lock rather than 100% inaccessible | |
1554 | opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight)); | |
06f41160 | 1555 | if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition()) |
1556 | { | |
514fde1b | 1557 | LogPrintf("CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
86e31e3d | 1558 | fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n"); |
06f41160 | 1559 | return 0; |
1560 | } | |
1561 | ||
1562 | opretScript += scriptPubKeyIn; | |
abb90a89 | 1563 | |
41f170fd MT |
1564 | coinbaseTx.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript)); |
1565 | coinbaseTx.vout.back().scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK); | |
1566 | coinbaseTx.vout.back().nValue = 0; | |
48d800c2 | 1567 | } // timelocks and commissions are currently incompatible due to validation complexity of the combination |
5034d1c1 | 1568 | else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) |
c9b1071d | 1569 | { |
c000c9ca | 1570 | int32_t i; uint8_t *ptr; |
41f170fd MT |
1571 | coinbaseTx.vout.resize(2); |
1572 | coinbaseTx.vout[1].nValue = commission; | |
1573 | coinbaseTx.vout[1].scriptPubKey.resize(35); | |
1574 | ptr = (uint8_t *)&coinbaseTx.vout[1].scriptPubKey[0]; | |
c000c9ca | 1575 | ptr[0] = 33; |
1576 | for (i=0; i<33; i++) | |
1577 | ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i]; | |
1578 | ptr[34] = OP_CHECKSIG; | |
146d2aa2 | 1579 | //printf("autocreate commision vout\n"); |
c9b1071d | 1580 | } |
88bc6df5 | 1581 | */ |
48d800c2 | 1582 | |
ebee7b5b | 1583 | // finalize input of coinbase |
41f170fd MT |
1584 | coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS; |
1585 | assert(coinbaseTx.vin[0].scriptSig.size() <= 100); | |
ebee7b5b | 1586 | |
88bc6df5 MT |
1587 | // coinbase is done |
1588 | pblock->vtx[0] = coinbaseTx; | |
1589 | uint256 cbHash = coinbaseTx.GetHash(); | |
68b309c0 | 1590 | |
88bc6df5 | 1591 | // if there is a conversion, update the correct coinbase hash and add it to the block |
34d1aa13 MT |
1592 | // we also need to sign the conversion transaction |
1593 | if (newConversionOutputTx.vin.size() > 1) | |
88bc6df5 | 1594 | { |
a6b1eaf9 | 1595 | // put the coinbase into the updated coins, since we will spend from it |
1596 | UpdateCoins(pblock->vtx[0], view, nHeight); | |
1597 | ||
88bc6df5 | 1598 | newConversionOutputTx.vin[0].prevout.hash = cbHash; |
0574c740 | 1599 | |
1600 | CTransaction ncoTx(newConversionOutputTx); | |
1601 | ||
1602 | // sign transaction for cb output and conversions | |
1603 | for (int i = 0; i < ncoTx.vin.size(); i++) | |
1604 | { | |
1605 | bool signSuccess; | |
1606 | SignatureData sigdata; | |
1607 | CAmount value; | |
1608 | const CScript *pScriptPubKey; | |
1609 | ||
0574c740 | 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); | |
93440330 | 1641 | pblocktemplate->vTxFees.push_back(0); |
88bc6df5 MT |
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 | |
13ed2980 MT |
1680 | // if this is our coinbase input, we won't find it elsewhere |
1681 | if (i < notarizationInputs.size()) | |
eb0a6550 | 1682 | { |
13ed2980 MT |
1683 | pScriptPubKey = ¬arizationInputs[i].scriptPubKey; |
1684 | value = notarizationInputs[i].nValue; | |
eb0a6550 | 1685 | } |
1686 | else | |
1687 | { | |
41f170fd MT |
1688 | pScriptPubKey = &coinbaseTx.vout[ntx.vin[i].prevout.n].scriptPubKey; |
1689 | value = coinbaseTx.vout[ntx.vin[i].prevout.n].nValue; | |
eb0a6550 | 1690 | } |
8577896f | 1691 | |
eb0a6550 | 1692 | signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId); |
68b309c0 MT |
1693 | |
1694 | if (!signSuccess) | |
1695 | { | |
41f170fd | 1696 | if (ntx.vin[i].prevout.hash == coinbaseTx.GetHash()) |
4edfdbb0 | 1697 | { |
41f170fd MT |
1698 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1699 | 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 |
1700 | } |
1701 | 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()); | |
1702 | 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 |
1703 | return NULL; |
1704 | } else { | |
88bc6df5 | 1705 | UpdateTransaction(newNotarizationTx, i, sigdata); |
68b309c0 MT |
1706 | } |
1707 | } | |
88bc6df5 | 1708 | pblocktemplate->vTxSigOps[notarizationTxIndex] = GetLegacySigOpCount(newNotarizationTx); |
13ed2980 MT |
1709 | |
1710 | // put now signed notarization back in the block | |
88bc6df5 | 1711 | pblock->vtx[notarizationTxIndex] = newNotarizationTx; |
f3be524a | 1712 | |
41f170fd MT |
1713 | LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); |
1714 | //printf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str()); | |
88bc6df5 | 1715 | LogPrintf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, newNotarizationTx.GetHash().GetHex().c_str()); |
989b1de1 | 1716 | //printf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, mntx.GetHash().GetHex().c_str()); |
f3be524a MT |
1717 | { |
1718 | LOCK(cs_main); | |
88bc6df5 | 1719 | for (auto input : newNotarizationTx.vin) |
f3be524a | 1720 | { |
1026ac58 | 1721 | 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 | 1722 | //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 |
1723 | } |
1724 | } | |
68b309c0 MT |
1725 | } |
1726 | ||
41f170fd | 1727 | pblock->vtx[0] = coinbaseTx; |
d247a5d1 | 1728 | pblocktemplate->vTxFees[0] = -nFees; |
88bc6df5 | 1729 | pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); |
48d800c2 | 1730 | |
1fae37f6 MT |
1731 | // if not Verus stake, setup nonce, otherwise, leave it alone |
1732 | if (!isStake || ASSETCHAINS_LWMAPOS == 0) | |
1733 | { | |
eb0a6550 | 1734 | // Randomize nonce |
1fae37f6 | 1735 | arith_uint256 nonce = UintToArith256(GetRandHash()); |
48d800c2 | 1736 | |
1fae37f6 MT |
1737 | // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters) |
1738 | nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO]; | |
1739 | nonce >>= 16; | |
1740 | pblock->nNonce = ArithToUint256(nonce); | |
1741 | } | |
e9e70b95 | 1742 | |
d247a5d1 JG |
1743 | // Fill in header |
1744 | pblock->hashPrevBlock = pindexPrev->GetBlockHash(); | |
31a04d28 | 1745 | pblock->hashFinalSaplingRoot = sapling_tree.root(); |
0c8fa56a MT |
1746 | |
1747 | // all Verus PoS chains need this data in the block at all times | |
1748 | if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 ) | |
9a0f2798 | 1749 | { |
1750 | UpdateTime(pblock, Params().GetConsensus(), pindexPrev); | |
1fae37f6 | 1751 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
9a0f2798 | 1752 | } |
12217420 | 1753 | |
4d068367 | 1754 | if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 ) |
af805d53 | 1755 | { |
28a62b60 | 1756 | uint32_t r; |
496f1fd2 | 1757 | CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1); |
fa04bcf3 | 1758 | if ( pblock->nTime < pindexPrev->nTime+60 ) |
1759 | pblock->nTime = pindexPrev->nTime + 60; | |
16593898 | 1760 | if ( gpucount < 33 ) |
28a62b60 | 1761 | { |
55566f16 | 1762 | uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals; |
28a62b60 | 1763 | memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid); |
1764 | memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height); | |
1765 | memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock); | |
9a146fef | 1766 | vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n); |
55566f16 | 1767 | memcpy(&r,&randvals,sizeof(r)); |
1768 | pblock->nTime += (r % (33 - gpucount)*(33 - gpucount)); | |
28a62b60 | 1769 | } |
a893e994 | 1770 | if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 ) |
496f1fd2 | 1771 | { |
2d79309f | 1772 | CAmount txfees = 5000; |
496f1fd2 | 1773 | pblock->vtx.push_back(txNotary); |
1774 | pblocktemplate->vTxFees.push_back(txfees); | |
1775 | pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary)); | |
1776 | nFees += txfees; | |
2d79309f | 1777 | pblocktemplate->vTxFees[0] = -nFees; |
c881e52b | 1778 | //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees; |
f31815fc | 1779 | //fprintf(stderr,"added notaryvin\n"); |
0857c3d5 | 1780 | } |
1781 | else | |
1782 | { | |
1783 | fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n"); | |
1784 | return(0); | |
1785 | } | |
707b061c | 1786 | } |
809f2e25 | 1787 | else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) ) |
af805d53 | 1788 | { |
8fc79ac9 | 1789 | CValidationState state; |
809f2e25 | 1790 | //fprintf(stderr,"check validity\n"); |
1791 | if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) // invokes CC checks | |
8fc79ac9 | 1792 | { |
9feb4b9e | 1793 | throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed"); |
8fc79ac9 | 1794 | } |
809f2e25 | 1795 | //fprintf(stderr,"valid\n"); |
af805d53 | 1796 | } |
d247a5d1 | 1797 | } |
2a6a442a | 1798 | //fprintf(stderr,"done new block\n"); |
1685bba0 MT |
1799 | |
1800 | // setup the header and buid the Merkle tree | |
1801 | unsigned int extraNonce; | |
1802 | IncrementExtraNonce(pblock, pindexPrev, extraNonce); | |
1803 | ||
d247a5d1 JG |
1804 | return pblocktemplate.release(); |
1805 | } | |
32b915c9 | 1806 | |
1a31463b | 1807 | /* |
e9e70b95 | 1808 | #ifdef ENABLE_WALLET |
1809 | boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey) | |
1810 | #else | |
1811 | boost::optional<CScript> GetMinerScriptPubKey() | |
1812 | #endif | |
1813 | { | |
1814 | CKeyID keyID; | |
1815 | CBitcoinAddress addr; | |
1816 | if (addr.SetString(GetArg("-mineraddress", ""))) { | |
1817 | addr.GetKeyID(keyID); | |
1818 | } else { | |
1819 | #ifdef ENABLE_WALLET | |
1820 | CPubKey pubkey; | |
1821 | if (!reservekey.GetReservedKey(pubkey)) { | |
1822 | return boost::optional<CScript>(); | |
1823 | } | |
1824 | keyID = pubkey.GetID(); | |
1825 | #else | |
1826 | return boost::optional<CScript>(); | |
1827 | #endif | |
1828 | } | |
1829 | ||
1830 | CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; | |
1831 | return scriptPubKey; | |
1832 | } | |
1833 | ||
1834 | #ifdef ENABLE_WALLET | |
1835 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) | |
1836 | { | |
1837 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey); | |
1838 | #else | |
1839 | CBlockTemplate* CreateNewBlockWithKey() | |
1840 | { | |
1841 | boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(); | |
1842 | #endif | |
1843 | ||
1844 | if (!scriptPubKey) { | |
1845 | return NULL; | |
1846 | } | |
1847 | return CreateNewBlock(*scriptPubKey); | |
1848 | }*/ | |
acfa0333 | 1849 | |
c1de826f JG |
1850 | ////////////////////////////////////////////////////////////////////////////// |
1851 | // | |
1852 | // Internal miner | |
1853 | // | |
1854 | ||
2cc0a252 | 1855 | #ifdef ENABLE_MINING |
c1de826f | 1856 | |
4a85e067 | 1857 | #ifdef ENABLE_WALLET |
acfa0333 WL |
1858 | ////////////////////////////////////////////////////////////////////////////// |
1859 | // | |
1860 | // Internal miner | |
1861 | // | |
acfa0333 | 1862 | |
5034d1c1 | 1863 | CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake) |
acfa0333 | 1864 | { |
9feb4b9e | 1865 | CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i; |
d9f176ac | 1866 | if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 ) |
1867 | { | |
1868 | scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG; | |
1869 | } | |
1870 | else if ( USE_EXTERNAL_PUBKEY != 0 ) | |
998397aa | 1871 | { |
7bfc207a | 1872 | //fprintf(stderr,"use notary pubkey\n"); |
c95fd5e0 | 1873 | scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG; |
f6c647ed | 1874 | } |
1875 | else | |
1876 | { | |
f1f6dfbb | 1877 | if (!isStake) |
1b5b89ba | 1878 | { |
f1f6dfbb | 1879 | if (!reservekey.GetReservedKey(pubkey)) |
1880 | { | |
1881 | return NULL; | |
1882 | } | |
1883 | scriptPubKey.resize(35); | |
1884 | ptr = (uint8_t *)pubkey.begin(); | |
1885 | scriptPubKey[0] = 33; | |
1886 | for (i=0; i<33; i++) | |
1887 | scriptPubKey[i+1] = ptr[i]; | |
1888 | scriptPubKey[34] = OP_CHECKSIG; | |
1889 | //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG; | |
1b5b89ba | 1890 | } |
f6c647ed | 1891 | } |
5034d1c1 | 1892 | return CreateNewBlock(scriptPubKey, gpucount, isStake); |
acfa0333 WL |
1893 | } |
1894 | ||
395f10cf | 1895 | void komodo_broadcast(CBlock *pblock,int32_t limit) |
1896 | { | |
1897 | int32_t n = 1; | |
1898 | //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1899 | { | |
1900 | LOCK(cs_vNodes); | |
1901 | BOOST_FOREACH(CNode* pnode, vNodes) | |
1902 | { | |
1903 | if ( pnode->hSocket == INVALID_SOCKET ) | |
1904 | continue; | |
1905 | if ( (rand() % n) == 0 ) | |
1906 | { | |
1907 | pnode->PushMessage("block", *pblock); | |
1908 | if ( n++ > limit ) | |
1909 | break; | |
1910 | } | |
1911 | } | |
1912 | } | |
1913 | //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); | |
1914 | } | |
945f015d | 1915 | |
269d8ba0 | 1916 | static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) |
8e8b6d70 JG |
1917 | #else |
1918 | static bool ProcessBlockFound(CBlock* pblock) | |
1919 | #endif // ENABLE_WALLET | |
d247a5d1 | 1920 | { |
572c763f | 1921 | int32_t height = chainActive.LastTip()->GetHeight()+1; |
81212588 | 1922 | LogPrintf("%s\n", pblock->ToString()); |
572c763f | 1923 | LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue), height); |
e9e70b95 | 1924 | |
d247a5d1 JG |
1925 | // Found a solution |
1926 | { | |
86131275 | 1927 | if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash()) |
ba8419c7 | 1928 | { |
1929 | uint256 hash; int32_t i; | |
1930 | hash = pblock->hashPrevBlock; | |
92266e99 | 1931 | for (i=31; i>=0; i--) |
ba8419c7 | 1932 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 1933 | fprintf(stderr," <- prev (stale)\n"); |
86131275 | 1934 | hash = chainActive.LastTip()->GetBlockHash(); |
92266e99 | 1935 | for (i=31; i>=0; i--) |
ba8419c7 | 1936 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); |
c0dbb034 | 1937 | fprintf(stderr," <- chainTip (stale)\n"); |
e9e70b95 | 1938 | |
ffde1589 | 1939 | return error("VerusMiner: generated block is stale"); |
ba8419c7 | 1940 | } |
18e72167 | 1941 | } |
e9e70b95 | 1942 | |
8e8b6d70 | 1943 | #ifdef ENABLE_WALLET |
18e72167 | 1944 | // Remove key from key pool |
998397aa | 1945 | if ( IS_KOMODO_NOTARY == 0 ) |
945f015d | 1946 | { |
1947 | if (GetArg("-mineraddress", "").empty()) { | |
1948 | // Remove key from key pool | |
1949 | reservekey.KeepKey(); | |
1950 | } | |
8e8b6d70 | 1951 | } |
18e72167 | 1952 | // Track how many getdata requests this block gets |
438ba9c1 | 1953 | //if ( 0 ) |
18e72167 | 1954 | { |
d1bc3a75 | 1955 | //fprintf(stderr,"lock cs_wallet\n"); |
18e72167 PW |
1956 | LOCK(wallet.cs_wallet); |
1957 | wallet.mapRequestCount[pblock->GetHash()] = 0; | |
d247a5d1 | 1958 | } |
8e8b6d70 | 1959 | #endif |
d1bc3a75 | 1960 | //fprintf(stderr,"process new block\n"); |
194ad5b8 | 1961 | |
18e72167 PW |
1962 | // Process this block the same as if we had received it from another node |
1963 | CValidationState state; | |
4b729ec5 | 1964 | if (!ProcessNewBlock(1,chainActive.LastTip()->GetHeight()+1,state, NULL, pblock, true, NULL)) |
ffde1589 | 1965 | return error("VerusMiner: ProcessNewBlock, block not accepted"); |
e9e70b95 | 1966 | |
d793f94b | 1967 | TrackMinedBlock(pblock->GetHash()); |
395f10cf | 1968 | komodo_broadcast(pblock,16); |
d247a5d1 JG |
1969 | return true; |
1970 | } | |
1971 | ||
078f6af1 | 1972 | int32_t komodo_baseid(char *origbase); |
a30dd993 | 1973 | int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); |
13691369 | 1974 | arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); |
8ee93080 | 1975 | int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; |
99ba67a0 | 1976 | extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC; |
8b51b9e4 | 1977 | int32_t roundrobin_delay; |
18443f69 | 1978 | arith_uint256 HASHTarget,HASHTarget_POW; |
3363d1c0 | 1979 | int32_t komodo_longestchain(); |
078f6af1 | 1980 | |
5642c96c | 1981 | // wait for peers to connect |
12217420 | 1982 | void waitForPeers(const CChainParams &chainparams) |
5642c96c | 1983 | { |
1984 | if (chainparams.MiningRequiresPeers()) | |
1985 | { | |
3da69a31 MT |
1986 | bool fvNodesEmpty; |
1987 | { | |
00a7120e | 1988 | boost::this_thread::interruption_point(); |
3da69a31 MT |
1989 | LOCK(cs_vNodes); |
1990 | fvNodesEmpty = vNodes.empty(); | |
1991 | } | |
3363d1c0 | 1992 | int longestchain = komodo_longestchain(); |
1993 | int lastlongest = 0; | |
1994 | if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight())) | |
3da69a31 | 1995 | { |
af2e212d | 1996 | int loops = 0, blockDiff = 0, newDiff = 0; |
1997 | ||
3da69a31 | 1998 | do { |
64d6048f | 1999 | if (fvNodesEmpty) |
3da69a31 | 2000 | { |
69fa3d0e | 2001 | MilliSleep(1000 + rand() % 4000); |
00a7120e | 2002 | boost::this_thread::interruption_point(); |
3da69a31 MT |
2003 | LOCK(cs_vNodes); |
2004 | fvNodesEmpty = vNodes.empty(); | |
af2e212d | 2005 | loops = 0; |
2006 | blockDiff = 0; | |
3363d1c0 | 2007 | lastlongest = 0; |
af2e212d | 2008 | } |
3363d1c0 | 2009 | else if ((newDiff = IsNotInSync()) > 0) |
af2e212d | 2010 | { |
2011 | if (blockDiff != newDiff) | |
2012 | { | |
2013 | blockDiff = newDiff; | |
2014 | } | |
2015 | else | |
2016 | { | |
3363d1c0 | 2017 | if (++loops <= 5) |
af2e212d | 2018 | { |
2019 | MilliSleep(1000); | |
2020 | } | |
2021 | else break; | |
2022 | } | |
3363d1c0 | 2023 | lastlongest = 0; |
2024 | } | |
2025 | else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight()) | |
2026 | { | |
2027 | // the only thing may be that we are seeing a long chain that we'll never get | |
2028 | // don't wait forever | |
2029 | if (lastlongest == 0) | |
2030 | { | |
2031 | MilliSleep(3000); | |
2032 | lastlongest = longestchain; | |
2033 | } | |
3da69a31 | 2034 | } |
af2e212d | 2035 | } while (fvNodesEmpty || IsNotInSync()); |
0ba20651 | 2036 | MilliSleep(100 + rand() % 400); |
3da69a31 | 2037 | } |
5642c96c | 2038 | } |
2039 | } | |
2040 | ||
42181656 | 2041 | #ifdef ENABLE_WALLET |
d7e6718d MT |
2042 | CBlockIndex *get_chainactive(int32_t height) |
2043 | { | |
3c40a9a6 | 2044 | if ( chainActive.LastTip() != 0 ) |
d7e6718d | 2045 | { |
4b729ec5 | 2046 | if ( height <= chainActive.LastTip()->GetHeight() ) |
3c40a9a6 MT |
2047 | { |
2048 | LOCK(cs_main); | |
d7e6718d | 2049 | return(chainActive[height]); |
3c40a9a6 | 2050 | } |
4b729ec5 | 2051 | // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight()); |
d7e6718d MT |
2052 | } |
2053 | //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height); | |
2054 | return(0); | |
2055 | } | |
2056 | ||
135fa24e | 2057 | /* |
2058 | * A separate thread to stake, while the miner threads mine. | |
2059 | */ | |
2060 | void static VerusStaker(CWallet *pwallet) | |
2061 | { | |
2062 | LogPrintf("Verus staker thread started\n"); | |
2063 | RenameThread("verus-staker"); | |
2064 | ||
2065 | const CChainParams& chainparams = Params(); | |
2d02c19e | 2066 | auto consensusParams = chainparams.GetConsensus(); |
135fa24e | 2067 | |
2068 | // Each thread has its own key | |
2069 | CReserveKey reservekey(pwallet); | |
2070 | ||
2071 | // Each thread has its own counter | |
2072 | unsigned int nExtraNonce = 0; | |
12217420 | 2073 | |
135fa24e | 2074 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2075 | ||
4b729ec5 | 2076 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
135fa24e | 2077 | { |
2078 | sleep(1); | |
2079 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2080 | break; | |
2081 | } | |
2082 | ||
2083 | // try a nice clean peer connection to start | |
bf9c36f4 MT |
2084 | CBlockIndex *pindexPrev, *pindexCur; |
2085 | do { | |
2086 | pindexPrev = chainActive.LastTip(); | |
2087 | MilliSleep(5000 + rand() % 5000); | |
2088 | waitForPeers(chainparams); | |
2089 | pindexCur = chainActive.LastTip(); | |
2090 | } while (pindexPrev != pindexCur); | |
c132b91a | 2091 | |
135fa24e | 2092 | try { |
0fc0dc56 | 2093 | static int32_t lastStakingHeight = 0; |
2094 | ||
135fa24e | 2095 | while (true) |
2096 | { | |
135fa24e | 2097 | waitForPeers(chainparams); |
4ca6678c | 2098 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
135fa24e | 2099 | |
2100 | // Create new block | |
2101 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
0fc0dc56 | 2102 | |
4b729ec5 | 2103 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
135fa24e | 2104 | { |
4b729ec5 | 2105 | Mining_height = pindexPrev->GetHeight()+1; |
135fa24e | 2106 | Mining_start = (uint32_t)time(NULL); |
2107 | } | |
2108 | ||
1fae37f6 MT |
2109 | // Check for stop or if block needs to be rebuilt |
2110 | boost::this_thread::interruption_point(); | |
2111 | ||
135fa24e | 2112 | // try to stake a block |
1fae37f6 MT |
2113 | CBlockTemplate *ptr = NULL; |
2114 | if (Mining_height > VERUS_MIN_STAKEAGE) | |
5034d1c1 | 2115 | ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0, true); |
135fa24e | 2116 | |
a73ab4b4 | 2117 | // TODO - putting this output here tends to help mitigate announcing a staking height earlier than |
2118 | // announcing the last block win when we start staking before a block's acceptance has been | |
2119 | // acknowledged by the mining thread - a better solution may be to put the output on the submission | |
2120 | // thread. | |
2121 | if ( ptr == 0 && Mining_height != lastStakingHeight ) | |
2122 | { | |
2123 | printf("Staking height %d for %s\n", Mining_height, ASSETCHAINS_SYMBOL); | |
2124 | } | |
2125 | lastStakingHeight = Mining_height; | |
2126 | ||
135fa24e | 2127 | if ( ptr == 0 ) |
2128 | { | |
1fae37f6 | 2129 | // wait to try another staking block until after the tip moves again |
37ad6886 | 2130 | while ( chainActive.LastTip() == pindexPrev ) |
bab13dd2 | 2131 | MilliSleep(250); |
135fa24e | 2132 | continue; |
2133 | } | |
2134 | ||
2135 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); | |
2136 | if (!pblocktemplate.get()) | |
2137 | { | |
2138 | if (GetArg("-mineraddress", "").empty()) { | |
1fae37f6 | 2139 | LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
135fa24e | 2140 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2141 | } else { | |
2142 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
1fae37f6 | 2143 | LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
135fa24e | 2144 | } |
2145 | return; | |
2146 | } | |
2147 | ||
2148 | CBlock *pblock = &pblocktemplate->block; | |
1fae37f6 | 2149 | LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); |
135fa24e | 2150 | // |
2151 | // Search | |
2152 | // | |
1fae37f6 MT |
2153 | int64_t nStart = GetTime(); |
2154 | ||
1fae37f6 MT |
2155 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) |
2156 | { | |
2157 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2158 | { | |
2159 | fprintf(stderr,"no nodes, attempting reconnect\n"); | |
2160 | continue; | |
2161 | } | |
2162 | } | |
2163 | ||
2164 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) | |
2165 | { | |
2166 | fprintf(stderr,"timeout, retrying\n"); | |
2167 | continue; | |
2168 | } | |
135fa24e | 2169 | |
37ad6886 | 2170 | if ( pindexPrev != chainActive.LastTip() ) |
135fa24e | 2171 | { |
4b729ec5 | 2172 | printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight()); |
135fa24e | 2173 | MilliSleep(250); |
2174 | continue; | |
2175 | } | |
2176 | ||
1fae37f6 MT |
2177 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); |
2178 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); | |
135fa24e | 2179 | |
1fae37f6 | 2180 | uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits)); |
135fa24e | 2181 | |
df756d24 | 2182 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); |
b9956efc | 2183 | |
df756d24 | 2184 | UpdateTime(pblock, consensusParams, pindexPrev); |
b9956efc | 2185 | |
ed47e5ec MT |
2186 | if (ProcessBlockFound(pblock, *pwallet, reservekey)) |
2187 | { | |
2188 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
2189 | LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex()); | |
2190 | printf("Found block %d \n", Mining_height ); | |
2191 | printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
2192 | arith_uint256 post; | |
2193 | post.SetCompact(pblock->GetVerusPOSTarget()); | |
2194 | pindexPrev = get_chainactive(Mining_height - 100); | |
2195 | CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1]; | |
2196 | printf("POS hash: %s \ntarget: %s\n", | |
2197 | 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()); | |
2198 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) | |
2199 | printf("- timelocked until block %i\n", unlockTime); | |
2200 | else | |
2201 | printf("\n"); | |
2202 | } | |
1fae37f6 | 2203 | else |
ed47e5ec MT |
2204 | { |
2205 | LogPrintf("Found block rejected at staking height: %d\n", Mining_height); | |
2206 | printf("Found block rejected at staking height: %d\n", Mining_height); | |
2207 | } | |
135fa24e | 2208 | |
1fae37f6 MT |
2209 | // Check for stop or if block needs to be rebuilt |
2210 | boost::this_thread::interruption_point(); | |
135fa24e | 2211 | |
bf9c36f4 | 2212 | sleep(3); |
3da69a31 | 2213 | |
1fae37f6 MT |
2214 | // In regression test mode, stop mining after a block is found. |
2215 | if (chainparams.MineBlocksOnDemand()) { | |
2216 | throw boost::thread_interrupted(); | |
135fa24e | 2217 | } |
2218 | } | |
2219 | } | |
2220 | catch (const boost::thread_interrupted&) | |
2221 | { | |
135fa24e | 2222 | LogPrintf("VerusStaker terminated\n"); |
2223 | throw; | |
2224 | } | |
2225 | catch (const std::runtime_error &e) | |
2226 | { | |
135fa24e | 2227 | LogPrintf("VerusStaker runtime error: %s\n", e.what()); |
2228 | return; | |
2229 | } | |
135fa24e | 2230 | } |
2231 | ||
fa7fdbc6 | 2232 | typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); |
2233 | bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
2234 | bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count); | |
2235 | ||
42181656 | 2236 | void static BitcoinMiner_noeq(CWallet *pwallet) |
2237 | #else | |
2238 | void static BitcoinMiner_noeq() | |
2239 | #endif | |
2240 | { | |
05f6e633 | 2241 | LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
05f6e633 | 2242 | RenameThread("verushash-miner"); |
42181656 | 2243 | |
2244 | #ifdef ENABLE_WALLET | |
2245 | // Each thread has its own key | |
2246 | CReserveKey reservekey(pwallet); | |
2247 | #endif | |
2248 | ||
2910478b | 2249 | const CChainParams& chainparams = Params(); |
42181656 | 2250 | // Each thread has its own counter |
2251 | unsigned int nExtraNonce = 0; | |
12217420 | 2252 | |
42181656 | 2253 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j; |
2254 | ||
4b729ec5 | 2255 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 && |
42181656 | 2256 | { |
2257 | sleep(1); | |
2258 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) | |
2259 | break; | |
2260 | } | |
9f3e2213 | 2261 | |
3da69a31 MT |
2262 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2263 | ||
5642c96c | 2264 | // try a nice clean peer connection to start |
c132b91a | 2265 | CBlockIndex *pindexPrev, *pindexCur; |
9f3e2213 | 2266 | do { |
37ad6886 | 2267 | pindexPrev = chainActive.LastTip(); |
3da69a31 | 2268 | MilliSleep(5000 + rand() % 5000); |
bf9c36f4 | 2269 | waitForPeers(chainparams); |
37ad6886 | 2270 | pindexCur = chainActive.LastTip(); |
c132b91a | 2271 | } while (pindexPrev != pindexCur); |
6176a421 | 2272 | |
a9f18272 | 2273 | // make sure that we have checked for PBaaS availability |
2274 | ConnectedChains.CheckVerusPBaaSAvailable(); | |
2275 | ||
dbe656fe MT |
2276 | // this will not stop printing more than once in all cases, but it will allow us to print in all cases |
2277 | // and print duplicates rarely without having to synchronize | |
2278 | static CBlockIndex *lastChainTipPrinted; | |
90198f71 | 2279 | static int32_t lastMiningHeight = 0; |
9f3e2213 | 2280 | |
42181656 | 2281 | miningTimer.start(); |
2282 | ||
2283 | try { | |
dbe656fe | 2284 | printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
08d46b7f | 2285 | |
08d46b7f | 2286 | // v2 hash writer |
2287 | CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION); | |
2288 | ||
42181656 | 2289 | while (true) |
2290 | { | |
68334c8d | 2291 | miningTimer.stop(); |
2292 | waitForPeers(chainparams); | |
dfcf8255 | 2293 | |
37ad6886 | 2294 | pindexPrev = chainActive.LastTip(); |
dfcf8255 | 2295 | |
f8f61a6d | 2296 | // prevent forking on startup before the diff algorithm kicks in, |
2297 | // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from | |
2298 | // their parent | |
57055854 | 2299 | if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip())) |
dfcf8255 MT |
2300 | { |
2301 | do { | |
37ad6886 | 2302 | pindexPrev = chainActive.LastTip(); |
2830db29 | 2303 | MilliSleep(2000 + rand() % 2000); |
37ad6886 | 2304 | } while (pindexPrev != chainActive.LastTip()); |
dfcf8255 | 2305 | } |
42181656 | 2306 | |
2307 | // Create new block | |
2308 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
4b729ec5 | 2309 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
42181656 | 2310 | { |
4b729ec5 | 2311 | Mining_height = pindexPrev->GetHeight()+1; |
90198f71 | 2312 | if (lastMiningHeight != Mining_height) |
2313 | { | |
2314 | lastMiningHeight = Mining_height; | |
dc74c06d | 2315 | printf("Mining %s at height %d\n", ASSETCHAINS_SYMBOL, Mining_height); |
90198f71 | 2316 | } |
42181656 | 2317 | Mining_start = (uint32_t)time(NULL); |
2318 | } | |
2319 | ||
dbe656fe | 2320 | miningTimer.start(); |
42181656 | 2321 | |
2322 | #ifdef ENABLE_WALLET | |
5034d1c1 | 2323 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0); |
42181656 | 2324 | #else |
2325 | CBlockTemplate *ptr = CreateNewBlockWithKey(); | |
2326 | #endif | |
2327 | if ( ptr == 0 ) | |
2328 | { | |
2329 | static uint32_t counter; | |
f6084562 MT |
2330 | if ( counter++ % 40 == 0 ) |
2331 | { | |
2332 | if (!IsVerusActive() && | |
2333 | ConnectedChains.IsVerusPBaaSAvailable() && | |
2334 | ConnectedChains.notaryChainHeight < ConnectedChains.ThisChain().startBlock) | |
2335 | { | |
2336 | fprintf(stderr,"Waiting for block %d on %s chain to start. Current block is %d\n", ConnectedChains.ThisChain().startBlock, | |
2337 | ConnectedChains.notaryChain.chainDefinition.name.c_str(), | |
2338 | ConnectedChains.notaryChainHeight); | |
2339 | } | |
2340 | else | |
2341 | { | |
2342 | fprintf(stderr,"Unable to create valid block... will continue to try\n"); | |
2343 | } | |
2344 | } | |
2830db29 | 2345 | MilliSleep(2000); |
42181656 | 2346 | continue; |
2347 | } | |
dbe656fe | 2348 | |
42181656 | 2349 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
2350 | if (!pblocktemplate.get()) | |
2351 | { | |
2352 | if (GetArg("-mineraddress", "").empty()) { | |
05f6e633 | 2353 | LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n", |
2354 | ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); | |
42181656 | 2355 | } else { |
2356 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
05f6e633 | 2357 | LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL); |
42181656 | 2358 | } |
2359 | return; | |
2360 | } | |
2361 | CBlock *pblock = &pblocktemplate->block; | |
f8f61a6d | 2362 | |
2363 | uint32_t savebits; | |
2364 | bool mergeMining = false; | |
2365 | savebits = pblock->nBits; | |
2366 | ||
2367 | bool verusHashV2 = pblock->nVersion == CBlockHeader::VERUS_V2; | |
2368 | bool verusSolutionV3 = CConstVerusSolutionVector::Version(pblock->nSolution) == CActivationHeight::SOLUTION_VERUSV3; | |
2369 | ||
42181656 | 2370 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2371 | { | |
2372 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) | |
2373 | { | |
2374 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2375 | { | |
2376 | static uint32_t counter; | |
2377 | if ( counter++ < 10 ) | |
2378 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2379 | sleep(10); | |
2380 | continue; | |
2381 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2382 | } | |
2383 | } | |
b2a98c42 | 2384 | |
1685bba0 MT |
2385 | // this builds the Merkle tree and sets our easiest target |
2386 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, false, &savebits); | |
b2a98c42 MT |
2387 | |
2388 | // update PBaaS header | |
f8f61a6d | 2389 | if (verusSolutionV3) |
b2a98c42 | 2390 | { |
2fd1f0fb | 2391 | if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable()) |
f8f61a6d | 2392 | { |
b2a98c42 | 2393 | |
2fd1f0fb | 2394 | UniValue params(UniValue::VARR); |
2395 | UniValue error(UniValue::VARR); | |
2396 | params.push_back(EncodeHexBlk(*pblock)); | |
2397 | params.push_back(ASSETCHAINS_SYMBOL); | |
2398 | params.push_back(ASSETCHAINS_RPCHOST); | |
2399 | params.push_back(ASSETCHAINS_RPCPORT); | |
2400 | params.push_back(ASSETCHAINS_RPCCREDENTIALS); | |
2401 | try | |
b2a98c42 | 2402 | { |
be17c611 | 2403 | ConnectedChains.lastSubmissionFailed = false; |
2fd1f0fb | 2404 | params = RPCCallRoot("addmergedblock", params); |
2405 | params = find_value(params, "result"); | |
2406 | error = find_value(params, "error"); | |
2407 | } catch (std::exception e) | |
2408 | { | |
2409 | printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
2410 | params = UniValue(e.what()); | |
b2a98c42 | 2411 | } |
2fd1f0fb | 2412 | if (mergeMining = (params.isNull() && error.isNull())) |
f8f61a6d | 2413 | { |
a1d91f89 | 2414 | printf("Merge mining %s with %s as the hashing chain\n", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str()); |
2415 | LogPrintf("Merge mining with %s as the hashing chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str()); | |
f8f61a6d | 2416 | } |
b2a98c42 MT |
2417 | } |
2418 | } | |
2419 | ||
42181656 | 2420 | LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], |
2421 | pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION)); | |
2422 | // | |
2423 | // Search | |
2424 | // | |
f8f61a6d | 2425 | int64_t nStart = GetTime(); |
42181656 | 2426 | |
f8f61a6d | 2427 | arith_uint256 hashTarget = arith_uint256().SetCompact(savebits); |
fa7fdbc6 | 2428 | uint256 uintTarget = ArithToUint256(hashTarget); |
f8f61a6d | 2429 | arith_uint256 ourTarget; |
2430 | ourTarget.SetCompact(pblock->nBits); | |
2431 | ||
42181656 | 2432 | Mining_start = 0; |
ef70c5b2 | 2433 | |
37ad6886 | 2434 | if ( pindexPrev != chainActive.LastTip() ) |
05f6e633 | 2435 | { |
37ad6886 | 2436 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2437 | { |
37ad6886 | 2438 | lastChainTipPrinted = chainActive.LastTip(); |
4b729ec5 | 2439 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2440 | } |
f8f61a6d | 2441 | MilliSleep(100); |
05f6e633 | 2442 | continue; |
2443 | } | |
ef70c5b2 | 2444 | |
135fa24e | 2445 | if ( ASSETCHAINS_STAKED != 0 ) |
2446 | { | |
2447 | int32_t percPoS,z; | |
2448 | hashTarget = komodo_PoWtarget(&percPoS,hashTarget,Mining_height,ASSETCHAINS_STAKED); | |
2449 | for (z=31; z>=0; z--) | |
2450 | fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); | |
2451 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2452 | } | |
2453 | ||
2830db29 | 2454 | uint64_t count; |
2455 | uint64_t hashesToGo = 0; | |
2456 | uint64_t totalDone = 0; | |
2457 | ||
fa7fdbc6 | 2458 | if (!verusHashV2) |
458bfcab | 2459 | { |
fa7fdbc6 | 2460 | // must not be in sync |
2461 | printf("Mining on incorrect block version.\n"); | |
2462 | sleep(2); | |
2463 | continue; | |
458bfcab | 2464 | } |
2465 | ||
e29b5dd5 | 2466 | int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue); |
fa7fdbc6 | 2467 | count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; |
db027133 | 2468 | CVerusHashV2 *vh2 = &ss2.GetState(); |
3b500530 | 2469 | u128 *hashKey; |
2470 | verusclhasher &vclh = vh2->vclh; | |
fa7fdbc6 | 2471 | minefunction mine_verus; |
2472 | mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port; | |
f21fad6a | 2473 | |
42181656 | 2474 | while (true) |
2475 | { | |
4dcb64c0 | 2476 | uint256 hashResult = uint256(); |
458bfcab | 2477 | |
e5fb645e | 2478 | unsigned char *curBuf; |
2479 | ||
f8f61a6d | 2480 | if (mergeMining) |
42181656 | 2481 | { |
c89d86ee | 2482 | // loop for a few minutes before refreshing the block |
e771a884 | 2483 | while (true) |
12217420 | 2484 | { |
93ff475b | 2485 | uint256 ourMerkle = pblock->hashMerkleRoot; |
a1d91f89 | 2486 | if ( pindexPrev != chainActive.LastTip() ) |
2487 | { | |
2488 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2489 | { | |
2490 | lastChainTipPrinted = chainActive.LastTip(); | |
2491 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); | |
2492 | arith_uint256 target; | |
2493 | target.SetCompact(lastChainTipPrinted->nBits); | |
93ff475b MT |
2494 | if (ourMerkle == lastChainTipPrinted->hashMerkleRoot) |
2495 | { | |
2496 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
607402ba | 2497 | printf("Found block %d \n", lastChainTipPrinted->GetHeight()); |
93ff475b MT |
2498 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); |
2499 | printf(" hash: %s\ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str()); | |
2500 | } | |
a1d91f89 | 2501 | } |
2502 | break; | |
2503 | } | |
2504 | ||
e771a884 | 2505 | // if PBaaS is no longer available, we can't count on merge mining |
2506 | if (!ConnectedChains.IsVerusPBaaSAvailable()) | |
2507 | { | |
2508 | break; | |
2509 | } | |
f8f61a6d | 2510 | |
2511 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
458bfcab | 2512 | { |
f8f61a6d | 2513 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) |
fa7fdbc6 | 2514 | { |
f8f61a6d | 2515 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
2516 | break; | |
fa7fdbc6 | 2517 | } |
f8f61a6d | 2518 | } |
2519 | ||
a82942e4 | 2520 | // update every few minutes, regardless |
2521 | int64_t elapsed = GetTime() - nStart; | |
f8f61a6d | 2522 | |
a9663647 | 2523 | if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed) |
458bfcab | 2524 | { |
f8f61a6d | 2525 | break; |
458bfcab | 2526 | } |
a1d91f89 | 2527 | |
dc74c06d | 2528 | boost::this_thread::interruption_point(); |
a1d91f89 | 2529 | MilliSleep(500); |
458bfcab | 2530 | } |
ffde1589 | 2531 | break; |
f8f61a6d | 2532 | } |
2533 | else | |
2534 | { | |
2535 | // check NONCEMASK at a time | |
2536 | for (uint64_t i = 0; i < count; i++) | |
42181656 | 2537 | { |
2fd1f0fb | 2538 | // 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 | 2539 | // merge mined block, but not our own |
f8f61a6d | 2540 | bool blockFound; |
2541 | arith_uint256 arithHash; | |
2830db29 | 2542 | totalDone = 0; |
f8f61a6d | 2543 | do |
2544 | { | |
2fd1f0fb | 2545 | // pickup/remove any new/deleted headers |
71f97948 | 2546 | if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1)) |
2fd1f0fb | 2547 | { |
71f97948 | 2548 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, false, &savebits); |
1fa4454d | 2549 | |
2fd1f0fb | 2550 | hashTarget.SetCompact(savebits); |
2551 | uintTarget = ArithToUint256(hashTarget); | |
2552 | } | |
2553 | ||
f8f61a6d | 2554 | // hashesToGo gets updated with actual number run for metrics |
2555 | hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO]; | |
2830db29 | 2556 | uint64_t start = i * hashesToGo + totalDone; |
f8f61a6d | 2557 | hashesToGo -= totalDone; |
2558 | ||
2559 | if (verusSolutionV3) | |
2560 | { | |
2561 | // mine on canonical header for merge mining | |
2562 | CPBaaSPreHeader savedHeader(*pblock); | |
da97aa5c | 2563 | |
f8f61a6d | 2564 | pblock->ClearNonCanonicalData(); |
2565 | blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo); | |
2566 | savedHeader.SetBlockData(*pblock); | |
2567 | } | |
2568 | else | |
2569 | { | |
2570 | blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo); | |
2571 | } | |
2572 | ||
2573 | arithHash = UintToArith256(hashResult); | |
249e20e4 | 2574 | totalDone += hashesToGo + 1; |
f8f61a6d | 2575 | if (blockFound && IsVerusActive()) |
2576 | { | |
2577 | ConnectedChains.QueueNewBlockHeader(*pblock); | |
2578 | if (arithHash > ourTarget) | |
2579 | { | |
2580 | // all blocks qualified with this hash will be submitted | |
2581 | // until we redo the block, we might as well not try again with anything over this hash | |
2582 | hashTarget = arithHash; | |
2583 | uintTarget = ArithToUint256(hashTarget); | |
2584 | } | |
2585 | } | |
2fd1f0fb | 2586 | } while (blockFound && arithHash > ourTarget); |
c98efb5a | 2587 | |
f8f61a6d | 2588 | if (!blockFound || arithHash > ourTarget) |
4dcb64c0 | 2589 | { |
f8f61a6d | 2590 | // Check for stop or if block needs to be rebuilt |
2591 | boost::this_thread::interruption_point(); | |
ce40cf2e | 2592 | if ( pindexPrev != chainActive.LastTip() ) |
f8f61a6d | 2593 | { |
2594 | if (lastChainTipPrinted != chainActive.LastTip()) | |
2595 | { | |
2596 | lastChainTipPrinted = chainActive.LastTip(); | |
2597 | printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight()); | |
2598 | } | |
2599 | break; | |
2600 | } | |
a1d91f89 | 2601 | else if ((i + 1) < count) |
f8f61a6d | 2602 | { |
a1d91f89 | 2603 | // if we'll not drop through, update hashcount |
f8f61a6d | 2604 | { |
2605 | LOCK(cs_metrics); | |
2830db29 | 2606 | nHashCount += totalDone; |
2607 | totalDone = 0; | |
f8f61a6d | 2608 | } |
f8f61a6d | 2609 | } |
4dcb64c0 | 2610 | } |
f8f61a6d | 2611 | else |
2612 | { | |
2613 | // Check for stop or if block needs to be rebuilt | |
2614 | boost::this_thread::interruption_point(); | |
4dcb64c0 | 2615 | |
f8f61a6d | 2616 | if (pblock->nSolution.size() != 1344) |
2617 | { | |
2618 | LogPrintf("ERROR: Block solution is not 1344 bytes as it should be"); | |
2619 | break; | |
2620 | } | |
42181656 | 2621 | |
f8f61a6d | 2622 | SetThreadPriority(THREAD_PRIORITY_NORMAL); |
2623 | ||
2624 | int32_t unlockTime = komodo_block_unlocktime(Mining_height); | |
ef70c5b2 | 2625 | |
3363d1c0 | 2626 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2627 | std::string validateStr = hashResult.GetHex(); |
2628 | std::string hashStr = pblock->GetHash().GetHex(); | |
2629 | uint256 *bhalf1 = (uint256 *)vh2->CurBuffer(); | |
2630 | uint256 *bhalf2 = bhalf1 + 1; | |
3363d1c0 | 2631 | #else |
f8f61a6d | 2632 | std::string hashStr = hashResult.GetHex(); |
3363d1c0 | 2633 | #endif |
3af22e67 | 2634 | |
f8f61a6d | 2635 | LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
2636 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex()); | |
2637 | printf("Found block %d \n", Mining_height ); | |
2638 | printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL); | |
3363d1c0 | 2639 | #ifdef VERUSHASHDEBUG |
f8f61a6d | 2640 | printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
2641 | printf("intermediate %lx\n", intermediate); | |
2642 | printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
2643 | bhalf1 = (uint256 *)verusclhasher_key.get(); | |
2644 | bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5); | |
2645 | printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str()); | |
3363d1c0 | 2646 | #else |
f8f61a6d | 2647 | printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str()); |
3363d1c0 | 2648 | #endif |
f8f61a6d | 2649 | if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE) |
2650 | printf(" - timelocked until block %i\n", unlockTime); | |
2651 | else | |
2652 | printf("\n"); | |
42181656 | 2653 | #ifdef ENABLE_WALLET |
f8f61a6d | 2654 | ProcessBlockFound(pblock, *pwallet, reservekey); |
42181656 | 2655 | #else |
f8f61a6d | 2656 | ProcessBlockFound(pblock); |
42181656 | 2657 | #endif |
f8f61a6d | 2658 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2659 | break; | |
2660 | } | |
42181656 | 2661 | } |
42181656 | 2662 | |
f8f61a6d | 2663 | { |
2664 | LOCK(cs_metrics); | |
2830db29 | 2665 | nHashCount += totalDone; |
f8f61a6d | 2666 | } |
69767347 | 2667 | } |
f8f61a6d | 2668 | |
69767347 | 2669 | |
42181656 | 2670 | // Check for stop or if block needs to be rebuilt |
2671 | boost::this_thread::interruption_point(); | |
2672 | ||
2673 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
2674 | { | |
2675 | if ( Mining_height > ASSETCHAINS_MINHEIGHT ) | |
2676 | { | |
ef70c5b2 | 2677 | fprintf(stderr,"no nodes, attempting reconnect\n"); |
42181656 | 2678 | break; |
2679 | } | |
2680 | } | |
2681 | ||
dbe656fe | 2682 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
42181656 | 2683 | { |
dbe656fe | 2684 | fprintf(stderr,"timeout, retrying\n"); |
42181656 | 2685 | break; |
2686 | } | |
2687 | ||
37ad6886 | 2688 | if ( pindexPrev != chainActive.LastTip() ) |
42181656 | 2689 | { |
37ad6886 | 2690 | if (lastChainTipPrinted != chainActive.LastTip()) |
dbe656fe | 2691 | { |
37ad6886 | 2692 | lastChainTipPrinted = chainActive.LastTip(); |
90198f71 | 2693 | printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight()); |
dbe656fe | 2694 | } |
42181656 | 2695 | break; |
2696 | } | |
2697 | ||
2830db29 | 2698 | // totalDone now has the number of hashes actually done since starting on one nonce mask worth |
ce40cf2e | 2699 | uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3; |
2830db29 | 2700 | if (!(totalDone < hashesPerNonceMask)) |
ce40cf2e | 2701 | { |
52cf66e1 | 2702 | #ifdef _WIN32 |
ce40cf2e | 2703 | printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2704 | #else |
ce40cf2e | 2705 | printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576); |
52cf66e1 | 2706 | #endif |
ce40cf2e | 2707 | } |
4dcb64c0 | 2708 | break; |
8682e17a | 2709 | |
42181656 | 2710 | } |
2711 | } | |
2712 | } | |
2713 | catch (const boost::thread_interrupted&) | |
2714 | { | |
2715 | miningTimer.stop(); | |
5034d1c1 | 2716 | LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]); |
42181656 | 2717 | throw; |
2718 | } | |
2719 | catch (const std::runtime_error &e) | |
2720 | { | |
2721 | miningTimer.stop(); | |
5034d1c1 | 2722 | LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what()); |
42181656 | 2723 | return; |
2724 | } | |
2725 | miningTimer.stop(); | |
2726 | } | |
2727 | ||
8e8b6d70 | 2728 | #ifdef ENABLE_WALLET |
d247a5d1 | 2729 | void static BitcoinMiner(CWallet *pwallet) |
8e8b6d70 JG |
2730 | #else |
2731 | void static BitcoinMiner() | |
2732 | #endif | |
d247a5d1 | 2733 | { |
2e500f50 | 2734 | LogPrintf("KomodoMiner started\n"); |
d247a5d1 | 2735 | SetThreadPriority(THREAD_PRIORITY_LOWEST); |
2e500f50 | 2736 | RenameThread("komodo-miner"); |
bebe7282 | 2737 | const CChainParams& chainparams = Params(); |
e9e70b95 | 2738 | |
8e8b6d70 JG |
2739 | #ifdef ENABLE_WALLET |
2740 | // Each thread has its own key | |
d247a5d1 | 2741 | CReserveKey reservekey(pwallet); |
8e8b6d70 | 2742 | #endif |
e9e70b95 | 2743 | |
8e8b6d70 | 2744 | // Each thread has its own counter |
d247a5d1 | 2745 | unsigned int nExtraNonce = 0; |
e9e70b95 | 2746 | |
e9574728 JG |
2747 | unsigned int n = chainparams.EquihashN(); |
2748 | unsigned int k = chainparams.EquihashK(); | |
16593898 | 2749 | uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1; |
99ba67a0 | 2750 | while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) |
755ead98 | 2751 | { |
2752 | sleep(1); | |
4e624c04 | 2753 | if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) |
2754 | break; | |
755ead98 | 2755 | } |
32b0978b | 2756 | if ( ASSETCHAINS_SYMBOL[0] == 0 ) |
4b729ec5 | 2757 | komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime()); |
28a62b60 | 2758 | if ( notaryid != My_notaryid ) |
2759 | My_notaryid = notaryid; | |
755ead98 | 2760 | std::string solver; |
e1e65cef | 2761 | //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) |
e9e70b95 | 2762 | solver = "tromp"; |
e1e65cef | 2763 | //else solver = "default"; |
5f0009b2 | 2764 | assert(solver == "tromp" || solver == "default"); |
c7aaab7a | 2765 | LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); |
9ee43671 | 2766 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
25f7ef8c | 2767 | fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str()); |
5a360a5c JG |
2768 | std::mutex m_cs; |
2769 | bool cancelSolver = false; | |
2770 | boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( | |
e9e70b95 | 2771 | [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { |
2772 | std::lock_guard<std::mutex> lock{m_cs}; | |
2773 | cancelSolver = true; | |
2774 | } | |
2775 | ); | |
07be8f7e | 2776 | miningTimer.start(); |
e9e70b95 | 2777 | |
0655fac0 | 2778 | try { |
ad84148d | 2779 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
c96df8ec | 2780 | fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); |
e725f1cb | 2781 | while (true) |
2782 | { | |
4b729ec5 | 2783 | if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 && |
e725f1cb | 2784 | { |
4b729ec5 | 2785 | //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 ) |
a96fd7b5 | 2786 | // break; |
0655fac0 PK |
2787 | // Busy-wait for the network to come online so we don't waste time mining |
2788 | // on an obsolete chain. In regtest mode we expect to fly solo. | |
07be8f7e | 2789 | miningTimer.stop(); |
bba7c249 GM |
2790 | do { |
2791 | bool fvNodesEmpty; | |
2792 | { | |
373668be | 2793 | //LOCK(cs_vNodes); |
bba7c249 GM |
2794 | fvNodesEmpty = vNodes.empty(); |
2795 | } | |
269fe243 | 2796 | if (!fvNodesEmpty )//&& !IsInitialBlockDownload()) |
bba7c249 | 2797 | break; |
6e78d3df | 2798 | MilliSleep(15000); |
ad84148d | 2799 | //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); |
e9e70b95 | 2800 | |
bba7c249 | 2801 | } while (true); |
ad84148d | 2802 | //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); |
07be8f7e | 2803 | miningTimer.start(); |
0655fac0 | 2804 | } |
0655fac0 PK |
2805 | // |
2806 | // Create new block | |
2807 | // | |
2808 | unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); | |
86131275 | 2809 | CBlockIndex* pindexPrev = chainActive.LastTip(); |
4b729ec5 | 2810 | if ( Mining_height != pindexPrev->GetHeight()+1 ) |
4940066c | 2811 | { |
4b729ec5 | 2812 | Mining_height = pindexPrev->GetHeight()+1; |
4940066c | 2813 | Mining_start = (uint32_t)time(NULL); |
2814 | } | |
8e9ef91c | 2815 | if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 ) |
2825c0b5 | 2816 | { |
40304479 | 2817 | //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height); |
5a7fd132 | 2818 | //sleep(3); |
2825c0b5 | 2819 | } |
135fa24e | 2820 | |
8e8b6d70 | 2821 | #ifdef ENABLE_WALLET |
135fa24e | 2822 | // notaries always default to staking |
4b729ec5 | 2823 | CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0); |
8e8b6d70 | 2824 | #else |
945f015d | 2825 | CBlockTemplate *ptr = CreateNewBlockWithKey(); |
8e8b6d70 | 2826 | #endif |
08d0b73c | 2827 | if ( ptr == 0 ) |
2828 | { | |
d0f7ead0 | 2829 | static uint32_t counter; |
5bb3d0fe | 2830 | if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) |
1b5b89ba | 2831 | fprintf(stderr,"created illegal block, retry\n"); |
8fc79ac9 | 2832 | sleep(1); |
d0f7ead0 | 2833 | continue; |
08d0b73c | 2834 | } |
2a6a442a | 2835 | //fprintf(stderr,"get template\n"); |
08d0b73c | 2836 | unique_ptr<CBlockTemplate> pblocktemplate(ptr); |
0655fac0 | 2837 | if (!pblocktemplate.get()) |
6c37f7fd | 2838 | { |
8e8b6d70 | 2839 | if (GetArg("-mineraddress", "").empty()) { |
945f015d | 2840 | LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); |
8e8b6d70 JG |
2841 | } else { |
2842 | // Should never reach here, because -mineraddress validity is checked in init.cpp | |
945f015d | 2843 | LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n"); |
8e8b6d70 | 2844 | } |
0655fac0 | 2845 | return; |
6c37f7fd | 2846 | } |
0655fac0 | 2847 | CBlock *pblock = &pblocktemplate->block; |
16c7bf6b | 2848 | if ( ASSETCHAINS_SYMBOL[0] != 0 ) |
2849 | { | |
42181656 | 2850 | if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) |
16c7bf6b | 2851 | { |
8683bd8d | 2852 | if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) |
2853 | { | |
2854 | static uint32_t counter; | |
2855 | if ( counter++ < 10 ) | |
2856 | fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); | |
2857 | sleep(10); | |
2858 | continue; | |
2859 | } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); | |
2860 | } | |
16c7bf6b | 2861 | } |
0655fac0 | 2862 | IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); |
2a6a442a | 2863 | //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size()); |
2e500f50 | 2864 | 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 |
2865 | // |
2866 | // Search | |
2867 | // | |
2ba9de01 | 2868 | 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 | 2869 | pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); |
404391b5 | 2870 | savebits = pblock->nBits; |
d5614a76 | 2871 | HASHTarget = arith_uint256().SetCompact(savebits); |
f0100e72 | 2872 | roundrobin_delay = ROUNDROBIN_DELAY; |
3e7e3109 | 2873 | if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 ) |
5203fc4b | 2874 | { |
fda5f849 | 2875 | j = 65; |
67df454d | 2876 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 ) |
fb6c7505 | 2877 | { |
4fff8a63 | 2878 | int32_t dispflag = 0; |
ef70c5b2 | 2879 | if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 ) |
4fff8a63 | 2880 | dispflag = 1; |
4b729ec5 | 2881 | komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight()); |
29e60e48 | 2882 | if ( nonzpkeys > 0 ) |
2883 | { | |
ccb71a6e | 2884 | for (i=0; i<33; i++) |
2885 | if( pubkeys[0][i] != 0 ) | |
2886 | break; | |
2887 | if ( i == 33 ) | |
2888 | externalflag = 1; | |
2889 | else externalflag = 0; | |
4d068367 | 2890 | if ( IS_KOMODO_NOTARY != 0 ) |
b176c125 | 2891 | { |
345e545e | 2892 | for (i=1; i<66; i++) |
2893 | if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) | |
2894 | break; | |
6494f040 | 2895 | if ( externalflag == 0 && i != 66 && mids[i] >= 0 ) |
2896 | printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]); | |
2c7ad758 | 2897 | for (j=gpucount=0; j<65; j++) |
2898 | { | |
4fff8a63 | 2899 | if ( dispflag != 0 ) |
e4a383e3 | 2900 | { |
2901 | if ( mids[j] >= 0 ) | |
2902 | fprintf(stderr,"%d ",mids[j]); | |
2903 | else fprintf(stderr,"GPU "); | |
2904 | } | |
2c7ad758 | 2905 | if ( mids[j] == -1 ) |
2906 | gpucount++; | |
2907 | } | |
4fff8a63 | 2908 | if ( dispflag != 0 ) |
4b729ec5 | 2909 | 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 | 2910 | } |
29e60e48 | 2911 | for (j=0; j<65; j++) |
2912 | if ( mids[j] == notaryid ) | |
2913 | break; | |
49b49585 | 2914 | if ( j == 65 ) |
2915 | KOMODO_LASTMINED = 0; | |
965f0f7e | 2916 | } else fprintf(stderr,"no nonz pubkeys\n"); |
49b49585 | 2917 | if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) ) |
fda5f849 | 2918 | { |
88287857 | 2919 | HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS); |
4b729ec5 | 2920 | fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1); |
fda5f849 | 2921 | } //else fprintf(stderr,"duplicate at j.%d\n",j); |
fb6c7505 | 2922 | } else Mining_start = 0; |
d7d27bb3 | 2923 | } else Mining_start = 0; |
2ba9de01 | 2924 | if ( ASSETCHAINS_STAKED != 0 ) |
e725f1cb | 2925 | { |
ed3d0a05 | 2926 | int32_t percPoS,z; bool fNegative,fOverflow; |
18443f69 | 2927 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
f108acf9 | 2928 | HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); |
f2c1ac06 | 2929 | if ( ASSETCHAINS_STAKED < 100 ) |
2930 | { | |
2931 | for (z=31; z>=0; z--) | |
2932 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); | |
2933 | fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); | |
2934 | } | |
deba7f20 | 2935 | } |
e725f1cb | 2936 | while (true) |
2937 | { | |
99ba67a0 | 2938 | if ( KOMODO_INSYNC == 0 ) |
2939 | { | |
e9d56b2c | 2940 | fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); |
2941 | if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) | |
a02c45db | 2942 | KOMODO_INSYNC = 1; |
99ba67a0 | 2943 | sleep(3); |
2944 | } | |
7213c0b1 | 2945 | // Hash state |
8c22eb46 | 2946 | KOMODO_CHOSEN_ONE = 0; |
42181656 | 2947 | |
7213c0b1 | 2948 | crypto_generichash_blake2b_state state; |
e9574728 | 2949 | EhInitialiseState(n, k, state); |
7213c0b1 JG |
2950 | // I = the block header minus nonce and solution. |
2951 | CEquihashInput I{*pblock}; | |
2952 | CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); | |
2953 | ss << I; | |
7213c0b1 JG |
2954 | // H(I||... |
2955 | crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size()); | |
8e165d57 JG |
2956 | // H(I||V||... |
2957 | crypto_generichash_blake2b_state curr_state; | |
2958 | curr_state = state; | |
7a4c01c9 | 2959 | crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); |
8e165d57 | 2960 | // (x_1, x_2, ...) = A(I, V, n, k) |
7a4c01c9 | 2961 | LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); |
18443f69 | 2962 | arith_uint256 hashTarget; |
6e78d3df | 2963 | if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 ) |
18443f69 | 2964 | hashTarget = HASHTarget_POW; |
2965 | else hashTarget = HASHTarget; | |
5be6abbf | 2966 | std::function<bool(std::vector<unsigned char>)> validBlock = |
8e8b6d70 | 2967 | #ifdef ENABLE_WALLET |
e9e70b95 | 2968 | [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 2969 | #else |
e9e70b95 | 2970 | [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] |
8e8b6d70 | 2971 | #endif |
e9e70b95 | 2972 | (std::vector<unsigned char> soln) { |
c21c6306 | 2973 | int32_t z; arith_uint256 h; CBlock B; |
51eb5273 JG |
2974 | // Write the solution to the hash and compute the result. |
2975 | LogPrint("pow", "- Checking solution against target\n"); | |
8e165d57 | 2976 | pblock->nSolution = soln; |
e7d59bbc | 2977 | solutionTargetChecks.increment(); |
eff2c3a3 | 2978 | B = *pblock; |
2979 | h = UintToArith256(B.GetHash()); | |
eff2c3a3 | 2980 | /*for (z=31; z>=16; z--) |
02c30aac | 2981 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); |
aea2d1aa | 2982 | fprintf(stderr," mined "); |
2983 | for (z=31; z>=16; z--) | |
18443f69 | 2984 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); |
aea2d1aa | 2985 | fprintf(stderr," hashTarget "); |
2986 | for (z=31; z>=16; z--) | |
18443f69 | 2987 | fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); |
eff2c3a3 | 2988 | fprintf(stderr," POW\n");*/ |
265f4e96 | 2989 | if ( h > hashTarget ) |
40df8d84 | 2990 | { |
6e78d3df | 2991 | //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 ) |
afa90f17 | 2992 | // sleep(1); |
265f4e96 | 2993 | return false; |
40df8d84 | 2994 | } |
41e9c815 | 2995 | if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() ) |
d7d27bb3 | 2996 | { |
45ee62cb | 2997 | //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime())); |
596b05ba | 2998 | while ( GetAdjustedTime() < B.nTime-2 ) |
8e9ef91c | 2999 | { |
eb1ba5a0 | 3000 | sleep(1); |
4b729ec5 | 3001 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
4cc387ec | 3002 | { |
3003 | fprintf(stderr,"new block arrived\n"); | |
3004 | return(false); | |
3005 | } | |
8e9ef91c | 3006 | } |
eb1ba5a0 | 3007 | } |
8e9ef91c | 3008 | if ( ASSETCHAINS_STAKED == 0 ) |
d7d27bb3 | 3009 | { |
4d068367 | 3010 | if ( IS_KOMODO_NOTARY != 0 ) |
8e9ef91c | 3011 | { |
26810a26 | 3012 | int32_t r; |
9703f8a0 | 3013 | if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 ) |
596b05ba | 3014 | MilliSleep((rand() % (r * 1000)) + 1000); |
ef70c5b2 | 3015 | } |
e5430f52 | 3016 | } |
8e9ef91c | 3017 | else |
d7d27bb3 | 3018 | { |
0c35569b | 3019 | while ( B.nTime-57 > GetAdjustedTime() ) |
deba7f20 | 3020 | { |
afa90f17 | 3021 | sleep(1); |
4b729ec5 | 3022 | if ( chainActive.LastTip()->GetHeight() >= Mining_height ) |
afa90f17 | 3023 | return(false); |
68d0354d | 3024 | } |
4d068367 | 3025 | uint256 tmp = B.GetHash(); |
3026 | int32_t z; for (z=31; z>=0; z--) | |
3027 | fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); | |
01e50e73 | 3028 | fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height); |
d7d27bb3 | 3029 | } |
8fc79ac9 | 3030 | CValidationState state; |
86131275 | 3031 | if ( !TestBlockValidity(state,B, chainActive.LastTip(), true, false)) |
d2d3c766 | 3032 | { |
8fc79ac9 | 3033 | h = UintToArith256(B.GetHash()); |
3034 | for (z=31; z>=0; z--) | |
3035 | fprintf(stderr,"%02x",((uint8_t *)&h)[z]); | |
3036 | fprintf(stderr," Invalid block mined, try again\n"); | |
3037 | return(false); | |
d2d3c766 | 3038 | } |
b3183e3e | 3039 | KOMODO_CHOSEN_ONE = 1; |
8e165d57 JG |
3040 | // Found a solution |
3041 | SetThreadPriority(THREAD_PRIORITY_NORMAL); | |
2e500f50 | 3042 | LogPrintf("KomodoMiner:\n"); |
eff2c3a3 | 3043 | LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); |
8e8b6d70 | 3044 | #ifdef ENABLE_WALLET |
eff2c3a3 | 3045 | if (ProcessBlockFound(&B, *pwallet, reservekey)) { |
8e8b6d70 | 3046 | #else |
eff2c3a3 | 3047 | if (ProcessBlockFound(&B)) { |
8e8b6d70 | 3048 | #endif |
e9e70b95 | 3049 | // Ignore chain updates caused by us |
3050 | std::lock_guard<std::mutex> lock{m_cs}; | |
3051 | cancelSolver = false; | |
3052 | } | |
3053 | KOMODO_CHOSEN_ONE = 0; | |
3054 | SetThreadPriority(THREAD_PRIORITY_LOWEST); | |
3055 | // In regression test mode, stop mining after a block is found. | |
3056 | if (chainparams.MineBlocksOnDemand()) { | |
3057 | // Increment here because throwing skips the call below | |
3058 | ehSolverRuns.increment(); | |
3059 | throw boost::thread_interrupted(); | |
3060 | } | |
e9e70b95 | 3061 | return true; |
3062 | }; | |
3063 | std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { | |
a6a0d913 | 3064 | std::lock_guard<std::mutex> lock{m_cs}; |
e9e70b95 | 3065 | return cancelSolver; |
3066 | }; | |
3067 | ||
3068 | // TODO: factor this out into a function with the same API for each solver. | |
3069 | if (solver == "tromp" ) { //&& notaryid >= 0 ) { | |
3070 | // Create solver and initialize it. | |
3071 | equi eq(1); | |
3072 | eq.setstate(&curr_state); | |
3073 | ||
3074 | // Initialization done, start algo driver. | |
3075 | eq.digit0(0); | |
c7aaab7a | 3076 | eq.xfull = eq.bfull = eq.hfull = 0; |
e9e70b95 | 3077 | eq.showbsizes(0); |
3078 | for (u32 r = 1; r < WK; r++) { | |
3079 | (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); | |
3080 | eq.xfull = eq.bfull = eq.hfull = 0; | |
3081 | eq.showbsizes(r); | |
c7aaab7a | 3082 | } |
e9e70b95 | 3083 | eq.digitK(0); |
3084 | ehSolverRuns.increment(); | |
3085 | ||
3086 | // Convert solution indices to byte array (decompress) and pass it to validBlock method. | |
3087 | for (size_t s = 0; s < eq.nsols; s++) { | |
3088 | LogPrint("pow", "Checking solution %d\n", s+1); | |
3089 | std::vector<eh_index> index_vector(PROOFSIZE); | |
3090 | for (size_t i = 0; i < PROOFSIZE; i++) { | |
3091 | index_vector[i] = eq.sols[s][i]; | |
3092 | } | |
3093 | std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); | |
3094 | ||
3095 | if (validBlock(sol_char)) { | |
3096 | // If we find a POW solution, do not try other solutions | |
3097 | // because they become invalid as we created a new block in blockchain. | |
3098 | break; | |
3099 | } | |
3100 | } | |
3101 | } else { | |
3102 | try { | |
3103 | // If we find a valid block, we rebuild | |
3104 | bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); | |
3105 | ehSolverRuns.increment(); | |
3106 | if (found) { | |
997ddd92 | 3107 | int32_t i; uint256 hash = pblock->GetHash(); |
e9e70b95 | 3108 | for (i=0; i<32; i++) |
3109 | fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); | |
3110 | fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); | |
3111 | FOUND_BLOCK = 1; | |
3112 | KOMODO_MAYBEMINED = Mining_height; | |
3113 | break; | |
3114 | } | |
3115 | } catch (EhSolverCancelledException&) { | |
3116 | LogPrint("pow", "Equihash solver cancelled\n"); | |
3117 | std::lock_guard<std::mutex> lock{m_cs}; | |
3118 | cancelSolver = false; | |
c7aaab7a DH |
3119 | } |
3120 | } | |
e9e70b95 | 3121 | |
3122 | // Check for stop or if block needs to be rebuilt | |
3123 | boost::this_thread::interruption_point(); | |
3124 | // Regtest mode doesn't require peers | |
3125 | if ( FOUND_BLOCK != 0 ) | |
3126 | { | |
3127 | FOUND_BLOCK = 0; | |
3128 | fprintf(stderr,"FOUND_BLOCK!\n"); | |
3129 | //sleep(2000); | |
3130 | } | |
3131 | if (vNodes.empty() && chainparams.MiningRequiresPeers()) | |
3132 | { | |
3133 | if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) | |
3134 | { | |
3135 | fprintf(stderr,"no nodes, break\n"); | |
c7aaab7a | 3136 | break; |
a6df7ab5 | 3137 | } |
c7aaab7a | 3138 | } |
997ddd92 | 3139 | if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) |
10694486 | 3140 | { |
e9e70b95 | 3141 | //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) |
3142 | fprintf(stderr,"0xffff, break\n"); | |
d90cef0b | 3143 | break; |
10694486 | 3144 | } |
e9e70b95 | 3145 | if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) |
3146 | { | |
3147 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3148 | fprintf(stderr,"timeout, break\n"); | |
3149 | break; | |
3150 | } | |
86131275 | 3151 | if ( pindexPrev != chainActive.LastTip() ) |
e9e70b95 | 3152 | { |
3153 | if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) | |
3154 | fprintf(stderr,"Tip advanced, break\n"); | |
3155 | break; | |
3156 | } | |
3157 | // Update nNonce and nTime | |
3158 | pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); | |
3159 | pblock->nBits = savebits; | |
18dd6a3b | 3160 | /*if ( NOTARY_PUBKEY33[0] == 0 ) |
e9e70b95 | 3161 | { |
f8f740a9 | 3162 | int32_t percPoS; |
df756d24 MT |
3163 | UpdateTime(pblock, consensusParams, pindexPrev); |
3164 | if (consensusParams.fPowAllowMinDifficultyBlocks) | |
23fc88bb | 3165 | { |
3166 | // Changing pblock->nTime can change work required on testnet: | |
3167 | HASHTarget.SetCompact(pblock->nBits); | |
18443f69 | 3168 | HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); |
23fc88bb | 3169 | } |
18dd6a3b | 3170 | }*/ |
48265f3c | 3171 | } |
d247a5d1 JG |
3172 | } |
3173 | } | |
e9e70b95 | 3174 | catch (const boost::thread_interrupted&) |
3175 | { | |
3176 | miningTimer.stop(); | |
3177 | c.disconnect(); | |
3178 | LogPrintf("KomodoMiner terminated\n"); | |
3179 | throw; | |
3180 | } | |
3181 | catch (const std::runtime_error &e) | |
3182 | { | |
3183 | miningTimer.stop(); | |
3184 | c.disconnect(); | |
3185 | LogPrintf("KomodoMiner runtime error: %s\n", e.what()); | |
3186 | return; | |
3187 | } | |
07be8f7e | 3188 | miningTimer.stop(); |
5e9b555f | 3189 | c.disconnect(); |
bba7c249 | 3190 | } |
e9e70b95 | 3191 | |
8e8b6d70 | 3192 | #ifdef ENABLE_WALLET |
e9e70b95 | 3193 | void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) |
8e8b6d70 | 3194 | #else |
e9e70b95 | 3195 | void GenerateBitcoins(bool fGenerate, int nThreads) |
8e8b6d70 | 3196 | #endif |
d247a5d1 | 3197 | { |
f8f61a6d | 3198 | if (!AreParamsInitialized()) |
3199 | { | |
3200 | return; | |
3201 | } | |
3202 | ||
10214558 | 3203 | // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at |
3204 | // initialization, and this is the first time we can get it. store the Sapling address here | |
3205 | extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher; | |
3206 | extern std::string VERUS_CHEATCATCHER; | |
3207 | libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER); | |
3208 | if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr)) | |
3209 | { | |
99c94fc3 | 3210 | try |
3211 | { | |
3212 | cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr); | |
3213 | } | |
3214 | catch (...) | |
3215 | { | |
3216 | } | |
10214558 | 3217 | } |
bd6639fd | 3218 | |
b20c38cc | 3219 | VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0); |
bd6639fd | 3220 | |
89cd7b59 | 3221 | if (fGenerate == true || VERUS_MINTBLOCKS) |
10214558 | 3222 | { |
89cd7b59 MT |
3223 | mapArgs["-gen"] = "1"; |
3224 | ||
3225 | if (VERUS_CHEATCATCHER.size() > 0) | |
99c94fc3 | 3226 | { |
89cd7b59 MT |
3227 | if (cheatCatcher == boost::none) |
3228 | { | |
3229 | LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n"); | |
3230 | fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n"); | |
3231 | } | |
3232 | else | |
3233 | { | |
3234 | LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3235 | fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str()); | |
3236 | } | |
99c94fc3 | 3237 | } |
3238 | } | |
10214558 | 3239 | |
e9e70b95 | 3240 | static boost::thread_group* minerThreads = NULL; |
28424e9f | 3241 | |
e9e70b95 | 3242 | if (nThreads < 0) |
3243 | nThreads = GetNumCores(); | |
3244 | ||
3245 | if (minerThreads != NULL) | |
3246 | { | |
3247 | minerThreads->interrupt_all(); | |
3248 | delete minerThreads; | |
3249 | minerThreads = NULL; | |
3250 | } | |
135fa24e | 3251 | |
afaeb54b | 3252 | //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate); |
5034d1c1 | 3253 | if ( nThreads == 0 && ASSETCHAINS_STAKED ) |
3a446d9f | 3254 | nThreads = 1; |
5034d1c1 | 3255 | |
28424e9f | 3256 | if (!fGenerate) |
e9e70b95 | 3257 | return; |
135fa24e | 3258 | |
e9e70b95 | 3259 | minerThreads = new boost::thread_group(); |
135fa24e | 3260 | |
85c51d62 | 3261 | // add the PBaaS thread when mining or staking |
3262 | minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub)); | |
3263 | ||
135fa24e | 3264 | #ifdef ENABLE_WALLET |
b20c38cc | 3265 | if (VERUS_MINTBLOCKS && pwallet != NULL) |
135fa24e | 3266 | { |
3267 | minerThreads->create_thread(boost::bind(&VerusStaker, pwallet)); | |
3268 | } | |
3269 | #endif | |
3270 | ||
e9e70b95 | 3271 | for (int i = 0; i < nThreads; i++) { |
135fa24e | 3272 | |
8e8b6d70 | 3273 | #ifdef ENABLE_WALLET |
135fa24e | 3274 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3275 | minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); | |
3276 | else | |
3277 | minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet)); | |
8e8b6d70 | 3278 | #else |
135fa24e | 3279 | if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH) |
3280 | minerThreads->create_thread(&BitcoinMiner); | |
3281 | else | |
3282 | minerThreads->create_thread(&BitcoinMiner_noeq); | |
8e8b6d70 | 3283 | #endif |
e9e70b95 | 3284 | } |
8e8b6d70 | 3285 | } |
e9e70b95 | 3286 | |
2cc0a252 | 3287 | #endif // ENABLE_MINING |