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