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