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 "consensus/consensus.h"
15 #include "consensus/upgrades.h"
16 #include "consensus/validation.h"
18 #include "crypto/equihash.h"
25 #include "primitives/transaction.h"
28 #include "ui_interface.h"
30 #include "utilmoneystr.h"
32 #include "wallet/wallet.h"
37 #include <boost/thread.hpp>
38 #include <boost/tuple/tuple.hpp>
46 //////////////////////////////////////////////////////////////////////////////
52 // Unconfirmed transactions in the memory pool often depend on other
53 // transactions in the memory pool. When we select transactions from the
54 // pool, we select by highest priority or fee rate, so we might consider
55 // transactions that depend on transactions that aren't yet in the block.
56 // The COrphan class keeps track of these 'temporary orphans' while
57 // CreateBlock is figuring out which transactions to include.
62 const CTransaction* ptx;
63 set<uint256> setDependsOn;
67 COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0)
72 uint64_t nLastBlockTx = 0;
73 uint64_t nLastBlockSize = 0;
75 // We want to sort transactions by priority and fee rate, so:
76 typedef boost::tuple<double, CFeeRate, const CTransaction*> TxPriority;
77 class TxPriorityCompare
82 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
84 bool operator()(const TxPriority& a, const TxPriority& b)
88 if (a.get<1>() == b.get<1>())
89 return a.get<0>() < b.get<0>();
90 return a.get<1>() < b.get<1>();
94 if (a.get<0>() == b.get<0>())
95 return a.get<1>() < b.get<1>();
96 return a.get<0>() < b.get<0>();
101 void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
103 pblock->nTime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
106 #include "komodo_defs.h"
108 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;
109 extern uint64_t ASSETCHAINS_REWARD,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED;
110 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN];
111 extern std::string NOTARY_PUBKEY;
112 extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33];
113 uint32_t Mining_start,Mining_height;
114 int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp);
115 int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize);
116 //uint64_t komodo_paxtotal();
117 int32_t komodo_baseid(char *origbase);
118 //int32_t komodo_is_issuer();
119 //int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo);
120 //int32_t komodo_isrealtime(int32_t *kmdheightp);
121 int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag);
122 uint64_t komodo_commission(const CBlock *block);
123 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);
125 CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
127 uint64_t deposits; int32_t isrealtime,kmdheight; uint32_t blocktime; const CChainParams& chainparams = Params();
129 std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
130 if(!pblocktemplate.get())
132 fprintf(stderr,"pblocktemplate.get() failure\n");
135 CBlock *pblock = &pblocktemplate->block; // pointer for convenience
136 /*if ( ASSETCHAINS_SYMBOL[0] != 0 && komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && chainActive.Tip()->nHeight >= ASSETCHAINS_MINHEIGHT )
138 isrealtime = komodo_isrealtime(&kmdheight);
139 deposits = komodo_paxtotal();
140 while ( KOMODO_ON_DEMAND == 0 && deposits == 0 && (int32_t)mempool.GetTotalTxSize() == 0 )
142 deposits = komodo_paxtotal();
143 if ( KOMODO_PASSPORT_INITDONE == 0 || KOMODO_INITDONE == 0 || (komodo_baseid(ASSETCHAINS_SYMBOL) >= 0 && (isrealtime= komodo_isrealtime(&kmdheight)) == 0) )
145 //fprintf(stderr,"INITDONE.%d RT.%d deposits %.8f ht.%d\n",KOMODO_INITDONE,isrealtime,(double)deposits/COIN,kmdheight);
147 else if ( komodo_isrealtime(&kmdheight) != 0 && (deposits != 0 || (int32_t)mempool.GetTotalTxSize() > 0) )
149 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);
154 KOMODO_ON_DEMAND = 0;
155 if ( 0 && deposits != 0 )
156 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());
158 // -regtest only: allow overriding block.nVersion with
159 // -blockversion=N to test forking scenarios
160 if (Params().MineBlocksOnDemand())
161 pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
163 // Add dummy coinbase tx as first transaction
164 pblock->vtx.push_back(CTransaction());
165 pblocktemplate->vTxFees.push_back(-1); // updated at end
166 pblocktemplate->vTxSigOps.push_back(-1); // updated at end
168 // Largest block you're willing to create:
169 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
170 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
171 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
173 // How much of the block should be dedicated to high-priority transactions,
174 // included regardless of the fees they pay
175 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
176 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
178 // Minimum block size you want to create; block will be filled with free transactions
179 // until there are no more or the block reaches this size:
180 unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE);
181 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
183 // Collect memory pool transactions into the block
187 LOCK2(cs_main, mempool.cs);
188 CBlockIndex* pindexPrev = chainActive.Tip();
189 const int nHeight = pindexPrev->nHeight + 1;
190 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, chainparams.GetConsensus());
191 pblock->nTime = GetAdjustedTime();
192 const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
193 CCoinsViewCache view(pcoinsTip);
194 uint32_t expired; uint64_t commission;
196 // Priority order to process transactions
197 list<COrphan> vOrphan; // list memory doesn't move
198 map<uint256, vector<COrphan*> > mapDependers;
199 bool fPrintPriority = GetBoolArg("-printpriority", false);
201 // This vector will be sorted into a priority queue:
202 vector<TxPriority> vecPriority;
203 vecPriority.reserve(mempool.mapTx.size());
204 for (CTxMemPool::indexed_transaction_set::iterator mi = mempool.mapTx.begin();
205 mi != mempool.mapTx.end(); ++mi)
207 const CTransaction& tx = mi->GetTx();
209 int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
211 : pblock->GetBlockTime();
213 if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight))
215 //fprintf(stderr,"coinbase.%d finaltx.%d expired.%d\n",tx.IsCoinBase(),IsFinalTx(tx, nHeight, nLockTimeCutoff),IsExpiredTx(tx, nHeight));
218 if ( ASSETCHAINS_SYMBOL[0] == 0 && komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 )
220 //fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure nHeight.%d nTime.%u vs locktime.%u\n",nHeight,(uint32_t)pblock->nTime,(uint32_t)tx.nLockTime);
223 COrphan* porphan = NULL;
224 double dPriority = 0;
225 CAmount nTotalIn = 0;
226 bool fMissingInputs = false;
227 BOOST_FOREACH(const CTxIn& txin, tx.vin)
229 // Read prev transaction
230 if (!view.HaveCoins(txin.prevout.hash))
232 // This should never happen; all transactions in the memory
233 // pool should connect to either transactions in the chain
234 // or other transactions in the memory pool.
235 if (!mempool.mapTx.count(txin.prevout.hash))
237 LogPrintf("ERROR: mempool transaction missing input\n");
238 if (fDebug) assert("mempool transaction missing input" == 0);
239 fMissingInputs = true;
245 // Has to wait for dependencies
248 // Use list for automatic deletion
249 vOrphan.push_back(COrphan(&tx));
250 porphan = &vOrphan.back();
252 mapDependers[txin.prevout.hash].push_back(porphan);
253 porphan->setDependsOn.insert(txin.prevout.hash);
254 nTotalIn += mempool.mapTx.find(txin.prevout.hash)->GetTx().vout[txin.prevout.n].nValue;
257 const CCoins* coins = view.AccessCoins(txin.prevout.hash);
260 CAmount nValueIn = coins->vout[txin.prevout.n].nValue;
261 nTotalIn += nValueIn;
263 int nConf = nHeight - coins->nHeight;
265 dPriority += (double)nValueIn * nConf;
267 nTotalIn += tx.GetJoinSplitValueIn();
269 if (fMissingInputs) continue;
271 // Priority is sum(valuein * age) / modified_txsize
272 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
273 dPriority = tx.ComputePriority(dPriority, nTxSize);
275 uint256 hash = tx.GetHash();
276 mempool.ApplyDeltas(hash, dPriority, nTotalIn);
278 CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize);
282 porphan->dPriority = dPriority;
283 porphan->feeRate = feeRate;
286 vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx())));
289 // Collect transactions into block
290 uint64_t nBlockSize = 1000;
291 uint64_t nBlockTx = 0;
293 int nBlockSigOps = 100;
294 bool fSortedByFee = (nBlockPrioritySize <= 0);
296 TxPriorityCompare comparer(fSortedByFee);
297 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
299 while (!vecPriority.empty())
301 // Take highest priority transaction off the priority queue:
302 double dPriority = vecPriority.front().get<0>();
303 CFeeRate feeRate = vecPriority.front().get<1>();
304 const CTransaction& tx = *(vecPriority.front().get<2>());
306 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
307 vecPriority.pop_back();
310 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
311 if (nBlockSize + nTxSize >= nBlockMaxSize)
313 //fprintf(stderr,"nBlockSize %d + %d nTxSize >= %d nBlockMaxSize\n",(int32_t)nBlockSize,(int32_t)nTxSize,(int32_t)nBlockMaxSize);
317 // Legacy limits on sigOps:
318 unsigned int nTxSigOps = GetLegacySigOpCount(tx);
319 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
321 //fprintf(stderr,"A nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
324 // Skip free transactions if we're past the minimum block size:
325 const uint256& hash = tx.GetHash();
326 double dPriorityDelta = 0;
327 CAmount nFeeDelta = 0;
328 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
329 if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
331 //fprintf(stderr,"fee rate skip\n");
334 // Prioritise by fee once past the priority size or we run out of high-priority
337 ((nBlockSize + nTxSize >= nBlockPrioritySize) || !AllowFree(dPriority)))
340 comparer = TxPriorityCompare(fSortedByFee);
341 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
344 if (!view.HaveInputs(tx))
346 //fprintf(stderr,"dont have inputs\n");
349 CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
351 nTxSigOps += GetP2SHSigOpCount(tx, view);
352 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1)
354 //fprintf(stderr,"B nBlockSigOps %d + %d nTxSigOps >= %d MAX_BLOCK_SIGOPS-1\n",(int32_t)nBlockSigOps,(int32_t)nTxSigOps,(int32_t)MAX_BLOCK_SIGOPS);
357 // Note that flags: we don't want to set mempool/IsStandard()
358 // policy here, but we still have to ensure that the block we
359 // create only contains transactions that are valid in new blocks.
360 CValidationState state;
361 PrecomputedTransactionData txdata(tx);
362 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
364 //fprintf(stderr,"context failure\n");
367 UpdateCoins(tx, view, nHeight);
370 pblock->vtx.push_back(tx);
371 pblocktemplate->vTxFees.push_back(nTxFees);
372 pblocktemplate->vTxSigOps.push_back(nTxSigOps);
373 nBlockSize += nTxSize;
375 nBlockSigOps += nTxSigOps;
380 LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString());
383 // Add transactions that depend on this one to the priority queue
384 if (mapDependers.count(hash))
386 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
388 if (!porphan->setDependsOn.empty())
390 porphan->setDependsOn.erase(hash);
391 if (porphan->setDependsOn.empty())
393 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->feeRate, porphan->ptx));
394 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
401 nLastBlockTx = nBlockTx;
402 nLastBlockSize = nBlockSize;
403 blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
404 //pblock->nTime = blocktime + 1;
405 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
406 //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits);
407 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] != 0 )
409 uint64_t txfees,utxovalue; uint32_t txtime; uint256 utxotxid,revtxid; int32_t i,siglen,numsigs,utxovout; uint8_t utxosig[128],*ptr;
410 CMutableTransaction txStaked = CreateNewContextualCMutableTransaction(Params().GetConsensus(), chainActive.Height() + 1);
411 //if ( blocktime > pindexPrev->GetMedianTimePast()+60 )
412 // blocktime = pindexPrev->GetMedianTimePast() + 60;
413 if ( (siglen= komodo_staked(txStaked,pblock->nBits,&blocktime,&txtime,&utxotxid,&utxovout,&utxovalue,utxosig)) > 0 )
416 pblock->vtx.push_back(txStaked);
417 pblocktemplate->vTxFees.push_back(txfees);
418 pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked));
420 pblock->nTime = blocktime;
421 if ( GetAdjustedTime() < pblock->nTime )//|| pblock->GetBlockTime() > GetAdjustedTime() + 60)
423 fprintf(stderr,"need to wait %d seconds to mine:\n",(int32_t)(pblock->nTime - GetAdjustedTime()));
424 while ( GetAdjustedTime()+30 < pblock->nTime )
427 fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime()));
429 fprintf(stderr,"finished waiting\n");
430 //sleep(pblock->nTime - GetAdjustedTime());
432 } else return(0); //fprintf(stderr,"no utxos eligible for staking\n");
435 // Create coinbase tx
436 CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight);
438 txNew.vin[0].prevout.SetNull();
439 txNew.vout.resize(1);
440 txNew.vout[0].scriptPubKey = scriptPubKeyIn;
441 txNew.vout[0].nValue = GetBlockSubsidy(nHeight,chainparams.GetConsensus());
442 txNew.nLockTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
443 txNew.nExpiryHeight = 0;
445 txNew.vout[0].nValue += nFees;
446 txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
448 pblock->vtx[0] = txNew;
449 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 )
451 int32_t i; uint8_t *ptr;
452 txNew.vout.resize(2);
453 txNew.vout[1].nValue = commission;
454 txNew.vout[1].scriptPubKey.resize(35);
455 ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
458 ptr[i+1] = ASSETCHAINS_OVERRIDE_PUBKEY33[i];
459 ptr[34] = OP_CHECKSIG;
460 //printf("autocreate commision vout\n");
461 pblock->vtx[0] = txNew;
463 pblocktemplate->vTxFees[0] = -nFees;
465 arith_uint256 nonce = UintToArith256(GetRandHash());
466 // Clear the top and bottom 16 bits (for local use as thread flags and counters)
469 pblock->nNonce = ArithToUint256(nonce);
472 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
473 pblock->hashReserved = uint256();
474 if ( ASSETCHAINS_SYMBOL[0] == 0 || ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 )
476 UpdateTime(pblock, Params().GetConsensus(), pindexPrev);
477 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus());
479 if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 )
481 pblock->nTime = pindexPrev->nTime + 60;
482 while ( pblock->GetBlockTime() > GetAdjustedTime() + 10 )
484 //fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60));
486 pblock->nSolution.clear();
487 pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]);
489 CValidationState state;
490 if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false))
492 //static uint32_t counter;
493 //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
494 // fprintf(stderr,"warning: miner testblockvalidity failed\n");
499 return pblocktemplate.release();
504 boost::optional<CScript> GetMinerScriptPubKey(CReserveKey& reservekey)
506 boost::optional<CScript> GetMinerScriptPubKey()
510 CBitcoinAddress addr;
511 if (addr.SetString(GetArg("-mineraddress", ""))) {
512 addr.GetKeyID(keyID);
516 if (!reservekey.GetReservedKey(pubkey)) {
517 return boost::optional<CScript>();
519 keyID = pubkey.GetID();
521 return boost::optional<CScript>();
525 CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
530 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
532 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey(reservekey);
534 CBlockTemplate* CreateNewBlockWithKey()
536 boost::optional<CScript> scriptPubKey = GetMinerScriptPubKey();
542 return CreateNewBlock(*scriptPubKey);
545 //////////////////////////////////////////////////////////////////////////////
552 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
554 // Update nExtraNonce
555 static uint256 hashPrevBlock;
556 if (hashPrevBlock != pblock->hashPrevBlock)
559 hashPrevBlock = pblock->hashPrevBlock;
562 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
563 CMutableTransaction txCoinbase(pblock->vtx[0]);
564 txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
565 assert(txCoinbase.vin[0].scriptSig.size() <= 100);
567 pblock->vtx[0] = txCoinbase;
568 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
572 //////////////////////////////////////////////////////////////////////////////
577 CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
579 CPubKey pubkey; CScript scriptPubKey; uint8_t *script,*ptr; int32_t i;
580 if ( USE_EXTERNAL_PUBKEY != 0 )
582 //fprintf(stderr,"use notary pubkey\n");
583 scriptPubKey = CScript() << ParseHex(NOTARY_PUBKEY) << OP_CHECKSIG;
587 if (!reservekey.GetReservedKey(pubkey))
591 scriptPubKey.resize(35);
592 ptr = (uint8_t *)pubkey.begin();
593 script = (uint8_t *)scriptPubKey.data();
596 script[i+1] = ptr[i];
597 script[34] = OP_CHECKSIG;
598 //scriptPubKey = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
600 return CreateNewBlock(scriptPubKey);
603 void komodo_broadcast(CBlock *pblock,int32_t limit)
606 //fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL));
609 BOOST_FOREACH(CNode* pnode, vNodes)
611 if ( pnode->hSocket == INVALID_SOCKET )
613 if ( (rand() % n) == 0 )
615 pnode->PushMessage("block", *pblock);
621 //fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL));
624 static bool ProcessBlockFound(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
626 static bool ProcessBlockFound(CBlock* pblock)
627 #endif // ENABLE_WALLET
629 LogPrintf("%s\n", pblock->ToString());
630 LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1);
635 if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash())
637 uint256 hash; int32_t i;
638 hash = pblock->hashPrevBlock;
639 for (i=31; i>=0; i--)
640 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
641 fprintf(stderr," <- prev (stale)\n");
642 hash = chainActive.Tip()->GetBlockHash();
643 for (i=31; i>=0; i--)
644 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
645 fprintf(stderr," <- chainTip (stale)\n");
647 return error("KomodoMiner: generated block is stale");
652 // Remove key from key pool
653 if ( IS_KOMODO_NOTARY == 0 )
655 if (GetArg("-mineraddress", "").empty()) {
656 // Remove key from key pool
657 reservekey.KeepKey();
660 // Track how many getdata requests this block gets
663 LOCK(wallet.cs_wallet);
664 wallet.mapRequestCount[pblock->GetHash()] = 0;
668 // Process this block the same as if we had received it from another node
669 CValidationState state;
670 if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL))
671 return error("KomodoMiner: ProcessNewBlock, block not accepted");
673 TrackMinedBlock(pblock->GetHash());
674 komodo_broadcast(pblock,16);
678 int32_t komodo_baseid(char *origbase);
679 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height);
680 arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc);
681 int32_t FOUND_BLOCK,KOMODO_MAYBEMINED;
682 extern int32_t KOMODO_LASTMINED;
683 int32_t roundrobin_delay;
684 arith_uint256 HASHTarget,HASHTarget_POW;
687 void static BitcoinMiner(CWallet *pwallet)
689 void static BitcoinMiner()
692 LogPrintf("KomodoMiner started\n");
693 SetThreadPriority(THREAD_PRIORITY_LOWEST);
694 RenameThread("komodo-miner");
695 const CChainParams& chainparams = Params();
698 // Each thread has its own key
699 CReserveKey reservekey(pwallet);
702 // Each thread has its own counter
703 unsigned int nExtraNonce = 0;
705 unsigned int n = chainparams.EquihashN();
706 unsigned int k = chainparams.EquihashK();
707 uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1;
708 while ( (ASSETCHAIN_INIT == 0 || KOMODO_INITDONE == 0) ) //chainActive.Tip()->nHeight != 235300 &&
711 if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 )
714 komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime());
717 //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 )
719 //else solver = "default";
720 assert(solver == "tromp" || solver == "default");
721 LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k);
722 if ( ASSETCHAINS_SYMBOL[0] != 0 )
723 fprintf(stderr,"notaryid.%d Mining.%s with %s\n",notaryid,ASSETCHAINS_SYMBOL,solver.c_str());
725 bool cancelSolver = false;
726 boost::signals2::connection c = uiInterface.NotifyBlockTip.connect(
727 [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable {
728 std::lock_guard<std::mutex> lock{m_cs};
735 if ( ASSETCHAINS_SYMBOL[0] != 0 )
736 fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str());
739 if (chainparams.MiningRequiresPeers()) //chainActive.Tip()->nHeight != 235300 &&
741 //if ( ASSETCHAINS_SEED != 0 && chainActive.Tip()->nHeight < 100 )
743 // Busy-wait for the network to come online so we don't waste time mining
744 // on an obsolete chain. In regtest mode we expect to fly solo.
750 fvNodesEmpty = vNodes.empty();
752 if (!fvNodesEmpty )//&& !IsInitialBlockDownload())
755 //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload());
758 //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL);
761 /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT )
763 fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight);
769 unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
770 CBlockIndex* pindexPrev = chainActive.Tip();
771 if ( Mining_height != pindexPrev->nHeight+1 )
773 Mining_height = pindexPrev->nHeight+1;
774 Mining_start = (uint32_t)time(NULL);
776 if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_STAKED == 0 )
778 //fprintf(stderr,"%s create new block ht.%d\n",ASSETCHAINS_SYMBOL,Mining_height);
782 CBlockTemplate *ptr = CreateNewBlockWithKey(reservekey);
784 CBlockTemplate *ptr = CreateNewBlockWithKey();
788 static uint32_t counter;
789 if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 )
790 fprintf(stderr,"created illegal block, retry\n");
794 unique_ptr<CBlockTemplate> pblocktemplate(ptr);
795 if (!pblocktemplate.get())
797 if (GetArg("-mineraddress", "").empty()) {
798 LogPrintf("Error in KomodoMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n");
800 // Should never reach here, because -mineraddress validity is checked in init.cpp
801 LogPrintf("Error in KomodoMiner: Invalid -mineraddress\n");
805 CBlock *pblock = &pblocktemplate->block;
806 if ( ASSETCHAINS_SYMBOL[0] != 0 )
808 if ( ASSETCHAINS_REWARD == 0 )
810 if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT )
812 static uint32_t counter;
813 if ( counter++ < 10 )
814 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
817 } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",ASSETCHAINS_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT);
820 IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
821 LogPrintf("Running KomodoMiner.%s with %u transactions in block (%u bytes)\n",solver.c_str(),pblock->vtx.size(),::GetSerializeSize(*pblock,SER_NETWORK,PROTOCOL_VERSION));
825 uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime();
826 savebits = pblock->nBits;
827 HASHTarget = arith_uint256().SetCompact(pblock->nBits);
828 roundrobin_delay = ROUNDROBIN_DELAY;
829 if ( ASSETCHAINS_SYMBOL[0] == 0 && notaryid >= 0 )
832 if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 )
834 komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight);
838 if( pubkeys[0][i] != 0 )
842 else externalflag = 0;
843 if ( NOTARY_PUBKEY33[0] != 0 )
846 if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 )
848 if ( externalflag == 0 && i != 66 && mids[i] >= 0 )
849 printf("VIOLATION at %d, notaryid.%d\n",i,mids[i]);
850 for (j=gpucount=0; j<65; j++)
852 if ( notaryid <= 3 || notaryid == 34 || notaryid == 51 || notaryid == 52 )
855 fprintf(stderr,"%d ",mids[j]);
856 else fprintf(stderr,"GPU ");
861 if ( gpucount > j/2 )
866 else i = ((Mining_height + notaryid) % 64);
867 delta = sqrt((double)gpucount - j/2) / 2.;
868 roundrobin_delay += ((delta * i) / 64) - delta;
869 //fprintf(stderr,"delta.%f %f %f\n",delta,(double)(gpucount - j/3) / 2,(delta * i) / 64);
871 fprintf(stderr," <- prev minerids from ht.%d notary.%d gpucount.%d %.2f%% t.%u %d\n",pindexPrev->nHeight,notaryid,gpucount,100.*(double)gpucount/j,(uint32_t)time(NULL),roundrobin_delay);
874 if ( mids[j] == notaryid )
877 KOMODO_LASTMINED = 0;
878 } else fprintf(stderr,"no nonz pubkeys\n");
879 if ( (Mining_height >= 235300 && Mining_height < 236000) || (j == 65 && Mining_height > KOMODO_MAYBEMINED+1 && Mining_height > KOMODO_LASTMINED+64) )
881 HASHTarget = arith_uint256().SetCompact(KOMODO_MINDIFF_NBITS);
882 fprintf(stderr,"I am the chosen one for %s ht.%d\n",ASSETCHAINS_SYMBOL,pindexPrev->nHeight+1);
883 } //else fprintf(stderr,"duplicate at j.%d\n",j);
884 } else Mining_start = 0;
885 } else Mining_start = 0;
886 if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 )
889 /*if ( Mining_height <= 100 )
894 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
895 for (z=31; z>=0; z--)
896 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
897 fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED);
901 /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt
903 fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL);
908 KOMODO_CHOSEN_ONE = 0;
909 crypto_generichash_blake2b_state state;
910 EhInitialiseState(n, k, state);
911 // I = the block header minus nonce and solution.
912 CEquihashInput I{*pblock};
913 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
916 crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
918 crypto_generichash_blake2b_state curr_state;
920 crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size());
921 // (x_1, x_2, ...) = A(I, V, n, k)
922 LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString());
923 arith_uint256 hashTarget;
924 if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 )
925 hashTarget = HASHTarget_POW;
926 else hashTarget = HASHTarget;
927 std::function<bool(std::vector<unsigned char>)> validBlock =
929 [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams]
931 [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams]
933 (std::vector<unsigned char> soln) {
934 int32_t z; arith_uint256 h; CBlock B;
935 // Write the solution to the hash and compute the result.
936 LogPrint("pow", "- Checking solution against target\n");
937 pblock->nSolution = soln;
938 solutionTargetChecks.increment();
940 h = UintToArith256(B.GetHash());
941 if ( h > hashTarget )
943 /*for (z=31; z>=16; z--)
944 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
945 fprintf(stderr," mined ");
946 for (z=31; z>=16; z--)
947 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]);
948 fprintf(stderr," hashTarget ");
949 for (z=31; z>=16; z--)
950 fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]);
951 fprintf(stderr," POW\n");*/
952 CValidationState state;
953 if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false))
955 h = UintToArith256(B.GetHash());
956 for (z=31; z>=0; z--)
957 fprintf(stderr,"%02x",((uint8_t *)&h)[z]);
958 fprintf(stderr," Invalid block mined, try again\n");
961 if ( ASSETCHAINS_STAKED == 0 )
963 if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay )
965 //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL)));
966 //int32_t nseconds = Mining_start+roundrobin_delay-time(NULL);
967 //if ( nseconds > 0 )
969 MilliSleep((rand() % 1700) + 1);
971 else if ( ASSETCHAINS_SYMBOL[0] != 0 )
978 if ( NOTARY_PUBKEY33[0] != 0 )
980 printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime()));
981 while ( GetAdjustedTime() < B.nTime )
986 uint256 tmp = B.GetHash();
987 int32_t z; for (z=31; z>=0; z--)
988 fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]);
989 fprintf(stderr," mined block!\n");
992 KOMODO_CHOSEN_ONE = 1;
994 SetThreadPriority(THREAD_PRIORITY_NORMAL);
995 LogPrintf("KomodoMiner:\n");
996 LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex());
998 if (ProcessBlockFound(&B, *pwallet, reservekey)) {
1000 if (ProcessBlockFound(&B)) {
1002 // Ignore chain updates caused by us
1003 std::lock_guard<std::mutex> lock{m_cs};
1004 cancelSolver = false;
1006 KOMODO_CHOSEN_ONE = 0;
1007 SetThreadPriority(THREAD_PRIORITY_LOWEST);
1008 // In regression test mode, stop mining after a block is found.
1009 if (chainparams.MineBlocksOnDemand()) {
1010 // Increment here because throwing skips the call below
1011 ehSolverRuns.increment();
1012 throw boost::thread_interrupted();
1014 //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 )
1018 std::function<bool(EhSolverCancelCheck)> cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) {
1019 std::lock_guard<std::mutex> lock{m_cs};
1020 return cancelSolver;
1023 // TODO: factor this out into a function with the same API for each solver.
1024 if (solver == "tromp" ) { //&& notaryid >= 0 ) {
1025 // Create solver and initialize it.
1027 eq.setstate(&curr_state);
1029 // Initialization done, start algo driver.
1031 eq.xfull = eq.bfull = eq.hfull = 0;
1033 for (u32 r = 1; r < WK; r++) {
1034 (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0);
1035 eq.xfull = eq.bfull = eq.hfull = 0;
1039 ehSolverRuns.increment();
1041 // Convert solution indices to byte array (decompress) and pass it to validBlock method.
1042 for (size_t s = 0; s < eq.nsols; s++) {
1043 LogPrint("pow", "Checking solution %d\n", s+1);
1044 std::vector<eh_index> index_vector(PROOFSIZE);
1045 for (size_t i = 0; i < PROOFSIZE; i++) {
1046 index_vector[i] = eq.sols[s][i];
1048 std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);
1050 if (validBlock(sol_char)) {
1051 // If we find a POW solution, do not try other solutions
1052 // because they become invalid as we created a new block in blockchain.
1058 // If we find a valid block, we rebuild
1059 bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled);
1060 ehSolverRuns.increment();
1062 int32_t i; uint256 hash = pblock->GetHash();
1063 for (i=0; i<32; i++)
1064 fprintf(stderr,"%02x",((uint8_t *)&hash)[i]);
1065 fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height);
1067 KOMODO_MAYBEMINED = Mining_height;
1070 } catch (EhSolverCancelledException&) {
1071 LogPrint("pow", "Equihash solver cancelled\n");
1072 std::lock_guard<std::mutex> lock{m_cs};
1073 cancelSolver = false;
1077 // Check for stop or if block needs to be rebuilt
1078 boost::this_thread::interruption_point();
1079 // Regtest mode doesn't require peers
1080 if ( FOUND_BLOCK != 0 )
1083 fprintf(stderr,"FOUND_BLOCK!\n");
1086 if (vNodes.empty() && chainparams.MiningRequiresPeers())
1088 if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT )
1090 fprintf(stderr,"no nodes, break\n");
1094 if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff)
1096 //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1097 fprintf(stderr,"0xffff, break\n");
1100 if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60)
1102 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1103 fprintf(stderr,"timeout, break\n");
1106 if ( pindexPrev != chainActive.Tip() )
1108 if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 )
1109 fprintf(stderr,"Tip advanced, break\n");
1112 // Update nNonce and nTime
1113 pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
1114 pblock->nBits = savebits;
1115 /*if ( NOTARY_PUBKEY33[0] == 0 )
1118 UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
1119 if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
1121 // Changing pblock->nTime can change work required on testnet:
1122 HASHTarget.SetCompact(pblock->nBits);
1123 HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED);
1129 catch (const boost::thread_interrupted&)
1133 LogPrintf("KomodoMiner terminated\n");
1136 catch (const std::runtime_error &e)
1140 LogPrintf("KomodoMiner runtime error: %s\n", e.what());
1147 #ifdef ENABLE_WALLET
1148 void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads)
1150 void GenerateBitcoins(bool fGenerate, int nThreads)
1153 static boost::thread_group* minerThreads = NULL;
1156 nThreads = GetNumCores();
1158 if (minerThreads != NULL)
1160 minerThreads->interrupt_all();
1161 delete minerThreads;
1162 minerThreads = NULL;
1165 if (nThreads == 0 || !fGenerate)
1168 minerThreads = new boost::thread_group();
1169 for (int i = 0; i < nThreads; i++) {
1170 #ifdef ENABLE_WALLET
1171 minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
1173 minerThreads->create_thread(&BitcoinMiner);
1178 #endif // ENABLE_MINING