1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or https://www.opensource.org/licenses/mit-license.php .
8 #include "pow/tromp/equi_miner.h"
12 #include "chainparams.h"
13 #include "cc/StakeGuard.h"
14 #include "importcoin.h"
15 #include "consensus/consensus.h"
16 #include "consensus/upgrades.h"
17 #include "consensus/validation.h"
19 #include "crypto/equihash.h"
20 #include "crypto/verus_hash.h"
28 #include "primitives/transaction.h"
31 #include "ui_interface.h"
33 #include "utilmoneystr.h"
34 #include "validationinterface.h"
36 #include "zcash/Address.hpp"
37 #include "transaction_builder.h"
41 #include <boost/thread.hpp>
42 #include <boost/tuple/tuple.hpp>
48 #include "pbaas/pbaas.h"
49 #include "pbaas/notarization.h"
50 #include "pbaas/identity.h"
51 #include "rpc/pbaasrpc.h"
52 #include "transaction_builder.h"
56 //////////////////////////////////////////////////////////////////////////////
62 // Unconfirmed transactions in the memory pool often depend on other
63 // transactions in the memory pool. When we select transactions from the
64 // pool, we select by highest priority or fee rate, so we might consider
65 // transactions that depend on transactions that aren't yet in the block.
66 // The COrphan class keeps track of these 'temporary orphans' while
67 // CreateBlock is figuring out which transactions to include.
72 const CTransaction* ptx;
73 set<uint256> setDependsOn;
77 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
82 uint64_t nLastBlockTx = 0;
83 uint64_t nLastBlockSize = 0;
85 // We want to sort transactions by priority and fee rate, so:
86 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
87 class TxPriorityCompare
92 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
94 bool operator()(const TxPriority& a, const TxPriority& b)
98 if (a.get<1>() == b.get<1>())
99 return a.get<0>() < b.get<0>();
100 return a.get<1>() < b.get<1>();
104 if (a.get<0>() == b.get<0>())
105 return a.get<1>() < b.get<1>();
106 return a.get<0>() < b.get<0>();
111 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
113 pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
115 // Updating time can change work required on testnet:
116 if (consensusParams.nPowAllowMinDifficultyBlocksAfterHeight != boost::none) {
117 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
121 #include "komodo_defs.h"
123 extern CCriticalSection cs_metrics;
124 extern int32_t KOMODO_MININGTHREADS,KOMODO_LONGESTCHAIN,ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
125 extern uint64_t ASSETCHAINS_COMMISSION, ASSETCHAINS_STAKED;
126 extern bool VERUS_MINTBLOCKS;
127 extern uint64_t ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS], ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_NONCEMASK[];
128 extern const char *ASSETCHAINS_ALGORITHMS[];
129 extern int32_t VERUS_MIN_STAKEAGE, ASSETCHAINS_EQUIHASH, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA, ASSETCHAINS_LWMAPOS, ASSETCHAINS_NONCESHIFT[], ASSETCHAINS_HASHESPERROUND[];
130 extern uint32_t ASSETCHAINS_ALGO;
131 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
132 extern uint160 ASSETCHAINS_CHAINID;
133 extern uint160 VERUS_CHAINID;
134 extern std::string VERUS_CHAINNAME;
135 extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK;
136 extern string PBAAS_HOST, PBAAS_USERPASS, ASSETCHAINS_RPCHOST, ASSETCHAINS_RPCCREDENTIALS;;
137 extern int32_t PBAAS_PORT;
138 extern uint16_t ASSETCHAINS_RPCPORT;
139 extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
140 void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
142 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
143 uint32_t Mining_start, Mining_height;
144 int32_t My_notaryid = -1;
145 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
146 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
147 int32_t komodo_baseid(char *origbase);
148 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
149 int64_t komodo_block_unlocktime(uint32_t nHeight);
150 uint64_t komodo_commission(const CBlock *block);
151 int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
152 int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits, arith_uint256 &hashResult, uint8_t *utxosig, CPubKey &pk);
153 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
155 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int &nExtraNonce, bool buildMerkle, uint32_t *pSaveBits)
157 // Update nExtraNonce
158 static uint256 hashPrevBlock;
159 if (hashPrevBlock != pblock->hashPrevBlock)
162 hashPrevBlock = pblock->hashPrevBlock;
168 *pSaveBits = pblock->nBits;
171 int32_t nHeight = pindexPrev->GetHeight() + 1;
173 if (CConstVerusSolutionVector::activationHeight.ActiveVersion(nHeight) >= CConstVerusSolutionVector::activationHeight.ACTIVATE_PBAAS)
175 // coinbase should already be finalized in the new version
178 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
179 pblock->SetPrevMMRRoot(ChainMerkleMountainView(chainActive.GetMMR(), pindexPrev->GetHeight()).GetRoot());
180 BlockMMRange mmRange(pblock->BuildBlockMMRTree());
181 BlockMMView mmView(mmRange);
182 pblock->SetBlockMMRRoot(mmView.GetRoot());
183 pblock->AddUpdatePBaaSHeader();
186 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
191 // set the PBaaS header
192 ChainMerkleMountainView mmv = chainActive.GetMMV();
193 mmvRoot = mmv.GetRoot();
196 pblock->AddUpdatePBaaSHeader();
198 // POS blocks have already had their solution space filled, and there is no actual extra nonce, extradata is used
199 // for POS proof, so don't modify it
200 if (!pblock->IsVerusPOSBlock())
203 // clear extra data to allow adding more PBaaS headers
204 pblock->SetExtraData(&dummy, 0);
206 // combine blocks and set compact difficulty if necessary
208 if ((savebits = ConnectedChains.CombineBlocks(*pblock)) && pSaveBits)
210 arith_uint256 ours, merged;
211 ours.SetCompact(pblock->nBits);
212 merged.SetCompact(savebits);
215 *pSaveBits = savebits;
219 // extra nonce is kept in the header, not in the coinbase any longer
220 // this allows instant spend transactions to use coinbase funds for
221 // inputs by ensuring that once final, the coinbase transaction hash
222 // will not continue to change
223 CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
225 std::vector<unsigned char> vENonce(s.begin(), s.end());
227 assert(pblock->ExtraDataLen() >= vENonce.size());
228 pblock->SetExtraData(vENonce.data(), vENonce.size());
233 // finalize input of coinbase
234 CMutableTransaction txcb(pblock->vtx[0]);
235 txcb.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
236 assert(txcb.vin[0].scriptSig.size() <= 100);
237 pblock->vtx[0] = txcb;
240 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
243 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
247 extern CWallet *pwalletMain;
249 CPubKey GetSolutionPubKey(const std::vector<std::vector<unsigned char>> &vSolutions, txnouttype txType)
253 if (txType == TX_PUBKEY)
255 pk = CPubKey(vSolutions[0]);
257 else if(txType == TX_PUBKEYHASH)
259 // we need to have this in our wallet to get the public key
260 LOCK(pwalletMain->cs_wallet);
261 pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);
263 else if (txType == TX_CRYPTOCONDITION)
265 if (vSolutions[0].size() == 33)
267 pk = CPubKey(vSolutions[0]);
269 else if (vSolutions[0].size() == 34 && vSolutions[0][0] == COptCCParams::ADDRTYPE_PK)
271 pk = CPubKey(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()));
273 else if (vSolutions[0].size() == 20)
275 LOCK(pwalletMain->cs_wallet);
276 pwalletMain->GetPubKey(CKeyID(uint160(vSolutions[0])), pk);
278 else if (vSolutions[0].size() == 21 && vSolutions[0][0] == COptCCParams::ADDRTYPE_ID)
280 // destination is an identity, see if we can get its first public key
281 std::pair<CIdentityMapKey, CIdentityMapValue> identity;
283 if (pwalletMain->GetIdentity(CIdentityID(uint160(std::vector<unsigned char>(vSolutions[0].begin() + 1, vSolutions[0].end()))), identity) &&
284 identity.second.IsValidUnrevoked() &&
285 identity.second.primaryAddresses.size())
287 CPubKey pkTmp = boost::apply_visitor<GetPubKeyForPubKey>(GetPubKeyForPubKey(), identity.second.primaryAddresses[0]);
294 LOCK(pwalletMain->cs_wallet);
295 pwalletMain->GetPubKey(CKeyID(GetDestinationID(identity.second.primaryAddresses[0])), pk);
303 CPubKey GetScriptPublicKey(const CScript &scriptPubKey)
306 std::vector<std::vector<unsigned char>> vSolutions;
307 if (Solver(scriptPubKey, typeRet, vSolutions))
309 return GetSolutionPubKey(vSolutions, typeRet);
314 CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& _scriptPubKeyIn, int32_t gpucount, bool isStake)
316 CScript scriptPubKeyIn(_scriptPubKeyIn);
318 // instead of one scriptPubKeyIn, we take a vector of them along with relative weight. each is assigned a percentage of the block subsidy and
319 // mining reward based on its weight relative to the total
320 std::vector<pair<int, CScript>> minerOutputs = scriptPubKeyIn.size() ? std::vector<pair<int, CScript>>({make_pair((int)1, scriptPubKeyIn)}) : std::vector<pair<int, CScript>>();
322 CTxDestination firstDestination;
323 if (!(scriptPubKeyIn.size() && ConnectedChains.SetLatestMiningOutputs(minerOutputs, firstDestination) || isStake))
325 fprintf(stderr,"%s: Must have valid miner outputs, including script with valid PK, PKH, or Verus ID destination.\n", __func__);
331 if (minerOutputs.size())
333 int64_t shareCheck = 0;
334 for (auto output : minerOutputs)
336 shareCheck += output.first;
337 if (shareCheck < 0 || shareCheck > INT_MAX)
339 fprintf(stderr,"Invalid miner outputs share specifications\n");
343 pk = GetScriptPublicKey(minerOutputs[0].second);
346 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime;
347 //fprintf(stderr,"create new block\n");
350 gpucount = KOMODO_MAXGPUCOUNT;
351 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
352 if(!pblocktemplate.get())
354 fprintf(stderr,"pblocktemplate.get() failure\n");
357 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
359 // set version according to the current tip height, add solution if it is
361 if (ASSETCHAINS_ALGO == ASSETCHAINS_VERUSHASH)
363 pblock->nSolution.resize(Eh200_9.SolutionWidth);
367 pblock->nSolution.clear();
369 pblock->SetVersionByHeight(chainActive.LastTip()->GetHeight() + 1);
371 // -regtest only: allow overriding block.nVersion with
372 // -blockversion=N to test forking scenarios
373 if (chainparams.MineBlocksOnDemand())
374 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
376 // Add dummy coinbase tx placeholder as first transaction
377 pblock->vtx.push_back(CTransaction());
379 pblocktemplate->vTxFees.push_back(-1); // updated at end
380 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
382 // Largest block you're willing to create:
383 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
384 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
385 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
387 unsigned int nMaxIDSize = nBlockMaxSize / 2;
388 unsigned int nCurrentIDSize = 0;
390 // How much of the block should be dedicated to high-priority transactions,
391 // included regardless of the fees they pay
392 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
393 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
395 // Minimum block size you want to create; block will be filled with free transactions
396 // until there are no more or the block reaches this size:
397 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
398 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
400 // Collect memory pool transactions into the block
403 // if this is a reserve currency, update the currency state from the coinbase of the last block
404 bool isVerusActive = IsVerusActive();
405 CCurrencyDefinition &thisChain = ConnectedChains.ThisChain();
406 CAmount prealloc = 0;
407 for (auto &onePair : thisChain.preAllocation)
409 prealloc += onePair.second;
411 CCoinbaseCurrencyState currencyState = CCoinbaseCurrencyState(CCurrencyStateNew(thisChain.currencies,
413 thisChain.contributions,
416 std::vector<CAmount> exchangeRate(thisChain.currencies.size());
418 // we will attempt to spend any cheats we see
419 CTransaction cheatTx;
420 boost::optional<CTransaction> cheatSpend;
423 CBlockIndex* pindexPrev = 0;
425 LOCK2(cs_main, mempool.cs);
426 pindexPrev = chainActive.LastTip();
427 const int nHeight = pindexPrev->GetHeight() + 1;
428 const Consensus::Params &consensusParams = chainparams.GetConsensus();
429 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, consensusParams);
430 bool sapling = consensusParams.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_SAPLING);
432 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
433 uint32_t proposedTime = GetAdjustedTime();
434 if (proposedTime == nMedianTimePast)
436 // too fast or stuck, this addresses the too fast issue, while moving
437 // forward as quickly as possible
438 for (int i; i < 100; i++)
440 proposedTime = GetAdjustedTime();
441 if (proposedTime == nMedianTimePast)
445 pblock->nTime = GetAdjustedTime();
447 CCoinsViewCache view(pcoinsTip);
448 uint32_t expired; uint64_t commission;
450 SaplingMerkleTree sapling_tree;
451 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
453 // Priority order to process transactions
454 list<COrphan> vOrphan; // list memory doesn't move
455 map<uint256, vector<COrphan*> > mapDependers;
456 bool fPrintPriority = GetBoolArg("-printpriority", false);
458 // This vector will be sorted into a priority queue:
459 vector<TxPriority> vecPriority;
460 vecPriority.reserve(mempool.mapTx.size() + 1);
462 // check if we should add cheat transaction
465 int cheatHeight = nHeight - COINBASE_MATURITY < 1 ? 1 : nHeight - COINBASE_MATURITY;
467 sapling && chainActive.Height() > 100 &&
468 (ppast = chainActive[cheatHeight]) &&
469 ppast->IsVerusPOSBlock() &&
470 cheatList.IsHeightOrGreaterInList(cheatHeight))
472 // get the block and see if there is a cheat candidate for the stake tx
474 if (!(fHavePruned && !(ppast->nStatus & BLOCK_HAVE_DATA) && ppast->nTx > 0) && ReadBlockFromDisk(b, ppast, chainparams.GetConsensus(), 1))
476 CTransaction &stakeTx = b.vtx[b.vtx.size() - 1];
478 if (cheatList.IsCheatInList(stakeTx, &cheatTx))
480 // make and sign the cheat transaction to spend the coinbase to our address
481 CMutableTransaction mtx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
484 // get the first vout with value
485 for (voutNum = 0; voutNum < b.vtx[0].vout.size(); voutNum++)
487 if (b.vtx[0].vout[voutNum].nValue > 0)
491 // send to the same pub key as the destination of this block reward
492 if (MakeCheatEvidence(mtx, b.vtx[0], voutNum, cheatTx))
494 LOCK(pwalletMain->cs_wallet);
495 TransactionBuilder tb = TransactionBuilder(consensusParams, nHeight);
497 cbHash = cb.GetHash();
499 bool hasInput = false;
500 for (uint32_t i = 0; i < cb.vout.size(); i++)
502 // add the spends with the cheat
503 if (cb.vout[i].nValue > 0)
505 tb.AddTransparentInput(COutPoint(cbHash,i), cb.vout[0].scriptPubKey, cb.vout[0].nValue);
512 // this is a send from a t-address to a sapling address, which we don't have an ovk for.
513 // Instead, generate a common one from the HD seed. This ensures the data is
514 // recoverable, at least for us, while keeping it logically separate from the ZIP 32
515 // Sapling key hierarchy, which the user might not be using.
518 if (pwalletMain->GetHDSeed(seed)) {
519 ovk = ovkForShieldingFromTaddr(seed);
521 // send everything to Sapling address
522 tb.SendChangeTo(cheatCatcher.value(), ovk);
524 tb.AddOpRet(mtx.vout[mtx.vout.size() - 1].scriptPubKey);
526 TransactionBuilderResult buildResult(tb.Build());
527 if (!buildResult.IsError() && buildResult.IsTx())
529 cheatSpend = buildResult.GetTxOrThrow();
533 LogPrintf("Error building cheat catcher transaction: %s\n", buildResult.GetError().c_str());
544 cheatTx = cheatSpend.value();
545 std::list<CTransaction> removed;
546 mempool.removeConflicts(cheatTx, removed);
547 printf("Found cheating stake! Adding cheat spend for %.8f at block #%d, coinbase tx\n%s\n",
548 (double)cb.GetValueOut() / (double)COIN, nHeight, cheatSpend.value().vin[0].prevout.hash.GetHex().c_str());
550 // add to mem pool and relay
551 if (myAddtomempool(cheatTx))
553 RelayTransaction(cheatTx);
558 // Now start solving the block
561 uint64_t nBlockSize = 1000; // initial size
562 uint64_t nBlockTx = 1; // number of transactions - always have a coinbase
563 uint32_t autoTxSize = 0; // extra transaction overhead that we will add while creating the block
564 int nBlockSigOps = 100;
566 // VerusPoP staking transaction data
567 CMutableTransaction txStaked; // if this is a stake operation, the staking transaction that goes at the end
568 uint32_t nStakeTxSize = 0; // serialized size of the stake transaction
570 // if this is not for mining, first determine if we have a right to bother
573 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
574 txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);
576 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
577 // blocktime = pindexPrev->GetMedianTimePast() + 60;
578 if (ASSETCHAINS_LWMAPOS != 0)
581 arith_uint256 posHash;
583 siglen = verus_staked(pblock, txStaked, nBitsPOS, posHash, utxosig, pk);
584 blocktime = GetAdjustedTime();
586 // change the default scriptPubKeyIn to the same output script exactly as the staking transaction
587 // TODO: improve this and just implement stake guard here rather than keeping this legacy
589 scriptPubKeyIn = CScript(txStaked.vout[0].scriptPubKey);
593 siglen = komodo_staked(txStaked, pblock->nBits, &blocktime, &txtime, &utxotxid, &utxovout, &utxovalue, utxosig);
601 pblock->nTime = blocktime;
602 nStakeTxSize = GetSerializeSize(txStaked, SER_NETWORK, PROTOCOL_VERSION);
603 nBlockSize += nStakeTxSize;
605 // get the public key and make a miner output if needed for this
606 if (!minerOutputs.size())
608 minerOutputs.push_back(make_pair((int)1, txStaked.vout[0].scriptPubKey));
609 pk = GetScriptPublicKey(txStaked.vout[0].scriptPubKey);
610 ExtractDestination(minerOutputs[0].second, firstDestination);
614 ConnectedChains.AggregateChainTransfers(firstDestination, nHeight);
616 // Now the coinbase -
617 // A PBaaS coinbase must have some additional outputs to enable certain chain state and functions to be properly
618 // validated. All but currency state and the first chain definition are either optional or not valid on non-fractional reserve PBaaS blockchains
619 // All of these are instant spend outputs that have no maturity wait time and may be spent in the same block.
621 // 1. (required) currency state - current state of currency supply and optionally reserve, premine, etc. This is primarily a data output to provide
622 // cross check for coin minting and burning operations, making it efficient to determine up-to-date supply, reserves, and conversions. To provide
623 // an extra level of supply cross-checking and fast data retrieval, this is part of all PBaaS chains' protocol, not just reserves.
624 // This output also includes reserve and native amounts for total conversions, less fees, of any conversions between Verus reserve and the
627 // 2. (block 1 required) chain definition - in order to confirm the amount of coins converted and issued within the possible range, before chain start,
628 // new PBaaS chains have a zero-amount, unspendable chain definition output.
630 // 3. (block 1 optional) initial import utxo - for any chain with conversion or pre-conversion, the first coinbase must include an initial import utxo.
631 // Pre-conversions are handled on the launch chain before the PBaaS chain starts, so they are an additional output, which begins
632 // 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
633 // are imported. All pre-converted outputs get their source currency from a thread that starts with this output in block 1.
635 // 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
636 // may have one, but currently, they can only be spent with valid exports, which only occur on reserve chains
638 // 5. (optional) notarization output - in order to ensure that notarization can occur independent of the availability of fungible
639 // coins on the network, and also that the notarization can provide a spendable finalization output and possible reward
641 // In addition, each PBaaS block can be mined with optional, fee-generating transactions. Inporting transactions from the reserve chain or sending
642 // exported transactions to the reserve chain are optional fee-generating steps that would be easy to do when running multiple daemons.
643 // The types of transactions miners/stakers may facilitate or create for fees are as follows:
645 // 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
647 // 2. Imported transactions from the export thread for this PBaaS chain on the Verus blockchain - imported transactions must spend the import utxo
648 // thread, represent the export from the alternate chain which spends the export output from the prior import transaction, carry a notary proof, and
649 // include outputs that map to each of its inputs on the source chain. Outputs can include unconverted reserve outputs only on fractional
650 // reserve chains, pre-converted outputs for any chain with launch conversion, and post launch outputs to be converted on fractional reserve
651 // chains. Each are handled in the following way:
652 // a. Unconverted outputs are left as outputs to the intended destination of Verus reserve token and do not pass through the coinbase
653 // b. Pre-converted outputs require that the import transaction spend the last pre-conversion output starting at block 1 as the source for
654 // pre-converted currency.
656 // 3. Zero or more aggregated exports that combine individual cross-chain transactions and reserve transfer outputs for export to the Verus chain.
658 // 4. Conversion distribution transactions for all native and reserve currency conversions, including reserve transfer outputs without conversion as
659 // a second step for reserve transfers that have conversion included. Any remaining pre-converted reserve must always remain in a change output
660 // until it is exhausted
661 CTxOut premineOut, chainDefinitionOut, importThreadOut, exportThreadOut, currencyStateOut, notarizationOut;
662 CMutableTransaction newNotarizationTx, newConversionOutputTx;
663 int currencyStateOutNum = 0, notarizationOutNum = 0;
665 // size of conversion tx
666 std::vector<CInputDescriptor> conversionInputs;
668 // if we are a PBaaS chain, first make sure we don't start prematurely, and if
669 // we should make an earned notarization, make it and set index to non-zero value
670 int32_t notarizationTxIndex = 0; // index of notarization if it is added
671 int32_t conversionTxIndex = 0; // index of conversion transaction if it is added
673 // export transactions can be created here by aggregating all pending transfer requests and either getting 10 or more together, or
674 // waiting n (10) blocks since the last one. each export must spend the output of the one before it
675 std::vector<CMutableTransaction> exportTransactions;
677 // all transaction outputs requesting conversion to another currency (PBaaS fractional reserve only)
678 // these will be used to calculate conversion price, fees, and generate coinbase conversion output as well as the
679 // conversion output transaction
680 std::vector<CTxOut> reserveConversionTo;
681 std::vector<CTxOut> reserveConversionFrom;
683 int64_t pbaasTransparentIn = 0;
684 int64_t pbaasTransparentOut = 0;
685 //extern int64_t ASSETCHAINS_SUPPLY;
686 //printf("%lu premine\n", ASSETCHAINS_SUPPLY);
687 int64_t blockSubsidy = GetBlockSubsidy(nHeight, consensusParams);
689 uint160 thisChainID = ConnectedChains.ThisChain().GetID();
692 vector<CInputDescriptor> notarizationInputs;
694 // used as scratch for making CCs, should be reinitialized each time
697 vector<CTxDestination> vKeys;
700 // Create coinbase tx and set up the null input with height
701 CMutableTransaction coinbaseTx = CreateNewContextualCMutableTransaction(consensusParams, nHeight);
702 coinbaseTx.vin.push_back(CTxIn(uint256(), (uint32_t)-1, CScript() << nHeight << OP_0));
704 // we will update amounts and fees later, but convert the guarded output now for validity checking and size estimate
707 // if there is a specific destination, use it
708 CTransaction stakeTx(txStaked);
710 if (ValidateStakeTransaction(stakeTx, p, false))
712 if (p.Version() < p.VERSION_EXTENDED_STAKE && !p.pk.IsValid())
714 LogPrintf("CreateNewBlock: invalid public key\n");
715 fprintf(stderr,"CreateNewBlock: invalid public key\n");
718 coinbaseTx.vout.push_back(CTxOut(1, CScript()));
719 if (!MakeGuardedOutput(1, p.pk, stakeTx, coinbaseTx.vout.back()))
721 LogPrintf("CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
722 fprintf(stderr,"CreateNewBlock: failed to make GuardedOutput on staking coinbase\n");
728 LogPrintf("CreateNewBlock: invalid stake transaction\n");
729 fprintf(stderr,"CreateNewBlock: invalid stake transaction\n");
735 // default outputs for mining and before stake guard or fee calculation
736 // store the relative weight in the amount output to convert later to a relative portion
737 // of the reward + fees
738 for (auto &spk : minerOutputs)
740 coinbaseTx.vout.push_back(CTxOut(spk.first, spk.second));
744 CAmount totalEmission = blockSubsidy;
746 // make earned notarization only if this is not the Verus chain and we have enough subsidy
749 // if we don't have a connected root PBaaS chain, we can't properly check
750 // and notarize the start block, so we have to pass the notarization and cross chain steps
751 bool notaryConnected = ConnectedChains.IsVerusPBaaSAvailable() && ConnectedChains.notaryChainHeight >= PBAAS_STARTBLOCK;
753 // get current currency state differently, depending on height
756 if (!notaryConnected || !ConnectedChains.readyToStart)
758 // cannot make block 1 unless we can properly notarize that the launch chain is past the start block
762 // if some amount of pre-conversion was allowed, we need to check with all eligible currency
763 // chains or systems to determine how much in each currency is available for preconversion
764 // TODO: support querying multiple systems... initial support for VRSC and VRSCTEST-homed currencies
765 if (thisChain.maxPreconvert.size() && thisChain.maxPreconvert.size() == thisChain.currencies.size())
767 // get the total amount pre-converted
768 UniValue params(UniValue::VARR);
769 params.push_back(EncodeDestination(CIdentityID(ASSETCHAINS_CHAINID)));
774 result = find_value(RPCCallRoot("getinitialcurrencystate", params), "result");
775 } catch (exception e)
777 result = NullUniValue;
780 if (!result.isNull())
782 currencyState = CCoinbaseCurrencyState(result);
785 if (result.isNull() || !currencyState.IsValid())
787 // no matter what happens, we should be able to get a valid currency state of some sort, if not, fail
788 LogPrintf("Unable to get initial currency state to create block.\n");
789 printf("Failure to get initial currency state. Cannot create block.\n");
793 CCurrencyValueMap preConverted = CCurrencyValueMap(ConnectedChains.ThisChain().currencies, currencyState.reserveIn);
794 CCurrencyValueMap minPreconvert = CCurrencyValueMap(ConnectedChains.ThisChain().currencies, ConnectedChains.ThisChain().minPreconvert);
796 if (preConverted < minPreconvert)
798 // we must reach minimums in all currencies to launch
799 LogPrintf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n");
800 printf("This chain did not receive the minimum currency contributions and cannot launch. Pre-launch contributions to this chain can be refunded.\n");
804 thisChain.preconverted = preConverted.AsCurrencyVector(thisChain.currencies);
805 thisChain.conversions = currencyState.conversionPrice;
808 CAmount blockOnePremine = thisChain.GetTotalPreallocation();
809 SetBlockOnePremine(blockOnePremine);
810 totalEmission = GetBlockSubsidy(nHeight, consensusParams);
811 blockSubsidy = totalEmission - blockOnePremine;
813 // add needed block one coinbase outputs for preallocation
816 std::vector<CTxOut> tmpOut;
817 for (auto &onePremine : ConnectedChains.ThisChain().GetPreAllocationAmounts())
819 premineOut = CTxOut(onePremine.second, GetScriptForDestination(CTxDestination(CIdentityID(onePremine.first))));
820 tmpOut.push_back(premineOut);
824 coinbaseTx.vout.insert(coinbaseTx.vout.end(), tmpOut.begin(), tmpOut.end());
828 // now, we have pre-mine outputs calculated and created for either absolute or percentage-based
831 // following that, we have either 1 stake guarded output to the staker or delegate,
832 // or some number of miner outputs
834 // now, start adding additional outputs, including chain-definition output for Notary chain and all currencies in ConnectedChains
835 ConnectedChains.LoadReserveCurrencies();
837 // create a currency definition output for this currency, the notary currency, and all reserves
840 cp = CCinit(&CC, EVAL_CURRENCY_DEFINITION);
841 pkCC = CPubKey(ParseHex(CC.CChexstr));
843 std::vector<CTxDestination> indexDests({CKeyID(ConnectedChains.ThisChain().GetConditionID(EVAL_CURRENCY_DEFINITION))});
844 std::vector<CTxDestination> dests({pkCC});
846 coinbaseTx.vout.push_back(CTxOut(0,
847 MakeMofNCCScript(CConditionObj<CCurrencyDefinition>(EVAL_CURRENCY_DEFINITION, dests, 1,
848 &ConnectedChains.ThisChain()),
851 for (auto &oneCur : ConnectedChains.reserveCurrencies)
853 indexDests = std::vector<CTxDestination>({CKeyID(ConnectedChains.ThisChain().GetConditionID(EVAL_CURRENCY_DEFINITION)),
854 CKeyID(oneCur.second.GetConditionID(EVAL_CURRENCY_DEFINITION))});
855 coinbaseTx.vout.push_back(CTxOut(0,
856 MakeMofNCCScript(CConditionObj<CCurrencyDefinition>(EVAL_CURRENCY_DEFINITION, dests, 1, &oneCur.second),
860 if (!ConnectedChains.reserveCurrencies.count(ConnectedChains.NotaryChain().GetID()))
862 indexDests = std::vector<CTxDestination>({CKeyID(ConnectedChains.ThisChain().GetConditionID(EVAL_CURRENCY_DEFINITION)),
863 CKeyID(ConnectedChains.NotaryChain().chainDefinition.GetConditionID(EVAL_CURRENCY_DEFINITION))});
864 coinbaseTx.vout.push_back(CTxOut(0,
865 MakeMofNCCScript(CConditionObj<CCurrencyDefinition>(EVAL_CURRENCY_DEFINITION, dests, 1,
866 &ConnectedChains.NotaryChain().chainDefinition),
870 // create the import thread output
871 cp = CCinit(&CC, EVAL_CROSSCHAIN_IMPORT);
872 pkCC = CPubKey(ParseHex(CC.CChexstr));
874 // import thread from PBaaS parent
875 indexDests = std::vector<CTxDestination>({CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetID(), EVAL_CROSSCHAIN_IMPORT))});
876 dests = std::vector<CTxDestination>({pkCC});
878 CCurrencyValueMap cvm;
879 for (auto &inPair : ConnectedChains.ThisChain().preAllocation)
881 cvm.valueMap[inPair.first] = inPair.second;
883 CCrossChainImport cci = CCrossChainImport(ConnectedChains.notaryChain.GetID(), cvm);
884 coinbaseTx.vout.push_back(CTxOut(currencyState.ReserveToNativeRaw(CCurrencyValueMap(thisChain.currencies, thisChain.preconverted), thisChain.conversions),
885 MakeMofNCCScript(CConditionObj<CCrossChainImport>(EVAL_CROSSCHAIN_IMPORT, dests, 1, &cci), &indexDests)));
887 // export thread to PBaaS parent
888 cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT);
889 pkCC = CPubKey(ParseHex(CC.CChexstr));
890 indexDests = std::vector<CTxDestination>({CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.notaryChain.GetID(), EVAL_CROSSCHAIN_EXPORT))});
891 dests = std::vector<CTxDestination>({pkCC});
893 CCrossChainExport ccx(ConnectedChains.NotaryChain().GetID(), 0, CCurrencyValueMap(), CCurrencyValueMap());
894 coinbaseTx.vout.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CCrossChainExport>(EVAL_CROSSCHAIN_EXPORT, dests, 1, &ccx), &indexDests)));
900 currencyState = ConnectedChains.GetCurrencyState(nHeight - 1);
901 currencyState.ClearForNextBlock();
903 if (!currencyState.IsValid())
905 // we should be able to get a valid currency state, if not, fail
906 LogPrintf("Unable to get initial currency state to create block #%d.\n", nHeight);
907 printf("Failure to get initial currency state. Cannot create block #%d.\n", nHeight);
912 // update the currency state to include emissions before calculating conversions
913 // premine is an emission that is factored in before this
914 currencyState.UpdateWithEmission(totalEmission);
916 // add currency state output to coinbase
918 cp = CCinit(&CC, EVAL_CURRENCYSTATE);
920 CPubKey currencyOutPK(ParseHex(cp->CChexstr));
921 std::vector<CTxDestination> indexDests({CKeyID(CCrossChainRPCData::GetConditionID(thisChainID, EVAL_CURRENCYSTATE))});
922 std::vector<CTxDestination> dests({currencyOutPK});
924 // pre-conversions go to the import thread
925 // conversions for this block, if any, will be processed
927 coinbaseTx.vout.push_back(CTxOut(currencyState.ReserveToNativeRaw(CCurrencyValueMap(thisChain.currencies, thisChain.preconverted), thisChain.conversions),
928 MakeMofNCCScript(CConditionObj<CCoinbaseCurrencyState>(EVAL_CROSSCHAIN_EXPORT, dests, 1, ¤cyState), &indexDests)));
930 currencyStateOutNum = coinbaseTx.vout.size() - 1;
934 // if we have access to our notary daemon
935 // create a notarization if we would qualify to do so. add it to the mempool and next block
936 CTransaction prevTx, crossTx, lastConfirmed, lastImportTx;
937 ChainMerkleMountainView mmv = chainActive.GetMMV();
938 mmrRoot = mmv.GetRoot();
939 int32_t confirmedInput = -1;
940 CTxDestination confirmedDest;
941 if (CreateEarnedNotarization(newNotarizationTx, notarizationInputs, prevTx, crossTx, lastConfirmed, nHeight, &confirmedInput, &confirmedDest))
943 // we have a valid, earned notarization transaction. we still need to complete it as follows:
944 // 1. Add an instant-spend input from the coinbase transaction to fund the finalization output
946 // 2. if we are spending finalization outputs, create an output of the same amount as a finalization output
947 // plus and any excess from the other, orphaned finalizations to the creator of the confirmed notarization
949 // 3. make sure the currency state is correct
951 // input should either be 0 or PBAAS_MINNOTARIZATIONOUTPUT + all finalized outputs
952 // we will add PBAAS_MINNOTARIZATIONOUTPUT from a coinbase instant spend in all cases and double that when it is 0 for block 1
953 for (const CTxIn& txin : newNotarizationTx.vin)
955 const uint256& prevHash = txin.prevout.hash;
956 const CCoins *pcoins = view.AccessCoins(prevHash);
957 pbaasTransparentIn += pcoins && (pcoins->vout.size() > txin.prevout.n) ? pcoins->vout[txin.prevout.n].nValue : 0;
960 // calculate the amount that will be sent to the confirmed notary address
961 // this will only be non-zero if we have finalized inputs
962 if (pbaasTransparentIn > 0)
964 pbaasTransparentOut = pbaasTransparentIn - PBAAS_MINNOTARIZATIONOUTPUT;
967 if (pbaasTransparentOut)
969 // if we are on a non-fungible chain, reward out must be unspendable
970 // make a normal output to the confirmed notary with the excess right behind the op_return
971 // TODO: make this a cc out to only allow spending on a fungible chain
972 CTxOut rewardOut = CTxOut(pbaasTransparentOut, GetScriptForDestination(confirmedDest));
973 newNotarizationTx.vout.insert(newNotarizationTx.vout.begin() + newNotarizationTx.vout.size() - 1, rewardOut);
976 // make the earned notarization coinbase output
978 cp = CCinit(&CC, EVAL_EARNEDNOTARIZATION);
980 // send this to EVAL_EARNEDNOTARIZATION address as a destination, locked by the default pubkey
981 pkCC = CPubKey(ParseHex(cp->CChexstr));
982 vKeys.push_back(CTxDestination(CKeyID(CCrossChainRPCData::GetConditionID(VERUS_CHAINID, EVAL_EARNEDNOTARIZATION))));
984 int64_t needed = nHeight == 1 ? PBAAS_MINNOTARIZATIONOUTPUT << 1 : PBAAS_MINNOTARIZATIONOUTPUT;
986 // output duplicate notarization as coinbase output for instant spend to notarization
987 // the output amount is considered part of the total value of this coinbase
988 CPBaaSNotarization pbn(newNotarizationTx);
989 notarizationOut = MakeCC1of1Vout(EVAL_EARNEDNOTARIZATION, needed, pkCC, vKeys, pbn);
990 coinbaseTx.vout.push_back(notarizationOut);
991 notarizationOutNum = coinbaseTx.vout.size() - 1;
993 // place the notarization
994 pblock->vtx.push_back(CTransaction(newNotarizationTx));
995 pblocktemplate->vTxFees.push_back(0);
996 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
997 nBlockSize += GetSerializeSize(newNotarizationTx, SER_NETWORK, PROTOCOL_VERSION);
998 notarizationTxIndex = pblock->vtx.size() - 1;
1001 else if (nHeight == 1)
1003 // failed to notarize at block 1
1007 // if we have a last confirmed notarization, then check for new imports from the notary chain
1008 if (lastConfirmed.vout.size())
1010 // we need to find the last unspent import transaction
1011 std::vector<CAddressUnspentDbEntry> unspentOutputs;
1015 // we cannot get export to a chain that has shut down
1016 // if the chain definition is spent, a chain is inactive
1017 if (GetAddressUnspent(CKeyID(CCrossChainRPCData::GetConditionID(ConnectedChains.NotaryChain().GetID(), EVAL_CROSSCHAIN_IMPORT)), 1, unspentOutputs))
1019 // if one spends the prior one, get the one that is not spent
1020 for (auto txidx : unspentOutputs)
1024 if (myGetTransaction(txidx.first.txhash, lastImportTx, blkHash) &&
1025 CCrossChainImport(lastImportTx).IsValid() &&
1026 (lastImportTx.IsCoinBase() ||
1027 (myGetTransaction(lastImportTx.vin[0].prevout.hash, itx, blkHash) &&
1028 CCrossChainImport(itx).IsValid())))
1036 if (found && pwalletMain)
1038 UniValue params(UniValue::VARR);
1039 UniValue param(UniValue::VOBJ);
1041 CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);
1043 for (i = 0; i < lastImportTx.vout.size(); i++)
1046 if (lastImportTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.evalCode == EVAL_CROSSCHAIN_IMPORT)
1048 txTemplate.vin.push_back(CTxIn(lastImportTx.GetHash(), (uint32_t)i));
1053 UniValue result = NullUniValue;
1054 if (i < lastImportTx.vout.size())
1056 param.push_back(Pair("name", thisChain.name));
1057 param.push_back(Pair("lastimporttx", EncodeHexTx(lastImportTx)));
1058 param.push_back(Pair("lastconfirmednotarization", EncodeHexTx(lastConfirmed)));
1059 param.push_back(Pair("importtxtemplate", EncodeHexTx(txTemplate)));
1060 param.push_back(Pair("totalimportavailable", lastImportTx.vout[txTemplate.vin[0].prevout.n].nValue));
1061 params.push_back(param);
1065 result = find_value(RPCCallRoot("getlatestimportsout", params), "result");
1066 } catch (exception e)
1068 printf("Could not get latest imports from notary chain\n");
1072 if (result.isArray() && result.size())
1074 LOCK(pwalletMain->cs_wallet);
1076 uint256 lastImportHash = lastImportTx.GetHash();
1077 for (int i = 0; i < result.size(); i++)
1080 if (result[i].isStr() && DecodeHexTx(itx, result[i].get_str()) && itx.vin.size() && itx.vin[0].prevout.hash == lastImportHash)
1082 // sign the transaction spending the last import and add to mempool
1083 CMutableTransaction mtx(itx);
1084 CCrossChainImport cci(lastImportTx);
1087 SignatureData sigdata;
1089 const CScript *pScriptPubKey;
1091 signSuccess = ProduceSignature(
1092 TransactionSignatureCreator(pwalletMain, &itx, 0, lastImportTx.vout[itx.vin[0].prevout.n].nValue, SIGHASH_ALL), lastImportTx.vout[itx.vin[0].prevout.n].scriptPubKey, sigdata, consensusBranchId);
1099 UpdateTransaction(mtx, 0, sigdata);
1100 itx = CTransaction(mtx);
1102 // commit to mempool and remove any conflicts
1103 std::list<CTransaction> removed;
1104 mempool.removeConflicts(itx, removed);
1105 CValidationState state;
1106 if (!myAddtomempool(itx, &state))
1108 LogPrintf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str());
1109 printf("Failed to add import transactions to the mempool due to: %s\n", state.GetRejectReason().c_str());
1110 break; // if we failed to add one, the others will fail to spend it
1114 lastImportHash = itx.GetHash();
1124 CAmount blockOnePremine = thisChain.GetTotalPreallocation();
1125 SetBlockOnePremine(blockOnePremine);
1126 totalEmission = GetBlockSubsidy(nHeight, consensusParams);
1127 blockSubsidy = totalEmission;
1128 currencyState.UpdateWithEmission(totalEmission);
1131 // coinbase should have all necessary outputs (TODO: timelock is not supported yet)
1132 uint32_t nCoinbaseSize = GetSerializeSize(coinbaseTx, SER_NETWORK, PROTOCOL_VERSION);
1133 nBlockSize += nCoinbaseSize;
1135 // now create the priority array, including market order reserve transactions, since they can always execute, leave limits for later
1136 bool haveReserveTransactions = false;
1137 uint32_t reserveExchangeLimitSize = 0;
1138 std::vector<CReserveTransactionDescriptor> limitOrders;
1140 // now add transactions from the mem pool to the priority heap
1141 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
1142 mi != mempool.mapTx.end(); ++mi)
1144 const CTransaction& tx = mi->GetTx();
1145 uint256 hash = tx.GetHash();
1147 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
1149 : pblock->GetBlockTime();
1151 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
1153 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
1157 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
1159 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
1163 COrphan* porphan = NULL;
1164 double dPriority = 0;
1165 CAmount nTotalIn = 0;
1166 CCurrencyValueMap totalReserveIn;
1167 bool fMissingInputs = false;
1168 CReserveTransactionDescriptor rtxd;
1169 bool isReserve = mempool.IsKnownReserveTransaction(hash, rtxd);
1171 if (tx.IsCoinImport())
1173 CAmount nValueIn = GetCoinImportValue(tx);
1174 nTotalIn += nValueIn;
1175 dPriority += (double)nValueIn * 1000; // flat multiplier
1177 // separate limit orders to be added later, we add them at the end, failed fill or kills are normal transactions, consider them reserve txs
1178 if (isReserve && rtxd.IsReserveExchange() && rtxd.IsLimit())
1180 // if we might expire, refresh and check again
1181 if (rtxd.IsFillOrKill())
1183 rtxd = CReserveTransactionDescriptor(tx, view, nHeight);
1184 mempool.PrioritiseReserveTransaction(rtxd, currencyState);
1187 // if is is a failed conversion, drop through
1188 if (!rtxd.IsFillOrKillFail())
1190 limitOrders.push_back(rtxd);
1191 reserveExchangeLimitSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
1197 nTotalIn += rtxd.nativeIn;
1198 totalReserveIn += rtxd.ReserveInputMap();
1199 if (rtxd.IsIdentity() && CNameReservation(tx).IsValid())
1201 nCurrentIDSize += GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
1202 if (nCurrentIDSize > nMaxIDSize)
1208 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1210 CAmount nValueIn = 0;
1211 CCurrencyValueMap reserveValueIn;
1213 // Read prev transaction
1214 if (!view.HaveCoins(txin.prevout.hash))
1216 // This should never happen; all transactions in the memory
1217 // pool should connect to either transactions in the chain
1218 // or other transactions in the memory pool.
1219 if (!mempool.mapTx.count(txin.prevout.hash))
1221 LogPrintf("ERROR: mempool transaction missing input\n");
1222 if (fDebug) assert("mempool transaction missing input" == 0);
1223 fMissingInputs = true;
1229 // Has to wait for dependencies
1232 // Use list for automatic deletion
1233 vOrphan.push_back(COrphan(&tx));
1234 porphan = &vOrphan.back();
1236 mapDependers[txin.prevout.hash].push_back(porphan);
1237 porphan->setDependsOn.insert(txin.prevout.hash);
1239 const CTransaction &otx = mempool.mapTx.find(txin.prevout.hash)->GetTx();
1240 // consider reserve outputs and set priority according to their value here as well
1243 totalReserveIn += otx.vout[txin.prevout.n].ReserveOutValue();
1245 nTotalIn += otx.vout[txin.prevout.n].nValue;
1248 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
1253 reserveValueIn = coins->vout[txin.prevout.n].ReserveOutValue();
1256 nValueIn = coins->vout[txin.prevout.n].nValue;
1257 int nConf = nHeight - coins->nHeight;
1259 dPriority += ((double)((reserveValueIn.valueMap.size() ? currencyState.ReserveToNative(reserveValueIn) : 0) + nValueIn)) * nConf;
1263 nTotalIn += nValueIn;
1264 totalReserveIn += reserveValueIn;
1267 nTotalIn += tx.GetShieldedValueIn();
1270 if (fMissingInputs) continue;
1272 // Priority is sum(valuein * age) / modified_txsize
1273 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
1274 dPriority = tx.ComputePriority(dPriority, nTxSize);
1276 CAmount nDeltaValueIn = nTotalIn + (totalReserveIn.valueMap.size() ? currencyState.ReserveToNative(totalReserveIn) : 0);
1277 CAmount nFeeValueIn = nDeltaValueIn;
1278 mempool.ApplyDeltas(hash, dPriority, nDeltaValueIn);
1280 CAmount nativeEquivalentOut = 0;
1282 // if there is reserve in, or this is a reserveexchange transaction, calculate fee properly
1283 if (isReserve && rtxd.ReserveOutputMap().valueMap.size())
1285 // if this has reserve currency out, convert it to native currency for fee calculation
1286 nativeEquivalentOut = currencyState.ReserveToNative(rtxd.ReserveOutputMap());
1289 CFeeRate feeRate(isReserve ? rtxd.AllFeesAsNative(currencyState) + currencyState.ReserveToNative(rtxd.ReserveConversionFeesMap()) + rtxd.nativeConversionFees :
1290 nFeeValueIn - (tx.GetValueOut() + nativeEquivalentOut), nTxSize);
1294 porphan->dPriority = dPriority;
1295 porphan->feeRate = feeRate;
1298 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
1302 // NOW -- REALLY START TO FILL THE BLOCK
1304 // estimate number of conversions, staking transaction size, and additional coinbase outputs that will be required
1306 int32_t maxPreLimitOrderBlockSize = nBlockMaxSize - std::min(nBlockMaxSize >> 2, reserveExchangeLimitSize);
1309 bool fSortedByFee = (nBlockPrioritySize <= 0);
1311 TxPriorityCompare comparer(fSortedByFee);
1312 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
1314 std::vector<int> reservePositions;
1316 // now loop and fill the block, leaving space for reserve exchange limit transactions
1317 while (!vecPriority.empty())
1319 // Take highest priority transaction off the priority queue:
1320 double dPriority = vecPriority.front().get<0>();
1321 CFeeRate feeRate = vecPriority.front().get<1>();
1322 const CTransaction& tx = *(vecPriority.front().get<2>());
1324 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
1325 vecPriority.pop_back();
1328 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
1329 if (nBlockSize + nTxSize >= maxPreLimitOrderBlockSize - autoTxSize) // room for extra autotx
1331 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d maxPreLimitOrderBlockSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)maxPreLimitOrderBlockSize);
1335 // Legacy limits on sigOps:
1336 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
1337 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
1339 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
1342 // Skip free transactions if we're past the minimum block size:
1343 const uint256& hash = tx.GetHash();
1344 double dPriorityDelta = 0;
1345 CAmount nFeeDelta = 0;
1346 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1347 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
1349 //fprintf(stderr,"fee rate skip\n");
1353 // Prioritise by fee once past the priority size or we run out of high-priority
1355 if (!fSortedByFee &&
1356 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
1358 fSortedByFee = true;
1359 comparer = TxPriorityCompare(fSortedByFee);
1360 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
1363 if (!view.HaveInputs(tx))
1365 //fprintf(stderr,"dont have inputs\n");
1369 CReserveTransactionDescriptor txDesc;
1370 bool isReserve = mempool.IsKnownReserveTransaction(hash, txDesc);
1372 nTxFees = view.GetValueIn(chainActive.LastTip()->GetHeight(),&interest,tx,chainActive.LastTip()->nTime)-tx.GetValueOut();
1374 nTxSigOps += GetP2SHSigOpCount(tx, view);
1375 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
1377 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
1381 // Note that flags: we don't want to set mempool/IsStandard()
1382 // policy here, but we still have to ensure that the block we
1383 // create only contains transactions that are valid in new blocks.
1384 CValidationState state;
1385 PrecomputedTransactionData txdata(tx);
1386 if (!ContextualCheckInputs(tx, state, view, nHeight, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1388 //fprintf(stderr,"context failure\n");
1392 UpdateCoins(tx, view, nHeight);
1396 nTxFees = 0; // we will adjust all reserve transaction fees when we get an accurate conversion rate
1397 reservePositions.push_back(nBlockTx);
1398 haveReserveTransactions = true;
1401 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
1402 sapling_tree.append(outDescription.cm);
1406 pblock->vtx.push_back(tx);
1407 pblocktemplate->vTxFees.push_back(nTxFees);
1408 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
1409 nBlockSize += nTxSize;
1411 nBlockSigOps += nTxSigOps;
1416 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
1419 // Add transactions that depend on this one to the priority queue
1420 if (mapDependers.count(hash))
1422 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
1424 if (!porphan->setDependsOn.empty())
1426 porphan->setDependsOn.erase(hash);
1427 if (porphan->setDependsOn.empty())
1429 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
1430 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
1437 // if we have reserve transactions or limit transactions to add:
1438 // 1. collect all the reserve transactions from the block and add them to the reserveFills vector
1439 // 2. add all limit transactions to the orders vector
1440 // 3. match orders to include all limit transactions that qualify and will fit
1441 CAmount conversionFees = 0;
1443 if (haveReserveTransactions)
1445 std::vector<CReserveTransactionDescriptor> reserveFills;
1446 std::vector<CReserveTransactionDescriptor> noFills;
1447 std::vector<const CReserveTransactionDescriptor *> expiredFillOrKills;
1448 std::vector<const CReserveTransactionDescriptor *> rejects;
1450 // identify all reserve transactions in the block to calculate fees
1451 for (int i = 0; i < reservePositions.size(); i++)
1453 CReserveTransactionDescriptor txDesc;
1454 if (mempool.IsKnownReserveTransaction(pblock->vtx[reservePositions[i]].GetHash(), txDesc))
1456 reserveFills.push_back(txDesc);
1460 // now, we need to have room for the transaction which will spend the coinbase
1461 // and output all conversions mined/staked
1462 newConversionOutputTx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);
1463 newConversionOutputTx.vin.resize(1); // placeholder for size calculation
1465 int64_t newBlockSize = nBlockSize;
1467 // TODO:PBAAS - NEED TO ADD SIGOPS LIMIT TO THIS FOR HARDENING
1468 CCoinbaseCurrencyState newState = currencyState.MatchOrders(limitOrders,
1476 nBlockMaxSize - autoTxSize,
1478 &newConversionOutputTx);
1480 // TODO:PBAAS - account for the edge case where we have too large expected fills and have no room
1481 // for transactions that we would otherwise take
1482 assert(reserveFills.size() >= reservePositions.size());
1484 // create the conversion transaction and all outputs indicated by every single mined transaction
1485 if (reserveFills.size())
1487 currencyState = newState;
1490 int oldRPSize = reservePositions.size();
1492 // add the rest of the reserve fills that have not yet been added to the block,
1493 for (int i = oldRPSize; i < reserveFills.size(); i++)
1495 // add these transactions to the block
1496 reservePositions.push_back(nBlockTx);
1497 pblock->vtx.push_back(*reserveFills[i].ptx);
1498 const CTransaction &tx = pblock->vtx.back();
1500 UpdateCoins(tx, view, nHeight);
1502 BOOST_FOREACH(const OutputDescription &outDescription, tx.vShieldedOutput) {
1503 sapling_tree.append(outDescription.cm);
1506 CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate);
1507 uint32_t nTxSigOps = GetLegacySigOpCount(tx);
1509 // size was already updated
1510 pblocktemplate->vTxFees.push_back(nTxFees);
1511 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
1513 nBlockSigOps += nTxSigOps;
1517 // update block size with the calculation from the function called, which includes all additional transactions,
1518 // but does not include the conversion transaction, since its final size is still unknown
1519 nBlockSize = newBlockSize;
1521 // fixup the transaction block template fees that were added before we knew the correct exchange rate and
1522 // add them to the block fee total
1523 for (int i = 0; i < oldRPSize; i++)
1525 assert(pblocktemplate->vTxFees.size() > reservePositions[i]);
1526 CAmount nTxFees = reserveFills[i].AllFeesAsNative(currencyState, exchangeRate);
1527 pblocktemplate->vTxFees[reservePositions[i]] = nTxFees;
1531 // remake the newConversionOutputTx, right now, it has dummy inputs and placeholder outputs, just remake it correctly
1532 newConversionOutputTx.vin.resize(1);
1533 newConversionOutputTx.vout.clear();
1534 conversionInputs.clear();
1536 // keep one placeholder for txCoinbase output as input and remake with the correct exchange rate
1537 for (auto fill : reserveFills)
1539 fill.AddConversionInOuts(newConversionOutputTx, conversionInputs, CCurrencyValueMap(currencyState.currencies, exchangeRate), ¤cyState);
1543 // first calculate and distribute block rewards, including fees in the minerOutputs vector
1544 CAmount rewardTotalShareAmount = 0;
1545 CAmount rewardTotal = blockSubsidy +
1546 currencyState.nativeConversionFees +
1547 currencyState.ReserveToNativeRaw(CCurrencyValueMap(currencyState.currencies, currencyState.conversionFees), exchangeRate) +
1548 currencyState.ReserveToNativeRaw(CCurrencyValueMap(currencyState.currencies, currencyState.fees), exchangeRate) +
1551 CAmount rewardLeft = notarizationTxIndex ? rewardTotal - notarizationOut.nValue : rewardTotal;
1553 // now that we have the total reward, update the coinbase outputs
1556 coinbaseTx.vout[0].nValue = rewardLeft;
1560 for (auto &outputShare : minerOutputs)
1562 rewardTotalShareAmount += outputShare.first;
1566 for (cbOutIdx = 0; cbOutIdx < minerOutputs.size(); cbOutIdx++)
1568 CAmount amount = (arith_uint256(rewardTotal) * arith_uint256(minerOutputs[cbOutIdx].first) / arith_uint256(rewardTotalShareAmount)).GetLow64();
1569 if (rewardLeft <= amount || (cbOutIdx + 1) == minerOutputs.size())
1571 amount = rewardLeft;
1573 rewardLeft -= amount;
1574 coinbaseTx.vout[cbOutIdx].nValue = amount;
1575 // the only valid CC output we currently support on coinbases is stake guard, which does not need to be modified for this
1579 // currencyStateOut - update currency state, output is present whether or not there is a conversion transaction
1580 // the transaction itself pays no fees, but all conversion fees are included for each conversion transaction between its input and this output
1581 if (currencyStateOut.scriptPubKey.size())
1584 currencyStateOut.scriptPubKey.IsPayToCryptoCondition(p);
1585 p.vData[0] = currencyState.AsVector();
1586 currencyStateOut.scriptPubKey.ReplaceCCParams(p);
1588 if (conversionInputs.size())
1590 CTransaction convertTx(newConversionOutputTx);
1591 currencyStateOut.nValue = convertTx.GetValueOut();
1593 auto reserveOutMap = convertTx.GetReserveValueOut();
1594 for (int i = 0; i < currencyState.currencies.size(); i++)
1596 auto it = reserveOutMap.valueMap.find(currencyState.currencies[i]);
1597 currencyState.reserveOut[i] = (it != reserveOutMap.valueMap.end()) ? it->second : 0;
1600 // the coinbase is not finished, store index placeholder here now and fixup hash later
1601 newConversionOutputTx.vin[0] = CTxIn(uint256(), currencyStateOutNum);
1605 newConversionOutputTx.vin.clear();
1606 newConversionOutputTx.vout.clear();
1609 coinbaseTx.vout[currencyStateOutNum] = currencyStateOut;
1612 // notarizationOut - update currencyState in notarization
1613 if (notarizationTxIndex)
1617 for (i = 0; i < newNotarizationTx.vout.size(); i++)
1619 if (newNotarizationTx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) && p.evalCode == EVAL_EARNEDNOTARIZATION)
1624 if (i >= newNotarizationTx.vout.size())
1626 LogPrintf("CreateNewBlock: bad notarization\n");
1627 fprintf(stderr,"CreateNewBlock: bad notarization\n");
1630 CPBaaSNotarization nz(p.vData[0]);
1631 nz.currencyState = currencyState;
1632 p.vData[0] = nz.AsVector();
1633 newNotarizationTx.vout[i].scriptPubKey.ReplaceCCParams(p);
1635 notarizationOut.scriptPubKey.IsPayToCryptoCondition(p);
1636 p.vData[0] = nz.AsVector();
1637 notarizationOut.scriptPubKey.ReplaceCCParams(p);
1639 coinbaseTx.vout[notarizationOutNum] = notarizationOut;
1641 // now that the coinbase is finished, finish and place conversion transaction before the stake transaction
1642 newNotarizationTx.vin.push_back(CTxIn(uint256(), notarizationOutNum));
1644 pblock->vtx[notarizationTxIndex] = newNotarizationTx;
1647 nLastBlockTx = nBlockTx;
1648 nLastBlockSize = nBlockSize;
1650 blocktime = std::max(pindexPrev->GetMedianTimePast(), GetAdjustedTime());
1652 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
1654 coinbaseTx.nExpiryHeight = 0;
1655 coinbaseTx.nLockTime = blocktime;
1657 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
1658 coinbaseTx.vout[0].nValue += 5000;
1661 // check if coinbase transactions must be time locked at current subsidy and prepend the time lock
1662 // to transaction if so, cast for GTE operator
1663 CAmount cbValueOut = 0;
1664 for (auto txout : coinbaseTx.vout)
1666 cbValueOut += txout.nValue;
1668 if (cbValueOut >= ASSETCHAINS_TIMELOCKGTE)
1670 int32_t opretlen, p2shlen, scriptlen;
1671 CScriptExt opretScript = CScriptExt();
1673 coinbaseTx.vout.push_back(CTxOut());
1675 // prepend time lock to original script unless original script is P2SH, in which case, we will leave the coins
1676 // protected only by the time lock rather than 100% inaccessible
1677 opretScript.AddCheckLockTimeVerify(komodo_block_unlocktime(nHeight));
1678 if (scriptPubKeyIn.IsPayToScriptHash() || scriptPubKeyIn.IsPayToCryptoCondition())
1680 LogPrintf("CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
1681 fprintf(stderr,"CreateNewBlock: attempt to add timelock to pay2sh or pay2cc\n");
1685 opretScript += scriptPubKeyIn;
1687 coinbaseTx.vout[0].scriptPubKey = CScriptExt().PayToScriptHash(CScriptID(opretScript));
1688 coinbaseTx.vout.back().scriptPubKey = CScriptExt().OpReturnScript(opretScript, OPRETTYPE_TIMELOCK);
1689 coinbaseTx.vout.back().nValue = 0;
1690 } // timelocks and commissions are currently incompatible due to validation complexity of the combination
1691 else if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
1693 int32_t i; uint8_t *ptr;
1694 coinbaseTx.vout.resize(2);
1695 coinbaseTx.vout[1].nValue = commission;
1696 coinbaseTx.vout[1].scriptPubKey.resize(35);
1697 ptr = (uint8_t *)&coinbaseTx.vout[1].scriptPubKey[0];
1699 for (i=0; i<33; i++)
1700 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
1701 ptr[34] = OP_CHECKSIG;
1702 //printf("autocreate commision vout\n");
1706 // finalize input of coinbase
1707 coinbaseTx.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(0)) + COINBASE_FLAGS;
1708 assert(coinbaseTx.vin[0].scriptSig.size() <= 100);
1711 pblock->vtx[0] = coinbaseTx;
1712 uint256 cbHash = coinbaseTx.GetHash();
1714 // if there is a conversion, update the correct coinbase hash and add it to the block
1715 // we also need to sign the conversion transaction
1716 if (newConversionOutputTx.vin.size() > 1)
1718 // put the coinbase into the updated coins, since we will spend from it
1719 UpdateCoins(pblock->vtx[0], view, nHeight);
1721 newConversionOutputTx.vin[0].prevout.hash = cbHash;
1723 CTransaction ncoTx(newConversionOutputTx);
1725 // sign transaction for cb output and conversions
1726 for (int i = 0; i < ncoTx.vin.size(); i++)
1729 SignatureData sigdata;
1731 const CScript *pScriptPubKey;
1733 // if this is our coinbase input, different signing
1736 pScriptPubKey = &conversionInputs[i - 1].scriptPubKey;
1737 value = conversionInputs[i - 1].nValue;
1741 pScriptPubKey = &coinbaseTx.vout[ncoTx.vin[i].prevout.n].scriptPubKey;
1742 value = coinbaseTx.vout[ncoTx.vin[i].prevout.n].nValue;
1745 signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ncoTx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId);
1749 if (ncoTx.vin[i].prevout.hash == coinbaseTx.GetHash())
1751 LogPrintf("Coinbase conversion source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str());
1752 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());
1754 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());
1755 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());
1758 UpdateTransaction(newConversionOutputTx, i, sigdata);
1762 UpdateCoins(newConversionOutputTx, view, nHeight);
1763 pblock->vtx.push_back(newConversionOutputTx);
1764 pblocktemplate->vTxFees.push_back(0);
1765 int txSigOps = GetLegacySigOpCount(newConversionOutputTx);
1766 pblocktemplate->vTxSigOps.push_back(txSigOps);
1767 nBlockSize += GetSerializeSize(newConversionOutputTx, SER_NETWORK, PROTOCOL_VERSION);
1769 nBlockSigOps += txSigOps;
1772 // if there is a stake transaction, add it to the very end
1775 UpdateCoins(txStaked, view, nHeight);
1776 pblock->vtx.push_back(txStaked);
1777 pblocktemplate->vTxFees.push_back(0);
1778 int txSigOps = GetLegacySigOpCount(txStaked);
1779 pblocktemplate->vTxSigOps.push_back(txSigOps);
1780 // already added to the block size above
1782 nBlockSigOps += txSigOps;
1785 extern CWallet *pwalletMain;
1787 // add final notarization and instant spend coinbase output hash fixup
1788 if (notarizationTxIndex)
1790 LOCK(pwalletMain->cs_wallet);
1792 newNotarizationTx.vin.back().prevout.hash = cbHash;
1794 CTransaction ntx(newNotarizationTx);
1796 for (int i = 0; i < ntx.vin.size(); i++)
1799 SignatureData sigdata;
1801 const CScript *pScriptPubKey;
1803 // if this is our coinbase input, we won't find it elsewhere
1804 if (i < notarizationInputs.size())
1806 pScriptPubKey = ¬arizationInputs[i].scriptPubKey;
1807 value = notarizationInputs[i].nValue;
1811 pScriptPubKey = &coinbaseTx.vout[ntx.vin[i].prevout.n].scriptPubKey;
1812 value = coinbaseTx.vout[ntx.vin[i].prevout.n].nValue;
1815 signSuccess = ProduceSignature(TransactionSignatureCreator(pwalletMain, &ntx, i, value, SIGHASH_ALL), *pScriptPubKey, sigdata, consensusBranchId);
1819 if (ntx.vin[i].prevout.hash == coinbaseTx.GetHash())
1821 LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str());
1822 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());
1824 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());
1825 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());
1828 UpdateTransaction(newNotarizationTx, i, sigdata);
1831 pblocktemplate->vTxSigOps[notarizationTxIndex] = GetLegacySigOpCount(newNotarizationTx);
1833 // put now signed notarization back in the block
1834 pblock->vtx[notarizationTxIndex] = newNotarizationTx;
1836 LogPrintf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str());
1837 //printf("Coinbase source tx id: %s\n", coinbaseTx.GetHash().GetHex().c_str());
1838 LogPrintf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, newNotarizationTx.GetHash().GetHex().c_str());
1839 //printf("adding notarization tx at height %d, index %d, id: %s\n", nHeight, notarizationTxIndex, mntx.GetHash().GetHex().c_str());
1842 for (auto input : newNotarizationTx.vin)
1844 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");
1845 //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");
1850 pblock->vtx[0] = coinbaseTx;
1851 pblocktemplate->vTxFees[0] = -nFees;
1852 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
1854 // if not Verus stake, setup nonce, otherwise, leave it alone
1855 if (!isStake || ASSETCHAINS_LWMAPOS == 0)
1858 arith_uint256 nonce = UintToArith256(GetRandHash());
1860 // Clear the top 16 and bottom 16 or 24 bits (for local use as thread flags and counters)
1861 nonce <<= ASSETCHAINS_NONCESHIFT[ASSETCHAINS_ALGO];
1863 pblock->nNonce = ArithToUint256(nonce);
1867 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
1868 pblock->hashFinalSaplingRoot = sapling_tree.root();
1870 // all Verus PoS chains need this data in the block at all times
1871 if ( ASSETCHAINS_LWMAPOS || ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || KOMODO_MININGTHREADS > 0 )
1873 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
1874 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
1877 if ( ASSETCHAINS_SYMBOL[0] == 0 && IS_KOMODO_NOTARY != 0 && My_notaryid >= 0 )
1880 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
1881 if ( pblock->nTime < pindexPrev->nTime+60 )
1882 pblock->nTime = pindexPrev->nTime + 60;
1883 if ( gpucount < 33 )
1885 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
1886 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
1887 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
1888 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
1889 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
1890 memcpy(&r,&randvals,sizeof(r));
1891 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
1893 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
1895 CAmount txfees = 5000;
1896 pblock->vtx.push_back(txNotary);
1897 pblocktemplate->vTxFees.push_back(txfees);
1898 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
1900 pblocktemplate->vTxFees[0] = -nFees;
1901 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
1902 //fprintf(stderr,"added notaryvin\n");
1906 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
1910 else if ( ASSETCHAINS_CC == 0 && pindexPrev != 0 && ASSETCHAINS_STAKED == 0 && (ASSETCHAINS_SYMBOL[0] != 0 || IS_KOMODO_NOTARY == 0 || My_notaryid < 0) )
1912 CValidationState state;
1913 //fprintf(stderr,"check validity\n");
1914 if ( !TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) // invokes CC checks
1916 throw std::runtime_error("CreateNewBlock(): TestBlockValidity failed");
1918 //fprintf(stderr,"valid\n");
1921 //fprintf(stderr,"done new block\n");
1923 // setup the header and buid the Merkle tree
1924 unsigned int extraNonce;
1925 IncrementExtraNonce(pblock, pindexPrev, extraNonce, true);
1927 return pblocktemplate.release();
1931 #ifdef ENABLE_WALLET
1932 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
1934 boost::optional<CScript> GetMinerScriptPubKey()
1938 CBitcoinAddress addr;
1939 if (addr.SetString(GetArg("-mineraddress", ""))) {
1940 addr.GetKeyID(keyID);
1942 #ifdef ENABLE_WALLET
1944 if (!reservekey.GetReservedKey(pubkey)) {
1945 return boost::optional<CScript>();
1947 keyID = pubkey.GetID();
1949 return boost::optional<CScript>();
1953 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
1954 return scriptPubKey;
1957 #ifdef ENABLE_WALLET
1958 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
1960 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
1962 CBlockTemplate* CreateNewBlockWithKey()
1964 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
1967 if (!scriptPubKey) {
1970 return CreateNewBlock(*scriptPubKey);
1973 //////////////////////////////////////////////////////////////////////////////
1978 #ifdef ENABLE_MINING
1980 class MinerAddressScript : public CReserveScript
1982 // CReserveScript requires implementing this function, so that if an
1983 // internal (not-visible) wallet address is used, the wallet can mark it as
1984 // important when a block is mined (so it then appears to the user).
1985 // If -mineraddress is set, the user already knows about and is managing the
1986 // address, so we don't need to do anything here.
1987 void KeepScript() {}
1990 void GetScriptForMinerAddress(boost::shared_ptr<CReserveScript> &script)
1992 CTxDestination addr = DecodeDestination(GetArg("-mineraddress", ""));
1993 if (!IsValidDestination(addr)) {
1997 boost::shared_ptr<MinerAddressScript> mAddr(new MinerAddressScript());
1998 CKeyID keyID = boost::get<CKeyID>(addr);
2001 script->reserveScript = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
2004 #ifdef ENABLE_WALLET
2005 //////////////////////////////////////////////////////////////////////////////
2010 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey, int32_t nHeight, int32_t gpucount, bool isStake)
2012 CPubKey pubkey; CScript scriptPubKey; uint8_t *ptr; int32_t i;
2013 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
2015 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
2017 else if ( USE_EXTERNAL_PUBKEY != 0 )
2019 //fprintf(stderr,"use notary pubkey\n");
2020 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
2026 if (!reservekey.GetReservedKey(pubkey))
2030 scriptPubKey.resize(35);
2031 ptr = (uint8_t *)pubkey.begin();
2032 scriptPubKey[0] = 33;
2033 for (i=0; i<33; i++)
2034 scriptPubKey[i+1] = ptr[i];
2035 scriptPubKey[34] = OP_CHECKSIG;
2036 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
2039 return CreateNewBlock(Params(), scriptPubKey, gpucount, isStake);
2042 void komodo_broadcast(const CBlock *pblock,int32_t limit)
2045 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
2048 BOOST_FOREACH(CNode* pnode, vNodes)
2050 if ( pnode->hSocket == INVALID_SOCKET )
2052 if ( (rand() % n) == 0 )
2054 pnode->PushMessage("block", *pblock);
2060 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
2063 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2065 static bool ProcessBlockFound(CBlock* pblock)
2066 #endif // ENABLE_WALLET
2068 int32_t height = chainActive.LastTip()->GetHeight()+1;
2069 LogPrintf("%s\n", pblock->ToString());
2070 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue), height);
2074 if (pblock->hashPrevBlock != chainActive.LastTip()->GetBlockHash())
2076 uint256 hash; int32_t i;
2077 hash = pblock->hashPrevBlock;
2078 for (i=31; i>=0; i--)
2079 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
2080 fprintf(stderr," <- prev (stale)\n");
2081 hash = chainActive.LastTip()->GetBlockHash();
2082 for (i=31; i>=0; i--)
2083 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
2084 fprintf(stderr," <- chainTip (stale)\n");
2086 return error("VerusMiner: generated block is stale");
2090 #ifdef ENABLE_WALLET
2091 // Remove key from key pool
2092 if ( IS_KOMODO_NOTARY == 0 )
2094 if (GetArg("-mineraddress", "").empty()) {
2095 // Remove key from key pool
2096 reservekey.KeepKey();
2099 // Track how many getdata requests this block gets
2102 //fprintf(stderr,"lock cs_wallet\n");
2103 LOCK(wallet.cs_wallet);
2104 wallet.mapRequestCount[pblock->GetHash()] = 0;
2107 //fprintf(stderr,"process new block\n");
2109 // Process this block (almost) the same as if we had received it from another node
2110 CValidationState state;
2111 if (!ProcessNewBlock(1, chainActive.LastTip()->GetHeight()+1, state, Params(), NULL, pblock, true, NULL))
2112 return error("VerusMiner: ProcessNewBlock, block not accepted");
2114 TrackMinedBlock(pblock->GetHash());
2115 komodo_broadcast(pblock,16);
2119 int32_t komodo_baseid(char *origbase);
2120 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
2121 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
2122 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
2123 extern int32_t KOMODO_LASTMINED,KOMODO_INSYNC;
2124 int32_t roundrobin_delay;
2125 arith_uint256 HASHTarget,HASHTarget_POW;
2126 int32_t komodo_longestchain();
2128 // wait for peers to connect
2129 void waitForPeers(const CChainParams &chainparams)
2131 if (chainparams.MiningRequiresPeers())
2135 boost::this_thread::interruption_point();
2137 fvNodesEmpty = vNodes.empty();
2139 int longestchain = komodo_longestchain();
2140 int lastlongest = 0;
2141 if (fvNodesEmpty || IsNotInSync() || (longestchain != 0 && longestchain > chainActive.LastTip()->GetHeight()))
2143 int loops = 0, blockDiff = 0, newDiff = 0;
2148 MilliSleep(1000 + rand() % 4000);
2149 boost::this_thread::interruption_point();
2151 fvNodesEmpty = vNodes.empty();
2156 else if ((newDiff = IsNotInSync()) > 0)
2158 if (blockDiff != newDiff)
2160 blockDiff = newDiff;
2172 else if (!fvNodesEmpty && !IsNotInSync() && longestchain > chainActive.LastTip()->GetHeight())
2174 // the only thing may be that we are seeing a long chain that we'll never get
2175 // don't wait forever
2176 if (lastlongest == 0)
2179 lastlongest = longestchain;
2182 } while (fvNodesEmpty || IsNotInSync());
2183 MilliSleep(100 + rand() % 400);
2188 #ifdef ENABLE_WALLET
2189 CBlockIndex *get_chainactive(int32_t height)
2191 if ( chainActive.LastTip() != 0 )
2193 if ( height <= chainActive.LastTip()->GetHeight() )
2196 return(chainActive[height]);
2198 // else fprintf(stderr,"get_chainactive height %d > active.%d\n",height,chainActive.Tip()->GetHeight());
2200 //fprintf(stderr,"get_chainactive null chainActive.Tip() height %d\n",height);
2205 * A separate thread to stake, while the miner threads mine.
2207 void static VerusStaker(CWallet *pwallet)
2209 LogPrintf("Verus staker thread started\n");
2210 RenameThread("verus-staker");
2212 const CChainParams& chainparams = Params();
2213 auto consensusParams = chainparams.GetConsensus();
2215 // Each thread has its own key
2216 CReserveKey reservekey(pwallet);
2218 // Each thread has its own counter
2219 unsigned int nExtraNonce = 0;
2221 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
2223 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
2226 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
2230 // try a nice clean peer connection to start
2231 CBlockIndex *pindexPrev, *pindexCur;
2233 pindexPrev = chainActive.LastTip();
2234 MilliSleep(5000 + rand() % 5000);
2235 waitForPeers(chainparams);
2236 pindexCur = chainActive.LastTip();
2237 } while (pindexPrev != pindexCur);
2240 static int32_t lastStakingHeight = 0;
2244 waitForPeers(chainparams);
2245 CBlockIndex* pindexPrev = chainActive.LastTip();
2248 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
2250 if ( Mining_height != pindexPrev->GetHeight()+1 )
2252 Mining_height = pindexPrev->GetHeight()+1;
2253 Mining_start = (uint32_t)time(NULL);
2256 // Check for stop or if block needs to be rebuilt
2257 boost::this_thread::interruption_point();
2259 // try to stake a block
2260 CBlockTemplate *ptr = NULL;
2262 // get height locally for consistent reporting
2263 int32_t newHeight = Mining_height;
2265 if (newHeight > VERUS_MIN_STAKEAGE)
2266 ptr = CreateNewBlockWithKey(reservekey, newHeight, 0, true);
2268 // TODO - putting this output here tends to help mitigate announcing a staking height earlier than
2269 // announcing the last block win when we start staking before a block's acceptance has been
2270 // acknowledged by the mining thread - a better solution may be to put the output on the submission
2272 if ( ptr == 0 && newHeight != lastStakingHeight )
2274 printf("Staking height %d for %s\n", newHeight, ASSETCHAINS_SYMBOL);
2276 lastStakingHeight = newHeight;
2280 // wait to try another staking block until after the tip moves again
2281 while ( chainActive.LastTip() == pindexPrev )
2286 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
2287 if (!pblocktemplate.get())
2289 if (GetArg("-mineraddress", "").empty()) {
2290 LogPrintf("Error in %s staker: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
2291 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2293 // Should never reach here, because -mineraddress validity is checked in init.cpp
2294 LogPrintf("Error in %s staker: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
2299 CBlock *pblock = &pblocktemplate->block;
2300 LogPrintf("Staking with %u transactions in block (%u bytes)\n", pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
2304 int64_t nStart = GetTime();
2306 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2308 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
2310 fprintf(stderr,"no nodes, attempting reconnect\n");
2315 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2317 fprintf(stderr,"timeout, retrying\n");
2321 if ( pindexPrev != chainActive.LastTip() )
2323 printf("Block %d added to chain\n", chainActive.LastTip()->GetHeight());
2328 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
2329 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
2331 uint256 hashTarget = ArithToUint256(arith_uint256().SetCompact(pblock->nBits));
2333 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
2335 UpdateTime(pblock, consensusParams, pindexPrev);
2337 if (ProcessBlockFound(pblock, *pwallet, reservekey))
2339 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2340 LogPrintf("Staked block found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
2341 printf("Found block %d \n", newHeight);
2342 printf("staking reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
2344 post.SetCompact(pblock->GetVerusPOSTarget());
2346 CTransaction &sTx = pblock->vtx[pblock->vtx.size()-1];
2347 printf("POS hash: %s \ntarget: %s\n",
2348 CTransaction::_GetVerusPOSHash(&(pblock->nNonce),
2349 sTx.vin[0].prevout.hash,
2350 sTx.vin[0].prevout.n,
2352 chainActive.GetVerusEntropyHash(Mining_height),
2353 sTx.vout[0].nValue).GetHex().c_str(),
2354 ArithToUint256(post).GetHex().c_str());
2355 if (unlockTime > newHeight && subsidy >= ASSETCHAINS_TIMELOCKGTE)
2356 printf("- timelocked until block %i\n", unlockTime);
2362 LogPrintf("Found block rejected at staking height: %d\n", Mining_height);
2363 printf("Found block rejected at staking height: %d\n", Mining_height);
2366 // Check for stop or if block needs to be rebuilt
2367 boost::this_thread::interruption_point();
2371 // In regression test mode, stop mining after a block is found.
2372 if (chainparams.MineBlocksOnDemand()) {
2373 throw boost::thread_interrupted();
2377 catch (const boost::thread_interrupted&)
2379 LogPrintf("VerusStaker terminated\n");
2382 catch (const std::runtime_error &e)
2384 LogPrintf("VerusStaker runtime error: %s\n", e.what());
2389 typedef bool (*minefunction)(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
2390 bool mine_verus_v2(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
2391 bool mine_verus_v2_port(CBlockHeader &bh, CVerusHashV2bWriter &vhw, uint256 &finalHash, uint256 &target, uint64_t start, uint64_t *count);
2393 void static BitcoinMiner_noeq(CWallet *pwallet)
2395 void static BitcoinMiner_noeq()
2398 LogPrintf("%s miner started\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2399 RenameThread("verushash-miner");
2401 #ifdef ENABLE_WALLET
2402 // Each thread has its own key
2403 CReserveKey reservekey(pwallet);
2406 miningTimer.clear();
2408 const CChainParams& chainparams = Params();
2409 // Each thread has its own counter
2410 unsigned int nExtraNonce = 0;
2412 uint8_t *script; uint64_t total,checktoshis; int32_t i,j;
2414 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->GetHeight() != 235300 &&
2417 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
2421 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2423 // try a nice clean peer connection to start
2424 CBlockIndex *pindexPrev, *pindexCur;
2426 pindexPrev = chainActive.LastTip();
2427 MilliSleep(5000 + rand() % 5000);
2428 waitForPeers(chainparams);
2429 pindexCur = chainActive.LastTip();
2430 } while (pindexPrev != pindexCur);
2432 // make sure that we have checked for PBaaS availability
2433 ConnectedChains.CheckVerusPBaaSAvailable();
2435 // this will not stop printing more than once in all cases, but it will allow us to print in all cases
2436 // and print duplicates rarely without having to synchronize
2437 static CBlockIndex *lastChainTipPrinted;
2438 static int32_t lastMiningHeight = 0;
2440 miningTimer.start();
2443 printf("Mining %s with %s\n", ASSETCHAINS_SYMBOL, ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2448 waitForPeers(chainparams);
2450 pindexPrev = chainActive.LastTip();
2452 // prevent forking on startup before the diff algorithm kicks in,
2453 // but only for a startup Verus test chain. PBaaS chains have the difficulty inherited from
2455 if (chainparams.MiningRequiresPeers() && ((IsVerusActive() && pindexPrev->GetHeight() < 50) || pindexPrev != chainActive.LastTip()))
2458 pindexPrev = chainActive.LastTip();
2459 MilliSleep(2000 + rand() % 2000);
2460 } while (pindexPrev != chainActive.LastTip());
2464 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
2465 if ( Mining_height != pindexPrev->GetHeight()+1 )
2467 Mining_height = pindexPrev->GetHeight()+1;
2468 if (lastMiningHeight != Mining_height)
2470 lastMiningHeight = Mining_height;
2471 printf("Mining %s at height %d\n", ASSETCHAINS_SYMBOL, Mining_height);
2473 Mining_start = (uint32_t)time(NULL);
2476 miningTimer.start();
2478 #ifdef ENABLE_WALLET
2479 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, Mining_height, 0);
2481 CBlockTemplate *ptr = CreateNewBlockWithKey();
2485 static uint32_t counter;
2486 if ( counter++ % 40 == 0 )
2488 if (!IsVerusActive() &&
2489 ConnectedChains.IsVerusPBaaSAvailable() &&
2490 ConnectedChains.notaryChainHeight < ConnectedChains.ThisChain().startBlock)
2492 fprintf(stderr,"Waiting for block %d on %s chain to start. Current block is %d\n", ConnectedChains.ThisChain().startBlock,
2493 ConnectedChains.notaryChain.chainDefinition.name.c_str(),
2494 ConnectedChains.notaryChainHeight);
2498 fprintf(stderr,"Unable to create valid block... will continue to try\n");
2505 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
2506 if (!pblocktemplate.get())
2508 if (GetArg("-mineraddress", "").empty()) {
2509 LogPrintf("Error in %s miner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n",
2510 ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2512 // Should never reach here, because -mineraddress validity is checked in init.cpp
2513 LogPrintf("Error in %s miner: Invalid %s -mineraddress\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], ASSETCHAINS_SYMBOL);
2516 miningTimer.clear();
2519 CBlock *pblock = &pblocktemplate->block;
2522 bool mergeMining = false;
2523 savebits = pblock->nBits;
2525 uint32_t solutionVersion = CConstVerusSolutionVector::Version(pblock->nSolution);
2526 if (pblock->nVersion != CBlockHeader::VERUS_V2)
2528 // must not be in sync
2529 printf("Mining on incorrect block version.\n");
2533 bool verusSolutionPBaaS = solutionVersion >= CActivationHeight::ACTIVATE_PBAAS;
2535 // v2 hash writer with adjustments for the current height
2536 CVerusHashV2bWriter ss2 = CVerusHashV2bWriter(SER_GETHASH, PROTOCOL_VERSION, solutionVersion);
2538 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2540 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
2542 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
2544 static uint32_t counter;
2545 if ( counter++ < 10 )
2546 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
2549 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
2553 // set our easiest target, if V3+, no need to rebuild the merkle tree
2554 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);
2556 // update PBaaS header
2557 if (verusSolutionPBaaS)
2559 if (!IsVerusActive() && ConnectedChains.IsVerusPBaaSAvailable())
2562 UniValue params(UniValue::VARR);
2563 UniValue error(UniValue::VARR);
2564 params.push_back(EncodeHexBlk(*pblock));
2565 params.push_back(ASSETCHAINS_SYMBOL);
2566 params.push_back(ASSETCHAINS_RPCHOST);
2567 params.push_back(ASSETCHAINS_RPCPORT);
2568 params.push_back(ASSETCHAINS_RPCCREDENTIALS);
2571 ConnectedChains.lastSubmissionFailed = false;
2572 params = RPCCallRoot("addmergedblock", params);
2573 params = find_value(params, "result");
2574 error = find_value(params, "error");
2575 } catch (std::exception e)
2577 printf("Failed to connect to %s chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
2578 params = UniValue(e.what());
2580 if (mergeMining = (params.isNull() && error.isNull()))
2582 printf("Merge mining %s with %s as the hashing chain\n", ASSETCHAINS_SYMBOL, ConnectedChains.notaryChain.chainDefinition.name.c_str());
2583 LogPrintf("Merge mining with %s as the hashing chain\n", ConnectedChains.notaryChain.chainDefinition.name.c_str());
2588 LogPrintf("Running %s miner with %u transactions in block (%u bytes)\n",ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO],
2589 pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
2593 int64_t nStart = GetTime();
2595 arith_uint256 hashTarget = arith_uint256().SetCompact(savebits);
2596 uint256 uintTarget = ArithToUint256(hashTarget);
2597 arith_uint256 ourTarget;
2598 ourTarget.SetCompact(pblock->nBits);
2602 if ( pindexPrev != chainActive.LastTip() )
2604 if (lastChainTipPrinted != chainActive.LastTip())
2606 lastChainTipPrinted = chainActive.LastTip();
2607 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
2614 uint64_t hashesToGo = 0;
2615 uint64_t totalDone = 0;
2617 int64_t subsidy = (int64_t)(pblock->vtx[0].vout[0].nValue);
2618 count = ((ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3) + 1) / ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
2619 CVerusHashV2 *vh2 = &ss2.GetState();
2621 verusclhasher &vclh = vh2->vclh;
2622 minefunction mine_verus;
2623 mine_verus = IsCPUVerusOptimized() ? &mine_verus_v2 : &mine_verus_v2_port;
2627 uint256 hashResult = uint256();
2629 unsigned char *curBuf;
2633 // loop for a few minutes before refreshing the block
2636 uint256 ourMerkle = pblock->hashMerkleRoot;
2637 if ( pindexPrev != chainActive.LastTip() )
2639 if (lastChainTipPrinted != chainActive.LastTip())
2641 lastChainTipPrinted = chainActive.LastTip();
2642 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
2643 arith_uint256 target;
2644 target.SetCompact(lastChainTipPrinted->nBits);
2645 if (ourMerkle == lastChainTipPrinted->hashMerkleRoot)
2647 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());
2648 printf("Found block %d \n", lastChainTipPrinted->GetHeight());
2649 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
2650 printf(" hash: %s\ntarget: %s\n", lastChainTipPrinted->GetBlockHash().GetHex().c_str(), ArithToUint256(ourTarget).GetHex().c_str());
2656 // if PBaaS is no longer available, we can't count on merge mining
2657 if (!ConnectedChains.IsVerusPBaaSAvailable())
2662 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2664 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
2666 fprintf(stderr,"no nodes, attempting reconnect\n");
2671 // update every few minutes, regardless
2672 int64_t elapsed = GetTime() - nStart;
2674 if ((mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && elapsed > 60) || elapsed > 60 || ConnectedChains.lastSubmissionFailed)
2679 boost::this_thread::interruption_point();
2686 // check NONCEMASK at a time
2687 for (uint64_t i = 0; i < count; i++)
2689 // 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
2690 // merge mined block, but not our own
2692 arith_uint256 arithHash;
2696 // pickup/remove any new/deleted headers
2697 if (ConnectedChains.dirty || (pblock->NumPBaaSHeaders() < ConnectedChains.mergeMinedChains.size() + 1))
2699 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce, verusSolutionPBaaS ? false : true, &savebits);
2701 hashTarget.SetCompact(savebits);
2702 uintTarget = ArithToUint256(hashTarget);
2705 // hashesToGo gets updated with actual number run for metrics
2706 hashesToGo = ASSETCHAINS_HASHESPERROUND[ASSETCHAINS_ALGO];
2707 uint64_t start = i * hashesToGo + totalDone;
2708 hashesToGo -= totalDone;
2710 if (verusSolutionPBaaS)
2712 // mine on canonical header for merge mining
2713 CPBaaSPreHeader savedHeader(*pblock);
2715 pblock->ClearNonCanonicalData();
2716 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
2717 savedHeader.SetBlockData(*pblock);
2721 blockFound = (*mine_verus)(*pblock, ss2, hashResult, uintTarget, start, &hashesToGo);
2724 arithHash = UintToArith256(hashResult);
2725 totalDone += hashesToGo + 1;
2726 if (blockFound && IsVerusActive())
2728 ConnectedChains.QueueNewBlockHeader(*pblock);
2729 if (arithHash > ourTarget)
2731 // all blocks qualified with this hash will be submitted
2732 // until we redo the block, we might as well not try again with anything over this hash
2733 hashTarget = arithHash;
2734 uintTarget = ArithToUint256(hashTarget);
2737 } while (blockFound && arithHash > ourTarget);
2739 if (!blockFound || arithHash > ourTarget)
2741 // Check for stop or if block needs to be rebuilt
2742 boost::this_thread::interruption_point();
2743 if ( pindexPrev != chainActive.LastTip() )
2745 if (lastChainTipPrinted != chainActive.LastTip())
2747 lastChainTipPrinted = chainActive.LastTip();
2748 printf("Block %d added to chain\n", lastChainTipPrinted->GetHeight());
2752 else if ((i + 1) < count)
2754 // if we'll not drop through, update hashcount
2756 miningTimer += totalDone;
2763 // Check for stop or if block needs to be rebuilt
2764 boost::this_thread::interruption_point();
2766 if (pblock->nSolution.size() != 1344)
2768 LogPrintf("ERROR: Block solution is not 1344 bytes as it should be");
2772 SetThreadPriority(THREAD_PRIORITY_NORMAL);
2774 int32_t unlockTime = komodo_block_unlocktime(Mining_height);
2776 #ifdef VERUSHASHDEBUG
2777 std::string validateStr = hashResult.GetHex();
2778 std::string hashStr = pblock->GetHash().GetHex();
2779 uint256 *bhalf1 = (uint256 *)vh2->CurBuffer();
2780 uint256 *bhalf2 = bhalf1 + 1;
2782 std::string hashStr = hashResult.GetHex();
2785 LogPrintf("Using %s algorithm:\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2786 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hashStr, ArithToUint256(ourTarget).GetHex());
2787 printf("Found block %d \n", Mining_height );
2788 printf("mining reward %.8f %s!\n", (double)subsidy / (double)COIN, ASSETCHAINS_SYMBOL);
2789 #ifdef VERUSHASHDEBUG
2790 printf(" hash: %s\n val: %s \ntarget: %s\n\n", hashStr.c_str(), validateStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
2791 printf("intermediate %lx\n", intermediate);
2792 printf("Curbuf: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
2793 bhalf1 = (uint256 *)verusclhasher_key.get();
2794 bhalf2 = bhalf1 + ((vh2->vclh.keyMask + 1) >> 5);
2795 printf(" Key: %s%s\n", bhalf1->GetHex().c_str(), bhalf2->GetHex().c_str());
2797 printf(" hash: %s\ntarget: %s", hashStr.c_str(), ArithToUint256(ourTarget).GetHex().c_str());
2799 if (unlockTime > Mining_height && subsidy >= ASSETCHAINS_TIMELOCKGTE)
2800 printf(" - timelocked until block %i\n", unlockTime);
2803 #ifdef ENABLE_WALLET
2804 ProcessBlockFound(pblock, *pwallet, reservekey);
2806 ProcessBlockFound(pblock);
2808 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2814 miningTimer += totalDone;
2819 // Check for stop or if block needs to be rebuilt
2820 boost::this_thread::interruption_point();
2822 if (vNodes.empty() && chainparams.MiningRequiresPeers())
2824 if ( Mining_height > ASSETCHAINS_MINHEIGHT )
2826 fprintf(stderr,"no nodes, attempting reconnect\n");
2831 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
2833 fprintf(stderr,"timeout, retrying\n");
2837 if ( pindexPrev != chainActive.LastTip() )
2839 if (lastChainTipPrinted != chainActive.LastTip())
2841 lastChainTipPrinted = chainActive.LastTip();
2842 printf("Block %d added to chain\n\n", lastChainTipPrinted->GetHeight());
2847 // totalDone now has the number of hashes actually done since starting on one nonce mask worth
2848 uint64_t hashesPerNonceMask = ASSETCHAINS_NONCEMASK[ASSETCHAINS_ALGO] >> 3;
2849 if (!(totalDone < hashesPerNonceMask))
2852 printf("%llu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
2854 printf("%lu mega hashes complete - working\n", (hashesPerNonceMask + 1) / 1048576);
2862 catch (const boost::thread_interrupted&)
2865 miningTimer.clear();
2866 LogPrintf("%s miner terminated\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO]);
2869 catch (const std::runtime_error &e)
2872 miningTimer.clear();
2873 LogPrintf("%s miner runtime error: %s\n", ASSETCHAINS_ALGORITHMS[ASSETCHAINS_ALGO], e.what());
2877 miningTimer.clear();
2880 void static BitcoinMiner(CWallet *pwallet)
2882 LogPrintf("KomodoMiner started\n");
2883 SetThreadPriority(THREAD_PRIORITY_LOWEST);
2884 RenameThread("komodo-miner");
2886 const CChainParams& chainparams = Params();
2888 #ifdef ENABLE_WALLET
2889 // Each thread has its own key
2890 CReserveKey reservekey(pwallet);
2893 // Each thread has its own counter
2894 unsigned int nExtraNonce = 0;
2896 unsigned int n = chainparams.GetConsensus().EquihashN();
2897 unsigned int k = chainparams.GetConsensus().EquihashK();
2898 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
2899 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) )
2902 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
2905 if ( ASSETCHAINS_SYMBOL[0] == 0 )
2906 komodo_chosennotary(¬aryid,chainActive.LastTip()->GetHeight(),NOTARY_PUBKEY33,(uint32_t)chainActive.LastTip()->GetBlockTime());
2907 if ( notaryid != My_notaryid )
2908 My_notaryid = notaryid;
2910 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
2912 //else solver = "default";
2913 assert(solver == "tromp" || solver == "default");
2914 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
2915 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2916 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
2918 bool cancelSolver = false;
2919 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
2920 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
2921 std::lock_guard<std::mutex> lock{m_cs};
2922 cancelSolver = true;
2925 miningTimer.start();
2928 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2929 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
2932 if (chainparams.MiningRequiresPeers()) //chainActive.LastTip()->GetHeight() != 235300 &&
2934 //if ( ASSETCHAINS_SEED != 0 && chainActive.LastTip()->GetHeight() < 100 )
2936 // Busy-wait for the network to come online so we don't waste time mining
2937 // on an obsolete chain. In regtest mode we expect to fly solo.
2943 fvNodesEmpty = vNodes.empty();
2945 if (!fvNodesEmpty && !IsInitialBlockDownload(chainparams))
2948 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
2951 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
2952 miningTimer.start();
2957 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
2958 CBlockIndex* pindexPrev = chainActive.LastTip();
2959 if ( Mining_height != pindexPrev->GetHeight()+1 )
2961 Mining_height = pindexPrev->GetHeight()+1;
2962 Mining_start = (uint32_t)time(NULL);
2964 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
2966 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
2970 #ifdef ENABLE_WALLET
2971 // notaries always default to staking
2972 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey, pindexPrev->GetHeight()+1, gpucount, ASSETCHAINS_STAKED != 0 && GetArg("-genproclimit", 0) == 0);
2974 CBlockTemplate *ptr = CreateNewBlockWithKey();
2978 static uint32_t counter;
2979 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
2980 fprintf(stderr,"created illegal block, retry\n");
2984 //fprintf(stderr,"get template\n");
2985 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
2986 if (!pblocktemplate.get())
2988 if (GetArg("-mineraddress", "").empty()) {
2989 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
2991 // Should never reach here, because -mineraddress validity is checked in init.cpp
2992 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
2996 CBlock *pblock = &pblocktemplate->block;
2997 if ( ASSETCHAINS_SYMBOL[0] != 0 )
2999 if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA )
3001 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
3003 static uint32_t counter;
3004 if ( counter++ < 10 )
3005 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
3008 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
3011 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
3012 //fprintf(stderr,"Running KomodoMiner.%s with %u transactions in block\n",solver.c_str(),(int32_t)pblock->vtx.size());
3013 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
3017 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();
3018 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
3019 savebits = pblock->nBits;
3020 HASHTarget = arith_uint256().SetCompact(savebits);
3021 roundrobin_delay = ROUNDROBIN_DELAY;
3022 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
3025 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
3027 int32_t dispflag = 0;
3028 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) &¬aryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 )
3030 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->GetHeight());
3031 if ( nonzpkeys > 0 )
3033 for (i=0; i<33; i++)
3034 if( pubkeys[0][i] != 0 )
3038 else externalflag = 0;
3039 if ( IS_KOMODO_NOTARY != 0 )
3041 for (i=1; i<66; i++)
3042 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
3044 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
3045 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
3046 for (j=gpucount=0; j<65; j++)
3048 if ( dispflag != 0 )
3051 fprintf(stderr,"%d ",mids[j]);
3052 else fprintf(stderr,"GPU ");
3054 if ( mids[j] == -1 )
3057 if ( dispflag != 0 )
3058 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));
3060 for (j=0; j<65; j++)
3061 if ( mids[j] == notaryid )
3064 KOMODO_LASTMINED = 0;
3065 } else fprintf(stderr,"no nonz pubkeys\n");
3066 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
3068 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
3069 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->GetHeight()+1);
3070 } //else fprintf(stderr,"duplicate at j.%d\n",j);
3071 } else Mining_start = 0;
3072 } else Mining_start = 0;
3073 if ( ASSETCHAINS_STAKED != 0 )
3075 int32_t percPoS,z; bool fNegative,fOverflow;
3076 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
3077 HASHTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow);
3078 if ( ASSETCHAINS_STAKED < 100 )
3080 for (z=31; z>=0; z--)
3081 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
3082 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
3087 if ( KOMODO_INSYNC == 0 )
3089 fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height);
3090 if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN )
3095 KOMODO_CHOSEN_ONE = 0;
3097 crypto_generichash_blake2b_state state;
3098 EhInitialiseState(n, k, state);
3099 // I = the block header minus nonce and solution.
3100 CEquihashInput I{*pblock};
3101 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3104 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
3106 crypto_generichash_blake2b_state curr_state;
3108 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
3109 // (x_1, x_2, ...) = A(I, V, n, k)
3110 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
3111 arith_uint256 hashTarget;
3112 if ( KOMODO_MININGTHREADS > 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
3113 hashTarget = HASHTarget_POW;
3114 else hashTarget = HASHTarget;
3115 std::function<bool(std::vector<unsigned char>)> validBlock =
3116 #ifdef ENABLE_WALLET
3117 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
3119 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
3121 (std::vector<unsigned char> soln) {
3122 int32_t z; arith_uint256 h; CBlock B;
3123 // Write the solution to the hash and compute the result.
3124 LogPrint("pow", "- Checking solution against target\n");
3125 pblock->nSolution = soln;
3126 solutionTargetChecks.increment();
3128 h = UintToArith256(B.GetHash());
3129 /*for (z=31; z>=16; z--)
3130 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
3131 fprintf(stderr," mined ");
3132 for (z=31; z>=16; z--)
3133 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
3134 fprintf(stderr," hashTarget ");
3135 for (z=31; z>=16; z--)
3136 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
3137 fprintf(stderr," POW\n");*/
3138 if ( h > hashTarget )
3140 //if ( ASSETCHAINS_STAKED != 0 && KOMODO_MININGTHREADS == 0 )
3144 if ( IS_KOMODO_NOTARY != 0 && B.nTime > GetAdjustedTime() )
3146 //fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
3147 while ( GetAdjustedTime() < B.nTime-2 )
3150 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
3152 fprintf(stderr,"new block arrived\n");
3157 if ( ASSETCHAINS_STAKED == 0 )
3159 if ( IS_KOMODO_NOTARY != 0 )
3162 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
3163 MilliSleep((rand() % (r * 1000)) + 1000);
3168 while ( B.nTime-57 > GetAdjustedTime() )
3171 if ( chainActive.LastTip()->GetHeight() >= Mining_height )
3174 uint256 tmp = B.GetHash();
3175 int32_t z; for (z=31; z>=0; z--)
3176 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
3177 fprintf(stderr," mined %s block %d!\n",ASSETCHAINS_SYMBOL,Mining_height);
3179 CValidationState state;
3180 if ( !TestBlockValidity(state, Params(), B, chainActive.LastTip(), true, false))
3182 h = UintToArith256(B.GetHash());
3183 for (z=31; z>=0; z--)
3184 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
3185 fprintf(stderr," Invalid block mined, try again\n");
3188 KOMODO_CHOSEN_ONE = 1;
3190 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3191 LogPrintf("KomodoMiner:\n");
3192 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
3193 #ifdef ENABLE_WALLET
3194 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
3196 if (ProcessBlockFound(&B)) {
3198 // Ignore chain updates caused by us
3199 std::lock_guard<std::mutex> lock{m_cs};
3200 cancelSolver = false;
3202 KOMODO_CHOSEN_ONE = 0;
3203 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3204 // In regression test mode, stop mining after a block is found.
3205 if (chainparams.MineBlocksOnDemand()) {
3206 // Increment here because throwing skips the call below
3207 ehSolverRuns.increment();
3208 throw boost::thread_interrupted();
3212 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
3213 std::lock_guard<std::mutex> lock{m_cs};
3214 return cancelSolver;
3217 // TODO: factor this out into a function with the same API for each solver.
3218 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
3219 // Create solver and initialize it.
3221 eq.setstate(&curr_state);
3223 // Initialization done, start algo driver.
3225 eq.xfull = eq.bfull = eq.hfull = 0;
3227 for (u32 r = 1; r < WK; r++) {
3228 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
3229 eq.xfull = eq.bfull = eq.hfull = 0;
3233 ehSolverRuns.increment();
3235 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
3236 for (size_t s = 0; s < eq.nsols; s++) {
3237 LogPrint("pow", "Checking solution %d\n", s+1);
3238 std::vector<eh_index> index_vector(PROOFSIZE);
3239 for (size_t i = 0; i < PROOFSIZE; i++) {
3240 index_vector[i] = eq.sols[s][i];
3242 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
3244 if (validBlock(sol_char)) {
3245 // If we find a POW solution, do not try other solutions
3246 // because they become invalid as we created a new block in blockchain.
3252 // If we find a valid block, we rebuild
3253 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
3254 ehSolverRuns.increment();
3256 int32_t i; uint256 hash = pblock->GetHash();
3257 for (i=0; i<32; i++)
3258 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
3259 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
3261 KOMODO_MAYBEMINED = Mining_height;
3264 } catch (EhSolverCancelledException&) {
3265 LogPrint("pow", "Equihash solver cancelled\n");
3266 std::lock_guard<std::mutex> lock{m_cs};
3267 cancelSolver = false;
3271 // Check for stop or if block needs to be rebuilt
3272 boost::this_thread::interruption_point();
3273 // Regtest mode doesn't require peers
3274 if ( FOUND_BLOCK != 0 )
3277 fprintf(stderr,"FOUND_BLOCK!\n");
3280 if (vNodes.empty() && chainparams.MiningRequiresPeers())
3282 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
3284 fprintf(stderr,"no nodes, break\n");
3288 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
3290 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
3291 fprintf(stderr,"0xffff, break\n");
3294 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3296 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
3297 fprintf(stderr,"timeout, break\n");
3300 if ( pindexPrev != chainActive.LastTip() )
3302 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
3303 fprintf(stderr,"Tip advanced, break\n");
3306 // Update nNonce and nTime
3307 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
3308 pblock->nBits = savebits;
3309 /*if ( NOTARY_PUBKEY33[0] == 0 )
3312 UpdateTime(pblock, consensusParams, pindexPrev);
3313 if (consensusParams.fPowAllowMinDifficultyBlocks)
3315 // Changing pblock->nTime can change work required on testnet:
3316 HASHTarget.SetCompact(pblock->nBits);
3317 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
3323 catch (const boost::thread_interrupted&)
3327 LogPrintf("KomodoMiner terminated\n");
3330 catch (const std::runtime_error &e)
3334 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
3341 #ifdef ENABLE_WALLET
3342 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
3344 void GenerateBitcoins(bool fGenerate, int nThreads)
3347 static CCriticalSection cs_startmining;
3349 LOCK(cs_startmining);
3350 if (!AreParamsInitialized())
3355 // if we are supposed to catch stake cheaters, there must be a valid sapling parameter, we need it at
3356 // initialization, and this is the first time we can get it. store the Sapling address here
3357 extern boost::optional<libzcash::SaplingPaymentAddress> cheatCatcher;
3358 extern std::string VERUS_CHEATCATCHER;
3359 libzcash::PaymentAddress addr = DecodePaymentAddress(VERUS_CHEATCATCHER);
3360 if (VERUS_CHEATCATCHER.size() > 0 && IsValidPaymentAddress(addr))
3364 cheatCatcher = boost::get<libzcash::SaplingPaymentAddress>(addr);
3371 VERUS_MINTBLOCKS = (VERUS_MINTBLOCKS && ASSETCHAINS_LWMAPOS != 0);
3373 if (fGenerate == true || VERUS_MINTBLOCKS)
3375 mapArgs["-gen"] = "1";
3377 if (VERUS_CHEATCATCHER.size() > 0)
3379 if (cheatCatcher == boost::none)
3381 LogPrintf("ERROR: -cheatcatcher parameter is invalid Sapling payment address\n");
3382 fprintf(stderr, "-cheatcatcher parameter is invalid Sapling payment address\n");
3386 LogPrintf("StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
3387 fprintf(stderr, "StakeGuard searching for double stakes on %s\n", VERUS_CHEATCATCHER.c_str());
3392 static boost::thread_group* minerThreads = NULL;
3395 nThreads = GetNumCores();
3397 if (minerThreads != NULL)
3399 minerThreads->interrupt_all();
3400 minerThreads->join_all();
3401 delete minerThreads;
3402 minerThreads = NULL;
3405 //fprintf(stderr,"nThreads.%d fGenerate.%d\n",(int32_t)nThreads,fGenerate);
3406 if ( nThreads == 0 && ASSETCHAINS_STAKED )
3412 minerThreads = new boost::thread_group();
3414 // add the PBaaS thread when mining or staking
3415 minerThreads->create_thread(boost::bind(&CConnectedChains::SubmissionThreadStub));
3417 #ifdef ENABLE_WALLET
3418 if (VERUS_MINTBLOCKS && pwallet != NULL)
3420 minerThreads->create_thread(boost::bind(&VerusStaker, pwallet));
3424 for (int i = 0; i < nThreads; i++) {
3426 #ifdef ENABLE_WALLET
3427 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
3428 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
3430 minerThreads->create_thread(boost::bind(&BitcoinMiner_noeq, pwallet));
3432 if (ASSETCHAINS_ALGO == ASSETCHAINS_EQUIHASH)
3433 minerThreads->create_thread(&BitcoinMiner);
3435 minerThreads->create_thread(&BitcoinMiner_noeq);
3440 #endif // ENABLE_MINING