bool BuildCertJson(const CCert& cert, UniValue& oCert) { oCert.push_back(Pair("_id", stringFromVch(cert.vchCert))); oCert.push_back(Pair("txid", cert.txHash.GetHex())); oCert.push_back(Pair("height", (int)cert.nHeight)); int64_t nTime = 0; if (chainActive.Height() >= cert.nHeight-1) { CBlockIndex *pindex = chainActive[cert.nHeight-1]; if (pindex) { nTime = pindex->GetMedianTimePast(); } } oCert.push_back(Pair("time", nTime)); oCert.push_back(Pair("title", stringFromVch(cert.vchTitle))); oCert.push_back(Pair("publicvalue", stringFromVch(cert.vchPubData))); oCert.push_back(Pair("category", stringFromVch(cert.sCategory))); oCert.push_back(Pair("alias", stringFromVch(cert.vchAlias))); oCert.push_back(Pair("access_flags", cert.nAccessFlags)); int64_t expired_time = GetCertExpiration(cert); bool expired = false; if(expired_time <= chainActive.Tip()->GetMedianTimePast()) { expired = true; } oCert.push_back(Pair("expires_on", expired_time)); oCert.push_back(Pair("expired", expired)); return true; }
uint256 CreateBlockWithAppointedAddr(CKeyID const &keyID) { if (SysCfg().NetworkID() == CBaseParams::REGTEST) { // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.Tip(); CAccountViewCache accview(*pAccountViewTip, true); CTransactionDBCache txCache(*pTxCacheTip, true); CScriptDBViewCache ScriptDbTemp(*pScriptDBTip, true); shared_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(accview,txCache,ScriptDbTemp)); if (!pblocktemplate.get()) return uint256(); CBlock *pblock = &pblocktemplate.get()->block; // int nBlockSize = pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); // int64_t nStart = GetTime(); while (true) { pblock->SetTime(max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime())); set<CKeyID> setCreateKey; setCreateKey.clear(); setCreateKey.insert(keyID); if (CreatePosTx(pindexPrev, pblock,setCreateKey,accview,txCache,ScriptDbTemp)) { CheckWork(pblock, *pwalletMain); // int nBlockSize = pblock->GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); } if(setCreateKey.empty()) { LogPrint("postx", "%s is not exist in the wallet\r\n",keyID.ToAddress()); break; } ::MilliSleep(1); if (pindexPrev != chainActive.Tip()) { return chainActive.Tip()->GetBlockHash() ; } } } return uint256(); }
bool BuildCertIndexerHistoryJson(const CCert& cert, UniValue& oCert) { oCert.push_back(Pair("_id", cert.txHash.GetHex())); oCert.push_back(Pair("cert", stringFromVch(cert.vchCert))); oCert.push_back(Pair("height", (int)cert.nHeight)); int64_t nTime = 0; if (chainActive.Height() >= cert.nHeight-1) { CBlockIndex *pindex = chainActive[cert.nHeight-1]; if (pindex) { nTime = pindex->GetMedianTimePast(); } } oCert.push_back(Pair("time", nTime)); oCert.push_back(Pair("title", stringFromVch(cert.vchTitle))); oCert.push_back(Pair("publicvalue", stringFromVch(cert.vchPubData))); oCert.push_back(Pair("category", stringFromVch(cert.sCategory))); oCert.push_back(Pair("alias", stringFromVch(cert.vchAlias))); oCert.push_back(Pair("access_flags", cert.nAccessFlags)); return true; }
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn,const int nHeightIn) { // Create new block auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate()); if(!pblocktemplate.get()) return NULL; CBlock *pblock = &pblocktemplate->block; // pointer for convenience CBlockIndex* pindexPrev; if(nHeightIn<=0) { pindexPrev = chainActive.Tip(); } else pindexPrev = chainActive[nHeightIn-1]; int nHeight = pindexPrev->nBlockHeight + 1; pblock->nBlockHeight=nHeight; UpdateTime(pblock, pindexPrev); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (Params().MineBlocksOnDemand()) pblock->nVersion = GetArg("-blockversion", pblock->nVersion); // Create coinbase tx CMutableTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vin[0].prevout.n=nHeight; txNew.vin[0].scriptSig=CScript()<<0; txNew.vout.resize(1); txNew.vout[0].scriptPubKey = scriptPubKeyIn; txNew.vout[0].nLockTime=nHeight +COINBASE_MATURITY; // Add dummy coinbase tx as first transaction pblock->vtx.push_back(CTransaction()); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); //min tx size to judge finish of block.set this a little bit higher so as to make mining faster unsigned int nMinTxSize=200; // Collect memory pool transactions into the block CAmount nFees = 0; uint64_t nBlockSize = 1000; uint64_t nBlockTx = 0; int nBlockSigOps = 100; { LOCK2(cs_main, mempool.cs); if(nHeightIn<=0) { CCoinsViewCache view(pcoinsTip); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; // Collect transactions into block for (int i=0;i<(int)mempool.queue.size();i++) { const CTransaction& tx = mempool.mapTx[mempool.queue[i]].GetTx(); if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight)) continue; COrphan* porphan = NULL; CAmount nTotalIn = 0; bool fMissingInputs = false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction if (!view.HaveCoins(txin.prevout.hash)) { //don't take in transactions with prevout in mempool,because txs are queued by fee, not sequence, we can't guarantee it's //previous tx can be included in this block fMissingInputs = true; break; // This should never happen; all transactions in the memory // pool should connect to either transactions in the chain // or other transactions in the memory pool. if (!mempool.mapTx.count(txin.prevout.hash)) { LogPrintf("ERROR: mempool transaction missing input\n"); if (fDebug) assert("mempool transaction missing input" == 0); fMissingInputs = true; if (porphan) vOrphan.pop_back(); break; } // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); nTotalIn += mempool.mapTx[txin.prevout.hash].GetTx().vout[txin.prevout.n].nValue; continue; } const CCoins* coins = view.AccessCoins(txin.prevout.hash); assert(coins); if ((int64_t)coins->vout[txin.prevout.n].nLockTime >= ((int64_t)coins->vout[txin.prevout.n].nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nHeight : std::min((int64_t)pindexPrev->nTime,std::max((int64_t)pindexPrev->GetMedianTimePast()+1, (int64_t)GetAdjustedTime())))) fMissingInputs = true; CAmount nValueIn = coins->vout[txin.prevout.n].nValue; nTotalIn += nValueIn; } if (fMissingInputs) continue; // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = GetLegacySigOpCount(tx); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!view.HaveInputs(tx)) continue; CAmount nTxFees = tx.GetFee(); nTxSigOps += GetP2SHSigOpCount(tx, view); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Note that flags: we don't want to set mempool/IsStandard() // policy here, but we still have to ensure that the block we // create only contains transactions that are valid in new blocks. CValidationState state; if (!CheckInputs(tx, tx,state, view, pblock,true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) continue; CTxUndo txundo; UpdateCoins(tx, state, view, txundo, nHeight); // Added pblock->vtx.push_back(tx); pblocktemplate->vTxFees.push_back(nTxFees); pblocktemplate->vTxSigOps.push_back(nTxSigOps); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; if (nBlockSize+nMinTxSize>nBlockMaxSize) break; } } CBlock prevBlock; ReadBlockFromDisk(prevBlock, pindexPrev); CAmount prevCoinbaseFee=prevBlock.vtx[0].GetFee(); nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; // Compute final coinbase transaction. CAmount coinbaseInput=GetBlockValue(nHeight, nFees)+prevCoinbaseFee; txNew.vin[0].prevout.nValue = coinbaseInput; txNew.vout[0].nValue = 0; CAmount coinbaseFee=CFeeRate(DEFAULT_TRANSACTION_FEE).GetFee(txNew.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION)+10); CAmount coinbaseOutput=coinbaseInput-coinbaseFee; if(nHeightIn<=0&&coinbaseOutput<=minRelayTxFee.GetFee(DUST_THRESHOLD)) return NULL; txNew.vout[0].nValue =coinbaseOutput; pblock->vtx[0] = txNew; pblocktemplate->vTxFees[0] = -nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock); pblock->nNonce = 0; pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); CValidationState state; if (nHeightIn<=0&&!TestBlockValidity(state, *pblock, pindexPrev, false, false)) { LogPrintf("CreateNewBlock() : TestBlockValidity failed \n" ); return NULL; } }
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx) { int64_t nTimeStart = GetTimeMicros(); resetBlock(); pblocktemplate.reset(new CBlockTemplate()); if(!pblocktemplate.get()) return nullptr; pblock = &pblocktemplate->block; // pointer for convenience // Add dummy coinbase tx as first transaction pblock->vtx.emplace_back(); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = chainActive.Tip(); assert(pindexPrev != nullptr); nHeight = pindexPrev->nHeight + 1; pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); // Decide whether to include witness transactions // This is only needed in case the witness softfork activation is reverted // (which would require a very deep reorganization) or when // -promiscuousmempoolflags is used. // TODO: replace this with a call to main to assess validity of a mempool // transaction (which in most cases can be a no-op). fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx; int nPackagesSelected = 0; int nDescendantsUpdated = 0; addPackageTxs(nPackagesSelected, nDescendantsUpdated); int64_t nTime1 = GetTimeMicros(); nLastBlockTx = nBlockTx; nLastBlockWeight = nBlockWeight; // Create coinbase transaction. CMutableTransaction coinbaseTx; coinbaseTx.vin.resize(1); coinbaseTx.vin[0].prevout.SetNull(); coinbaseTx.vout.resize(1); coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn; coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus()); coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0; pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus()); pblocktemplate->vTxFees[0] = -nFees; LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]); CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } int64_t nTime2 = GetTimeMicros(); LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart)); return std::move(pblocktemplate); }