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