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