1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "pow/tromp/equi_miner.h"
13 #include "chainparams.h"
14 #include "importcoin.h"
15 #include "consensus/consensus.h"
16 #include "consensus/upgrades.h"
17 #include "consensus/validation.h"
19 #include "crypto/equihash.h"
26 #include "primitives/transaction.h"
29 #include "ui_interface.h"
31 #include "utilmoneystr.h"
33 #include "wallet/wallet.h"
38 #include <boost/thread.hpp>
39 #include <boost/tuple/tuple.hpp>
47 //////////////////////////////////////////////////////////////////////////////
53 // Unconfirmed transactions in the memory pool often depend on other
54 // transactions in the memory pool. When we select transactions from the
55 // pool, we select by highest priority or fee rate, so we might consider
56 // transactions that depend on transactions that aren't yet in the block.
57 // The COrphan class keeps track of these 'temporary orphans' while
58 // CreateBlock is figuring out which transactions to include.
63 const CTransaction* ptx;
64 set<uint256> setDependsOn;
68 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
73 uint64_t nLastBlockTx = 0;
74 uint64_t nLastBlockSize = 0;
76 // We want to sort transactions by priority and fee rate, so:
77 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
78 class TxPriorityCompare
83 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
85 bool operator()(const TxPriority& a, const TxPriority& b)
89 if (a.get<1>() == b.get<1>())
90 return a.get<0>() < b.get<0>();
91 return a.get<1>() < b.get<1>();
95 if (a.get<0>() == b.get<0>())
96 return a.get<1>() < b.get<1>();
97 return a.get<0>() < b.get<0>();
102 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
104 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
107 #include "komodo_defs.h"
109 extern int32_t ASSETCHAINS_SEED,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAIN_INIT,KOMODO_INITDONE,KOMODO_ON_DEMAND,KOMODO_INITDONE,KOMODO_PASSPORT_INITDONE;
110 extern uint64_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED;
111 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
112 extern std::string NOTARY_PUBKEY,ASSETCHAINS_OVERRIDE_PUBKEY;
113 void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len);
115 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
116 uint32_t Mining_start,Mining_height;
117 int32_t My_notaryid = -1;
118 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
119 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
120 //uint64_t komodo_paxtotal();
121 int32_t komodo_baseid(char *origbase);
122 //int32_t komodo_is_issuer();
123 //int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
124 //int32_t komodo_isrealtime(int32_t *kmdheightp);
125 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
126 uint64_t komodo_commission(const CBlock *block);
127 int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig);
128 int32_t komodo_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33);
130 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn,int32_t gpucount)
132 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
135 gpucount = KOMODO_MAXGPUCOUNT;
136 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
137 if(!pblocktemplate.get())
139 fprintf(stderr,"pblocktemplate.get() failure\n");
142 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
143 /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
145 isrealtime = komodo_isrealtime(&kmdheight);
146 deposits = komodo_paxtotal();
147 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
149 deposits = komodo_paxtotal();
150 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
152 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
154 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
156 fprintf(stderr,"start CreateNewBlock %s initdone.%d deposit %.8f mempool.%d RT.%u KOMODO_ON_DEMAND.%d\n",ASSETCHAINS_SYMBOL,KOMODO_INITDONE,(double)komodo_paxtotal()/COIN,(int32_t)mempool.GetTotalTxSize(),isrealtime,KOMODO_ON_DEMAND);
161 KOMODO_ON_DEMAND = 0;
162 if ( 0 && deposits != 0 )
163 printf("miner KOMODO_DEPOSIT %llu pblock->nHeight %d mempool.GetTotalTxSize(%d)\n",(long long)komodo_paxtotal(),(int32_t)chainActive.Tip()->nHeight,(int32_t)mempool.GetTotalTxSize());
165 // -regtest only: allow overriding block.nVersion with
166 // -blockversion=N to test forking scenarios
167 if (Params().MineBlocksOnDemand())
168 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
170 // Add dummy coinbase tx as first transaction
171 pblock->vtx.push_back(CTransaction());
172 pblocktemplate->vTxFees.push_back(-1); // updated at end
173 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
175 // Largest block you're willing to create:
176 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
177 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
178 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
180 // How much of the block should be dedicated to high-priority transactions,
181 // included regardless of the fees they pay
182 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
183 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
185 // Minimum block size you want to create; block will be filled with free transactions
186 // until there are no more or the block reaches this size:
187 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
188 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
190 // Collect memory pool transactions into the block
194 LOCK2(cs_main, mempool.cs);
195 CBlockIndex* pindexPrev = chainActive.Tip();
196 const int nHeight = pindexPrev->nHeight + 1;
197 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
198 pblock->nTime = GetAdjustedTime();
199 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
200 CCoinsViewCache view(pcoinsTip);
201 uint32_t expired; uint64_t commission;
203 // Priority order to process transactions
204 list<COrphan> vOrphan; // list memory doesn't move
205 map<uint256, vector<COrphan*> > mapDependers;
206 bool fPrintPriority = GetBoolArg("-printpriority", false);
208 // This vector will be sorted into a priority queue:
209 vector<TxPriority> vecPriority;
210 vecPriority.reserve(mempool.mapTx.size());
211 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
212 mi != mempool.mapTx.end(); ++mi)
214 const CTransaction& tx = mi->GetTx();
216 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
218 : pblock->GetBlockTime();
220 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
222 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
225 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
227 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
230 COrphan* porphan = NULL;
231 double dPriority = 0;
232 CAmount nTotalIn = 0;
233 bool fMissingInputs = false;
234 if (tx.IsCoinImport())
236 CAmount nValueIn = GetCoinImportValue(tx);
237 nTotalIn += nValueIn;
238 dPriority += (double)nValueIn * 1000; // flat multiplier
240 BOOST_FOREACH(const CTxIn& txin, tx.vin)
242 // Read prev transaction
243 if (!view.HaveCoins(txin.prevout.hash))
245 // This should never happen; all transactions in the memory
246 // pool should connect to either transactions in the chain
247 // or other transactions in the memory pool.
248 if (!mempool.mapTx.count(txin.prevout.hash))
250 LogPrintf("ERROR: mempool transaction missing input\n");
251 if (fDebug) assert("mempool transaction missing input" == 0);
252 fMissingInputs = true;
258 // Has to wait for dependencies
261 // Use list for automatic deletion
262 vOrphan.push_back(COrphan(&tx));
263 porphan = &vOrphan.back();
265 mapDependers[txin.prevout.hash].push_back(porphan);
266 porphan->setDependsOn.insert(txin.prevout.hash);
267 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
270 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
273 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
274 nTotalIn += nValueIn;
276 int nConf = nHeight - coins->nHeight;
278 dPriority += (double)nValueIn * nConf;
280 nTotalIn += tx.GetJoinSplitValueIn();
283 if (fMissingInputs) continue;
285 // Priority is sum(valuein * age) / modified_txsize
286 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
287 dPriority = tx.ComputePriority(dPriority, nTxSize);
289 uint256 hash = tx.GetHash();
290 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
292 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
296 porphan->dPriority = dPriority;
297 porphan->feeRate = feeRate;
300 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
303 // Collect transactions into block
304 uint64_t nBlockSize = 1000;
305 uint64_t nBlockTx = 0;
307 int nBlockSigOps = 100;
308 bool fSortedByFee = (nBlockPrioritySize <= 0);
310 TxPriorityCompare comparer(fSortedByFee);
311 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
313 while (!vecPriority.empty())
315 // Take highest priority transaction off the priority queue:
316 double dPriority = vecPriority.front().get<0>();
317 CFeeRate feeRate = vecPriority.front().get<1>();
318 const CTransaction& tx = *(vecPriority.front().get<2>());
320 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
321 vecPriority.pop_back();
324 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
325 if (nBlockSize + nTxSize >= nBlockMaxSize-512) // room for extra autotx
327 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
331 // Legacy limits on sigOps:
332 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
333 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
335 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
338 // Skip free transactions if we're past the minimum block size:
339 const uint256& hash = tx.GetHash();
340 double dPriorityDelta = 0;
341 CAmount nFeeDelta = 0;
342 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
343 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
345 //fprintf(stderr,"fee rate skip\n");
348 // Prioritise by fee once past the priority size or we run out of high-priority
351 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
354 comparer = TxPriorityCompare(fSortedByFee);
355 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
358 if (!view.HaveInputs(tx))
360 //fprintf(stderr,"dont have inputs\n");
363 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
365 nTxSigOps += GetP2SHSigOpCount(tx, view);
366 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
368 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
371 // Note that flags: we don't want to set mempool/IsStandard()
372 // policy here, but we still have to ensure that the block we
373 // create only contains transactions that are valid in new blocks.
374 CValidationState state;
375 PrecomputedTransactionData txdata(tx);
376 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
378 //fprintf(stderr,"context failure\n");
381 UpdateCoins(tx, view, nHeight);
384 pblock->vtx.push_back(tx);
385 pblocktemplate->vTxFees.push_back(nTxFees);
386 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
387 nBlockSize += nTxSize;
389 nBlockSigOps += nTxSigOps;
394 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
397 // Add transactions that depend on this one to the priority queue
398 if (mapDependers.count(hash))
400 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
402 if (!porphan->setDependsOn.empty())
404 porphan->setDependsOn.erase(hash);
405 if (porphan->setDependsOn.empty())
407 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
408 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
415 nLastBlockTx = nBlockTx;
416 nLastBlockSize = nBlockSize;
417 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
418 //pblock->nTime = blocktime + 1;
419 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
420 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
421 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
423 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
424 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
425 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
428 if ( (int32_t)chainActive.Tip()->nHeight+1 > 100 && GetAdjustedTime() < blocktime-13 )
430 pblock->vtx.push_back(txStaked);
431 pblocktemplate->vTxFees.push_back(txfees);
432 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
434 pblock->nTime = blocktime;
435 printf("staking PoS ht.%d t%u lag.%u\n",(int32_t)chainActive.Tip()->nHeight+1,blocktime,(uint32_t)(GetAdjustedTime() - (blocktime-13)));
436 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
439 // Create coinbase tx
440 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
442 txNew.vin[0].prevout.SetNull();
443 txNew.vout.resize(1);
444 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
445 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
446 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
447 txNew.nExpiryHeight = 0;
449 txNew.vout[0].nValue += nFees;
450 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
452 pblock->vtx[0] = txNew;
453 if ( nHeight > 1 && ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
455 int32_t i; uint8_t *ptr;
456 txNew.vout.resize(2);
457 txNew.vout[1].nValue = commission;
458 txNew.vout[1].scriptPubKey.resize(35);
459 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
462 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
463 ptr[34] = OP_CHECKSIG;
464 //printf("autocreate commision vout\n");
465 pblock->vtx[0] = txNew;
467 pblocktemplate->vTxFees[0] = -nFees;
469 arith_uint256 nonce = UintToArith256(GetRandHash());
470 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
473 pblock->nNonce = ArithToUint256(nonce);
476 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
477 pblock->hashReserved = uint256();
478 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
480 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
481 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
483 pblock->nSolution.clear();
484 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
485 if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && My_notaryid >= 0 )
488 CMutableTransaction txNotary = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
489 if ( pblock->nTime < pindexPrev->nTime+60 )
490 pblock->nTime = pindexPrev->nTime + 60;
493 uint8_t tmpbuffer[40]; uint32_t r; int32_t n=0; uint256 randvals;
494 memcpy(&tmpbuffer[n],&My_notaryid,sizeof(My_notaryid)), n += sizeof(My_notaryid);
495 memcpy(&tmpbuffer[n],&Mining_height,sizeof(Mining_height)), n += sizeof(Mining_height);
496 memcpy(&tmpbuffer[n],&pblock->hashPrevBlock,sizeof(pblock->hashPrevBlock)), n += sizeof(pblock->hashPrevBlock);
497 vcalc_sha256(0,(uint8_t *)&randvals,tmpbuffer,n);
498 memcpy(&r,&randvals,sizeof(r));
499 pblock->nTime += (r % (33 - gpucount)*(33 - gpucount));
501 if ( komodo_notaryvin(txNotary,NOTARY_PUBKEY33) > 0 )
503 CAmount txfees = 5000;
504 pblock->vtx.push_back(txNotary);
505 pblocktemplate->vTxFees.push_back(txfees);
506 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txNotary));
508 pblocktemplate->vTxFees[0] = -nFees;
509 //*(uint64_t *)(&pblock->vtx[0].vout[0].nValue) += txfees;
510 //fprintf(stderr,"added notaryvin\n");
514 fprintf(stderr,"error adding notaryvin, need to create 0.0001 utxos\n");
520 CValidationState state;
521 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
523 //static uint32_t counter;
524 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
525 // fprintf(stderr,"warning: miner testblockvalidity failed\n");
531 return pblocktemplate.release();
536 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
538 boost::optional<CScript> GetMinerScriptPubKey()
542 CBitcoinAddress addr;
543 if (addr.SetString(GetArg("-mineraddress", ""))) {
544 addr.GetKeyID(keyID);
548 if (!reservekey.GetReservedKey(pubkey)) {
549 return boost::optional<CScript>();
551 keyID = pubkey.GetID();
553 return boost::optional<CScript>();
557 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
562 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
564 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
566 CBlockTemplate* CreateNewBlockWithKey()
568 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
574 return CreateNewBlock(*scriptPubKey);
577 //////////////////////////////////////////////////////////////////////////////
584 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
586 // Update nExtraNonce
587 static uint256 hashPrevBlock;
588 if (hashPrevBlock != pblock->hashPrevBlock)
591 hashPrevBlock = pblock->hashPrevBlock;
594 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
595 CMutableTransaction txCoinbase(pblock->vtx[0]);
596 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
597 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
599 pblock->vtx[0] = txCoinbase;
600 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
604 //////////////////////////////////////////////////////////////////////////////
609 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey,int32_t nHeight,int32_t gpucount)
611 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
612 if ( nHeight == 1 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 )
614 scriptPubKey = CScript() << ParseHex(ASSETCHAINS_OVERRIDE_PUBKEY) << OP_CHECKSIG;
616 else if ( USE_EXTERNAL_PUBKEY != 0 )
618 //fprintf(stderr,"use notary pubkey\n");
619 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
623 if (!reservekey.GetReservedKey(pubkey))
627 scriptPubKey.resize(35);
628 ptr = (uint8_t *)pubkey.begin();
629 script = (uint8_t *)scriptPubKey.data();
632 script[i+1] = ptr[i];
633 script[34] = OP_CHECKSIG;
634 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
636 return CreateNewBlock(scriptPubKey,gpucount);
639 void komodo_broadcast(CBlock *pblock,int32_t limit)
642 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
645 BOOST_FOREACH(CNode* pnode, vNodes)
647 if ( pnode->hSocket == INVALID_SOCKET )
649 if ( (rand() % n) == 0 )
651 pnode->PushMessage("block", *pblock);
657 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
660 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
662 static bool ProcessBlockFound(CBlock* pblock)
663 #endif // ENABLE_WALLET
665 LogPrintf("%s\n", pblock->ToString());
666 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
671 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
673 uint256 hash; int32_t i;
674 hash = pblock->hashPrevBlock;
675 for (i=31; i>=0; i--)
676 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
677 fprintf(stderr," <- prev (stale)\n");
678 hash = chainActive.Tip()->GetBlockHash();
679 for (i=31; i>=0; i--)
680 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
681 fprintf(stderr," <- chainTip (stale)\n");
683 return error("KomodoMiner: generated block is stale");
688 // Remove key from key pool
689 if ( IS_KOMODO_NOTARY == 0 )
691 if (GetArg("-mineraddress", "").empty()) {
692 // Remove key from key pool
693 reservekey.KeepKey();
696 // Track how many getdata requests this block gets
699 LOCK(wallet.cs_wallet);
700 wallet.mapRequestCount[pblock->GetHash()] = 0;
704 // Process this block the same as if we had received it from another node
705 CValidationState state;
706 if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
707 return error("KomodoMiner: ProcessNewBlock, block not accepted");
709 TrackMinedBlock(pblock->GetHash());
710 komodo_broadcast(pblock,16);
714 int32_t komodo_baseid(char *origbase);
715 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
716 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
717 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
718 extern int32_t KOMODO_LASTMINED;
719 int32_t roundrobin_delay;
720 arith_uint256 HASHTarget,HASHTarget_POW;
723 void static BitcoinMiner(CWallet *pwallet)
725 void static BitcoinMiner()
728 LogPrintf("KomodoMiner started\n");
729 SetThreadPriority(THREAD_PRIORITY_LOWEST);
730 RenameThread("komodo-miner");
731 const CChainParams& chainparams = Params();
734 // Each thread has its own key
735 CReserveKey reservekey(pwallet);
738 // Each thread has its own counter
739 unsigned int nExtraNonce = 0;
741 unsigned int n = chainparams.EquihashN();
742 unsigned int k = chainparams.EquihashK();
743 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,gpucount=KOMODO_MAXGPUCOUNT,notaryid = -1;
744 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
747 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
750 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
751 if ( notaryid != My_notaryid )
752 My_notaryid = notaryid;
754 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
756 //else solver = "default";
757 assert(solver == "tromp" || solver == "default");
758 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
759 if ( ASSETCHAINS_SYMBOL[0] != 0 )
760 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
762 bool cancelSolver = false;
763 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
764 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
765 std::lock_guard<std::mutex> lock{m_cs};
772 if ( ASSETCHAINS_SYMBOL[0] != 0 )
773 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
776 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
778 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
780 // Busy-wait for the network to come online so we don't waste time mining
781 // on an obsolete chain. In regtest mode we expect to fly solo.
787 fvNodesEmpty = vNodes.empty();
789 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
792 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
795 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
801 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
802 CBlockIndex* pindexPrev = chainActive.Tip();
803 if ( Mining_height != pindexPrev->nHeight+1 )
805 Mining_height = pindexPrev->nHeight+1;
806 Mining_start = (uint32_t)time(NULL);
808 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
810 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
814 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey,pindexPrev->nHeight+1,gpucount);
816 CBlockTemplate *ptr = CreateNewBlockWithKey();
820 static uint32_t counter;
821 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
822 fprintf(stderr,"created illegal block, retry\n");
826 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
827 if (!pblocktemplate.get())
829 if (GetArg("-mineraddress", "").empty()) {
830 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
832 // Should never reach here, because -mineraddress validity is checked in init.cpp
833 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
837 CBlock *pblock = &pblocktemplate->block;
838 if ( ASSETCHAINS_SYMBOL[0] != 0 )
840 if ( ASSETCHAINS_REWARD == 0 )
842 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
844 static uint32_t counter;
845 if ( counter++ < 10 )
846 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
849 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
852 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
853 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
857 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
858 savebits = pblock->nBits;
859 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
860 roundrobin_delay = ROUNDROBIN_DELAY;
861 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
864 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 || Mining_height > 1000000 )
866 int32_t dispflag = 0;
867 if ( notaryid <= 3 || notaryid == 32 || (notaryid >= 43 && notaryid <= 45) ||notaryid == 51 || notaryid == 52 || notaryid == 56 || notaryid == 57 || notaryid == 62 )
869 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
873 if( pubkeys[0][i] != 0 )
877 else externalflag = 0;
878 if ( NOTARY_PUBKEY33[0] != 0 )
881 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
883 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
884 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
885 for (j=gpucount=0; j<65; j++)
890 fprintf(stderr,"%d ",mids[j]);
891 else fprintf(stderr,"GPU ");
897 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL));
900 if ( mids[j] == notaryid )
903 KOMODO_LASTMINED = 0;
904 } else fprintf(stderr,"no nonz pubkeys\n");
905 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
907 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
908 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
909 } //else fprintf(stderr,"duplicate at j.%d\n",j);
910 } else Mining_start = 0;
911 } else Mining_start = 0;
912 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
915 /*if ( Mining_height <= 100 )
920 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
921 for (z=31; z>=0; z--)
922 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
923 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
927 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
929 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
934 KOMODO_CHOSEN_ONE = 0;
935 crypto_generichash_blake2b_state state;
936 EhInitialiseState(n, k, state);
937 // I = the block header minus nonce and solution.
938 CEquihashInput I{*pblock};
939 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
942 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
944 crypto_generichash_blake2b_state curr_state;
946 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
947 // (x_1, x_2, ...) = A(I, V, n, k)
948 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
949 arith_uint256 hashTarget;
950 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 && Mining_height > 10 )
951 hashTarget = HASHTarget_POW;
952 else hashTarget = HASHTarget;
953 std::function<bool(std::vector<unsigned char>)> validBlock =
955 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
957 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
959 (std::vector<unsigned char> soln) {
960 int32_t z; arith_uint256 h; CBlock B;
961 // Write the solution to the hash and compute the result.
962 LogPrint("pow", "- Checking solution against target\n");
963 pblock->nSolution = soln;
964 solutionTargetChecks.increment();
966 h = UintToArith256(B.GetHash());
967 /*for (z=31; z>=16; z--)
968 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
969 fprintf(stderr," mined ");
970 for (z=31; z>=16; z--)
971 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
972 fprintf(stderr," hashTarget ");
973 for (z=31; z>=16; z--)
974 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
975 fprintf(stderr," POW\n");*/
976 if ( h > hashTarget )
978 if ( NOTARY_PUBKEY33[0] != 0 && B.nTime > GetAdjustedTime() )
980 fprintf(stderr,"need to wait %d seconds to submit block\n",(int32_t)(B.nTime - GetAdjustedTime()));
981 while ( GetAdjustedTime() < B.nTime-2 )
984 if ( chainActive.Tip()->nHeight >= Mining_height )
986 fprintf(stderr,"new block arrived\n");
991 if ( ASSETCHAINS_STAKED == 0 )
993 if ( NOTARY_PUBKEY33[0] != 0 )
996 if ( (r= ((Mining_height + NOTARY_PUBKEY33[16]) % 64) / 8) > 0 )
997 MilliSleep((rand() % (r * 1000)) + 1000);
1002 if ( NOTARY_PUBKEY33[0] != 0 )
1004 while ( GetAdjustedTime() < B.nTime )
1009 uint256 tmp = B.GetHash();
1010 int32_t z; for (z=31; z>=0; z--)
1011 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
1012 fprintf(stderr," mined block!\n");
1015 CValidationState state;
1016 if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
1018 h = UintToArith256(B.GetHash());
1019 for (z=31; z>=0; z--)
1020 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
1021 fprintf(stderr," Invalid block mined, try again\n");
1024 KOMODO_CHOSEN_ONE = 1;
1026 SetThreadPriority(THREAD_PRIORITY_NORMAL);
1027 LogPrintf("KomodoMiner:\n");
1028 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
1029 #ifdef ENABLE_WALLET
1030 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1032 if (ProcessBlockFound(&B)) {
1034 // Ignore chain updates caused by us
1035 std::lock_guard<std::mutex> lock{m_cs};
1036 cancelSolver = false;
1038 KOMODO_CHOSEN_ONE = 0;
1039 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1040 // In regression test mode, stop mining after a block is found.
1041 if (chainparams.MineBlocksOnDemand()) {
1042 // Increment here because throwing skips the call below
1043 ehSolverRuns.increment();
1044 throw boost::thread_interrupted();
1046 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1050 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1051 std::lock_guard<std::mutex> lock{m_cs};
1052 return cancelSolver;
1055 // TODO: factor this out into a function with the same API for each solver.
1056 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1057 // Create solver and initialize it.
1059 eq.setstate(&curr_state);
1061 // Initialization done, start algo driver.
1063 eq.xfull = eq.bfull = eq.hfull = 0;
1065 for (u32 r = 1; r < WK; r++) {
1066 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1067 eq.xfull = eq.bfull = eq.hfull = 0;
1071 ehSolverRuns.increment();
1073 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1074 for (size_t s = 0; s < eq.nsols; s++) {
1075 LogPrint("pow", "Checking solution %d\n", s+1);
1076 std::vector<eh_index> index_vector(PROOFSIZE);
1077 for (size_t i = 0; i < PROOFSIZE; i++) {
1078 index_vector[i] = eq.sols[s][i];
1080 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1082 if (validBlock(sol_char)) {
1083 // If we find a POW solution, do not try other solutions
1084 // because they become invalid as we created a new block in blockchain.
1090 // If we find a valid block, we rebuild
1091 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1092 ehSolverRuns.increment();
1094 int32_t i; uint256 hash = pblock->GetHash();
1095 for (i=0; i<32; i++)
1096 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1097 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1099 KOMODO_MAYBEMINED = Mining_height;
1102 } catch (EhSolverCancelledException&) {
1103 LogPrint("pow", "Equihash solver cancelled\n");
1104 std::lock_guard<std::mutex> lock{m_cs};
1105 cancelSolver = false;
1109 // Check for stop or if block needs to be rebuilt
1110 boost::this_thread::interruption_point();
1111 // Regtest mode doesn't require peers
1112 if ( FOUND_BLOCK != 0 )
1115 fprintf(stderr,"FOUND_BLOCK!\n");
1118 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1120 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1122 fprintf(stderr,"no nodes, break\n");
1126 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1128 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1129 fprintf(stderr,"0xffff, break\n");
1132 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1134 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1135 fprintf(stderr,"timeout, break\n");
1138 if ( pindexPrev != chainActive.Tip() )
1140 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1141 fprintf(stderr,"Tip advanced, break\n");
1144 // Update nNonce and nTime
1145 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1146 pblock->nBits = savebits;
1147 /*if ( NOTARY_PUBKEY33[0] == 0 )
1150 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1151 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1153 // Changing pblock->nTime can change work required on testnet:
1154 HASHTarget.SetCompact(pblock->nBits);
1155 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1161 catch (const boost::thread_interrupted&)
1165 LogPrintf("KomodoMiner terminated\n");
1168 catch (const std::runtime_error &e)
1172 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1179 #ifdef ENABLE_WALLET
1180 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1182 void GenerateBitcoins(bool fGenerate, int nThreads)
1185 static boost::thread_group* minerThreads = NULL;
1188 nThreads = GetNumCores();
1190 if (minerThreads != NULL)
1192 minerThreads->interrupt_all();
1193 delete minerThreads;
1194 minerThreads = NULL;
1197 if (nThreads == 0 || !fGenerate)
1200 minerThreads = new boost::thread_group();
1201 for (int i = 0; i < nThreads; i++) {
1202 #ifdef ENABLE_WALLET
1203 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1205 minerThreads->create_thread(&BitcoinMiner);
1210 #endif // ENABLE_MINING