PIVX Core  5.6.99
P2P Digital Currency
blockassembler.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 The Bitcoin Core developers
3 // Copyright (c) 2021 The PIVX Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or https://www.opensource.org/licenses/mit-license.php.
6 
7 #include "blockassembler.h"
8 
9 #include "amount.h"
10 #include "blocksignature.h"
11 #include "chain.h"
12 #include "chainparams.h"
13 #include "consensus/consensus.h"
14 #include "consensus/merkle.h"
15 #include "consensus/upgrades.h"
16 #include "consensus/validation.h"
18 #include "masternode-payments.h"
19 #include "policy/policy.h"
20 #include "pow.h"
21 #include "primitives/transaction.h"
22 #include "spork.h"
23 #include "timedata.h"
24 #include "util/system.h"
25 #include "util/validation.h"
26 #include "validationinterface.h"
27 
28 #ifdef ENABLE_WALLET
29 #include "wallet/wallet.h"
30 #endif
31 
32 #include <algorithm>
33 #include <boost/thread.hpp>
34 
35 // Unconfirmed transactions in the memory pool often depend on other
36 // transactions in the memory pool. When we select transactions from the
37 // pool, we select by highest priority or fee rate, so we might consider
38 // transactions that depend on transactions that aren't yet in the block.
39 
40 uint64_t nLastBlockTx = 0;
41 uint64_t nLastBlockSize = 0;
42 
43 int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
44 {
45  int64_t nOldTime = pblock->nTime;
46  int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
47 
48  if (nOldTime < nNewTime)
49  pblock->nTime = nNewTime;
50 
51  // Updating time can change work required on testnet:
52  if (consensusParams.fPowAllowMinDifficultyBlocks)
53  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
54 
55  return nNewTime - nOldTime;
56 }
57 
58 static CMutableTransaction NewCoinbase(const int nHeight, const CScript* pScriptPubKey = nullptr)
59 {
60  CMutableTransaction txCoinbase;
61  txCoinbase.vout.emplace_back();
62  txCoinbase.vout[0].SetEmpty();
63  if (pScriptPubKey) txCoinbase.vout[0].scriptPubKey = *pScriptPubKey;
64  txCoinbase.vin.emplace_back();
65  txCoinbase.vin[0].scriptSig = CScript() << nHeight << OP_0;
66  return txCoinbase;
67 }
68 
69 bool SolveProofOfStake(CBlock* pblock, CBlockIndex* pindexPrev, CWallet* pwallet,
70  std::vector<CStakeableOutput>* availableCoins, bool stopPoSOnNewBlock)
71 {
72  boost::this_thread::interruption_point();
73 
74  assert(pindexPrev);
75  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
76 
77  // Sync wallet before create coinstake
79 
80  CMutableTransaction txCoinStake;
81  int64_t nTxNewTime = 0;
82  if (!pwallet->CreateCoinStake(pindexPrev,
83  pblock->nBits,
84  txCoinStake,
85  nTxNewTime,
86  availableCoins,
87  stopPoSOnNewBlock
88  )) {
89  LogPrint(BCLog::STAKING, "%s : stake not found\n", __func__);
90  return false;
91  }
92  // Stake found
93 
94  // Create coinbase tx and add masternode/budget payments
95  CMutableTransaction txCoinbase = NewCoinbase(pindexPrev->nHeight + 1);
96  FillBlockPayee(txCoinbase, txCoinStake, pindexPrev, true);
97 
98  // Sign coinstake
99  if (!pwallet->SignCoinStake(txCoinStake)) {
100  const COutPoint& stakeIn = txCoinStake.vin[0].prevout;
101  return error("Unable to sign coinstake with input %s-%d", stakeIn.hash.ToString(), stakeIn.n);
102  }
103 
104  pblock->vtx.emplace_back(MakeTransactionRef(txCoinbase));
105  pblock->vtx.emplace_back(MakeTransactionRef(txCoinStake));
106  pblock->nTime = nTxNewTime;
107  return true;
108 }
109 
110 CMutableTransaction CreateCoinbaseTx(const CScript& scriptPubKeyIn, CBlockIndex* pindexPrev)
111 {
112  assert(pindexPrev);
113  const int nHeight = pindexPrev->nHeight + 1;
114 
115  // Create coinbase tx
116  CMutableTransaction txCoinbase = NewCoinbase(nHeight, &scriptPubKeyIn);
117 
118  //Masternode and general budget payments
119  CMutableTransaction txDummy; // POW blocks have no coinstake
120  FillBlockPayee(txCoinbase, txDummy, pindexPrev, false);
121 
122  // If no payee was detected, then the whole block value goes to the first output.
123  if (txCoinbase.vout.size() == 1) {
124  txCoinbase.vout[0].nValue = GetBlockValue(nHeight);
125  }
126 
127  return txCoinbase;
128 }
129 
130 bool CreateCoinbaseTx(CBlock* pblock, const CScript& scriptPubKeyIn, CBlockIndex* pindexPrev)
131 {
132  pblock->vtx.emplace_back(MakeTransactionRef(CreateCoinbaseTx(scriptPubKeyIn, pindexPrev)));
133  return true;
134 }
135 
136 BlockAssembler::BlockAssembler(const CChainParams& _chainparams, const bool _defaultPrintPriority)
137  : chainparams(_chainparams), defaultPrintPriority(_defaultPrintPriority)
138 {
139  // Largest block you're willing to create:
140  nBlockMaxSize = gArgs.GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
141  // Limit to between 1K and MAX_BLOCK_SIZE-1K for sanity:
142  nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE_CURRENT - 1000), nBlockMaxSize));
143 }
144 
146 {
147  inBlock.clear();
148 
149  // Reserve space for coinbase tx
150  nBlockSize = 1000;
151  nBlockSigOps = 100;
152 
153  // These counters do not include coinbase tx
154  nBlockTx = 0;
155  nFees = 0;
156 }
157 
158 std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn,
159  CWallet* pwallet,
160  bool fProofOfStake,
161  std::vector<CStakeableOutput>* availableCoins,
162  bool fNoMempoolTx,
163  bool fTestValidity,
164  CBlockIndex* prevBlock,
165  bool stopPoSOnNewBlock,
166  bool fIncludeQfc)
167 {
168  resetBlock();
169 
170  pblocktemplate.reset(new CBlockTemplate());
171 
172  if(!pblocktemplate) return nullptr;
173  pblock = &pblocktemplate->block; // pointer for convenience
174 
175  pblocktemplate->vTxFees.push_back(-1); // updated at end
176  pblocktemplate->vTxSigOps.push_back(-1); // updated at end
177 
178  CBlockIndex* pindexPrev = prevBlock ? prevBlock : WITH_LOCK(cs_main, return chainActive.Tip());
179  assert(pindexPrev);
180  nHeight = pindexPrev->nHeight + 1;
181 
183  // -regtest only: allow overriding block.nVersion with
184  // -blockversion=N to test forking scenarios
185  if (Params().IsRegTestNet()) {
186  pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
187  }
188 
189  // Depending on the tip height, try to find a coinstake who solves the block or create a coinbase tx.
190  if (!(fProofOfStake ? SolveProofOfStake(pblock, pindexPrev, pwallet, availableCoins, stopPoSOnNewBlock)
191  : CreateCoinbaseTx(pblock, scriptPubKeyIn, pindexPrev))) {
192  return nullptr;
193  }
194 
195  // After v6 enforcement, add LLMQ commitments if needed
196  const Consensus::Params& consensus = Params().GetConsensus();
197  if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V6_0) && fIncludeQfc) {
198  LOCK(cs_main);
199  for (const auto& p : Params().GetConsensus().llmqs) {
200  CTransactionRef qcTx;
201  if (llmq::quorumBlockProcessor->GetMinableCommitmentTx(p.first, nHeight, qcTx)) {
202  pblock->vtx.emplace_back(qcTx);
203  pblocktemplate->vTxFees.emplace_back(0);
204  pblocktemplate->vTxSigOps.emplace_back(0);
205  nBlockSize += qcTx->GetTotalSize();
206  ++nBlockTx;
207  }
208  }
209  }
210 
211  if (!fNoMempoolTx) {
212  // Add transactions from mempool
214  addPackageTxs();
215  }
216 
217  if (!fProofOfStake) {
218  // Coinbase can get the fees.
219  CMutableTransaction txCoinbase(*pblock->vtx[0]);
220  txCoinbase.vout[0].nValue += nFees;
221  pblock->vtx[0] = MakeTransactionRef(txCoinbase);
222  pblocktemplate->vTxFees[0] = -nFees;
223  }
224 
227  LogPrintf("CreateNewBlock(): total size %u txs: %u fees: %ld sigops %d\n", nBlockSize, nBlockTx, nFees, nBlockSigOps);
228 
229 
230  // Fill in header
231  pblock->hashPrevBlock = pindexPrev->GetBlockHash();
232  if (!fProofOfStake) UpdateTime(pblock, consensus, pindexPrev);
233  pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
234  pblock->nNonce = 0;
235  pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*(pblock->vtx[0]));
237 
238  if (fProofOfStake) { // this is only for PoS because the IncrementExtraNonce does it for PoW
240  LogPrintf("CPUMiner : proof-of-stake block found %s \n", pblock->GetHash().GetHex());
241  if (!SignBlock(*pblock, *pwallet)) {
242  LogPrintf("%s: Signing new block with UTXO key failed \n", __func__);
243  return nullptr;
244  }
245  }
246 
247  {
248  LOCK(cs_main);
249  if (prevBlock == nullptr && chainActive.Tip() != pindexPrev) return nullptr; // new block came in, move on
250 
251  CValidationState state;
252  if (fTestValidity &&
253  !TestBlockValidity(state, *pblock, pindexPrev, false, false, false)) {
254  throw std::runtime_error(
255  strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
256  }
257  }
258 
259  return std::move(pblocktemplate);
260 }
261 
263 {
264  for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
265  // Only test txs not already in the block
266  if (inBlock.count(*iit)) {
267  testSet.erase(iit++);
268  }
269  else {
270  iit++;
271  }
272  }
273 }
274 
275 bool BlockAssembler::TestPackage(uint64_t packageSize, unsigned int packageSigOps)
276 {
277  if (nBlockSize + packageSize >= nBlockMaxSize)
278  return false;
279  if (nBlockSigOps + packageSigOps >= MAX_BLOCK_SIGOPS_CURRENT)
280  return false;
281  return true;
282 }
283 
284 // Block size and sigops have already been tested. Check that all transactions
285 // are final.
287 {
288  for (const CTxMemPool::txiter& it : package) {
289  if (!IsFinalTx(it->GetSharedTx(), nHeight))
290  return false;
291  }
292  return true;
293 }
294 
296 {
297  pblock->vtx.emplace_back(iter->GetSharedTx());
298  pblocktemplate->vTxFees.push_back(iter->GetFee());
299  pblocktemplate->vTxSigOps.push_back(iter->GetSigOpCount());
300  nBlockSize += iter->GetTxSize();
301  ++nBlockTx;
302  nBlockSigOps += iter->GetSigOpCount();
303  nFees += iter->GetFee();
304  inBlock.insert(iter);
305 
306  bool fPrintPriority = gArgs.GetBoolArg("-printpriority", defaultPrintPriority);
307  if (fPrintPriority) {
308  LogPrintf("feerate %s txid %s\n",
309  CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
310  iter->GetTx().GetHash().ToString());
311  }
312 }
313 
315  indexed_modified_transaction_set& mapModifiedTx)
316 {
317  for (const CTxMemPool::txiter& it : alreadyAdded) {
318  CTxMemPool::setEntries descendants;
319  mempool.CalculateDescendants(it, descendants);
320  // Insert all descendants (not yet in block) into the modified set
321  for (CTxMemPool::txiter desc : descendants) {
322  if (alreadyAdded.count(desc))
323  continue;
324  modtxiter mit = mapModifiedTx.find(desc);
325  if (mit == mapModifiedTx.end()) {
326  CTxMemPoolModifiedEntry modEntry(desc);
327  modEntry.nSizeWithAncestors -= it->GetTxSize();
328  modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
329  modEntry.nSigOpCountWithAncestors -= it->GetSigOpCount();
330  mapModifiedTx.insert(modEntry);
331  } else {
332  mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
333  }
334  }
335  }
336 }
337 
338 // Skip entries in mapTx that are already in a block or are present
339 // in mapModifiedTx (which implies that the mapTx ancestor state is
340 // stale due to ancestor inclusion in the block)
341 // Also skip transactions that we've already failed to add. This can happen if
342 // we consider a transaction in mapModifiedTx and it fails: we can then
343 // potentially consider it again while walking mapTx. It's currently
344 // guaranteed to fail again, but as a belt-and-suspenders check we put it in
345 // failedTx and avoid re-evaluation, since the re-evaluation would be using
346 // cached size/sigops/fee values that are not actually correct.
348 {
349  assert (it != mempool.mapTx.end());
350  if (mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it))
351  return true;
352  return false;
353 }
354 
355 void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
356 {
357  // Sort package by ancestor count
358  // If a transaction A depends on transaction B, then A's ancestor count
359  // must be greater than B's. So this is sufficient to validly order the
360  // transactions for block inclusion.
361  sortedEntries.clear();
362  sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
363  std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
364 }
365 
366 // This transaction selection algorithm orders the mempool based
367 // on feerate of a transaction including all unconfirmed ancestors.
368 // Since we don't remove transactions from the mempool as we select them
369 // for block inclusion, we need an alternate method of updating the feerate
370 // of a transaction with its not-yet-selected ancestors as we go.
371 // This is accomplished by walking the in-mempool descendants of selected
372 // transactions and storing a temporary modified state in mapModifiedTxs.
373 // Each time through the loop, we compare the best transaction in
374 // mapModifiedTxs with the next transaction in the mempool to decide what
375 // transaction package to work on next.
377 {
378  // mapModifiedTx will store sorted packages after they are modified
379  // because some of their txs are already in the block
380  indexed_modified_transaction_set mapModifiedTx;
381  // Keep track of entries that failed inclusion, to avoid duplicate work
382  CTxMemPool::setEntries failedTx;
383 
384  // Start by adding all descendants of previously added txs to mapModifiedTx
385  // and modifying them for their already included ancestors
386  UpdatePackagesForAdded(inBlock, mapModifiedTx);
387 
388  CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
389  CTxMemPool::txiter iter;
390  while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
391  {
392  // First try to find a new transaction in mapTx to evaluate.
393  if (mi != mempool.mapTx.get<ancestor_score>().end() &&
394  SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
395  ++mi;
396  continue;
397  }
398 
399  // Now that mi is not stale, determine which transaction to evaluate:
400  // the next entry from mapTx, or the best from mapModifiedTx?
401  bool fUsingModified = false;
402 
403  modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
404  if (mi == mempool.mapTx.get<ancestor_score>().end()) {
405  // We're out of entries in mapTx; use the entry from mapModifiedTx
406  iter = modit->iter;
407  fUsingModified = true;
408  } else {
409  // Try to compare the mapTx entry to the mapModifiedTx entry
410  iter = mempool.mapTx.project<0>(mi);
411  if (modit != mapModifiedTx.get<ancestor_score>().end() &&
413  // The best entry in mapModifiedTx has higher score
414  // than the one from mapTx.
415  // Switch which transaction (package) to consider
416  iter = modit->iter;
417  fUsingModified = true;
418  } else {
419  // Either no entry in mapModifiedTx, or it's worse than mapTx.
420  // Increment mi for the next loop iteration.
421  ++mi;
422  }
423  }
424 
425  // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
426  // contain anything that is inBlock.
427  assert(!inBlock.count(iter));
428 
429  uint64_t packageSize = iter->GetSizeWithAncestors();
430  CAmount packageFees = iter->GetModFeesWithAncestors();
431  unsigned int packageSigOps = iter->GetSigOpCountWithAncestors();
432  if (fUsingModified) {
433  packageSize = modit->nSizeWithAncestors;
434  packageFees = modit->nModFeesWithAncestors;
435  packageSigOps = modit->nSigOpCountWithAncestors;
436  }
437 
438  if (packageFees < ::minRelayTxFee.GetFee(packageSize)) {
439  // Everything else we might consider has a lower fee rate
440  return;
441  }
442 
443  if (!TestPackage(packageSize, packageSigOps)) {
444  if (fUsingModified) {
445  // Since we always look at the best entry in mapModifiedTx,
446  // we must erase failed entries so that we can consider the
447  // next best entry on the next loop iteration
448  mapModifiedTx.get<ancestor_score>().erase(modit);
449  failedTx.insert(iter);
450  }
451  continue;
452  }
453 
454  CTxMemPool::setEntries ancestors;
455  uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
456  std::string dummy;
457  mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
458 
459  onlyUnconfirmed(ancestors);
460  ancestors.insert(iter);
461 
462  // Test if all tx's are Final
463  if (!TestPackageFinality(ancestors)) {
464  if (fUsingModified) {
465  mapModifiedTx.get<ancestor_score>().erase(modit);
466  failedTx.insert(iter);
467  }
468  continue;
469  }
470 
471  // Package can be added. Sort the entries in a valid order.
472  std::vector<CTxMemPool::txiter> sortedEntries;
473  SortForBlock(ancestors, iter, sortedEntries);
474 
475  for (size_t i = 0; i < sortedEntries.size(); ++i) {
476  CTxMemPool::txiter& iterSortedEntries = sortedEntries[i];
477  if (iterSortedEntries->IsShielded()) {
478  // Don't add SHIELD transactions if in maintenance (SPORK_20)
480  break;
481  }
482  // Don't add SHIELD transactions if there's no reserved space left in the block
483  if (nSizeShielded + iterSortedEntries->GetTxSize() > MAX_BLOCK_SHIELDED_TXES_SIZE) {
484  break;
485  }
486  // Update cumulative size of SHIELD transactions in this block
487  nSizeShielded += iterSortedEntries->GetTxSize();
488  }
489  AddToBlock(iterSortedEntries);
490  // Erase from the modified set, if present
491  mapModifiedTx.erase(iterSortedEntries);
492  }
493 
494  // Update transactions that depend on each of these
495  UpdatePackagesForAdded(ancestors, mapModifiedTx);
496  }
497 }
498 
500 {
501  // Update header
503 }
504 
505 uint256 CalculateSaplingTreeRoot(CBlock* pblock, int nHeight, const CChainParams& chainparams)
506 {
507  if (NetworkUpgradeActive(nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_V5_0)) {
508  SaplingMerkleTree sapling_tree;
509  assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(), sapling_tree));
510 
511  // Update the Sapling commitment tree.
512  for (const auto &tx : pblock->vtx) {
513  if (tx->IsShieldedTx()) {
514  for (const OutputDescription &odesc : tx->sapData->vShieldedOutput) {
515  sapling_tree.append(odesc.cmu);
516  }
517  }
518  }
519  return sapling_tree.root();
520  }
521  return UINT256_ZERO;
522 }
523 
524 bool SolveBlock(std::shared_ptr<CBlock>& pblock, int nHeight)
525 {
526  unsigned int extraNonce = 0;
527  IncrementExtraNonce(pblock, nHeight, extraNonce);
528  while (pblock->nNonce < std::numeric_limits<uint32_t>::max() &&
529  !CheckProofOfWork(pblock->GetHash(), pblock->nBits)) {
530  ++pblock->nNonce;
531  }
532  return pblock->nNonce != std::numeric_limits<uint32_t>::max();
533 }
534 
535 void IncrementExtraNonce(std::shared_ptr<CBlock>& pblock, int nHeight, unsigned int& nExtraNonce)
536 {
537  // Update nExtraNonce
538  static uint256 hashPrevBlock;
539  if (hashPrevBlock != pblock->hashPrevBlock) {
540  nExtraNonce = 0;
541  hashPrevBlock = pblock->hashPrevBlock;
542  }
543  ++nExtraNonce;
544  CMutableTransaction txCoinbase(*pblock->vtx[0]);
545  txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
546  assert(txCoinbase.vin[0].scriptSig.size() <= 100);
547 
548  pblock->vtx[0] = MakeTransactionRef(txCoinbase);
549  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
550 }
551 
552 int32_t ComputeBlockVersion(const Consensus::Params& consensus, int nHeight)
553 {
554  if (NetworkUpgradeActive(nHeight, consensus, Consensus::UPGRADE_V5_0)) {
555  return CBlockHeader::CURRENT_VERSION; // v11 (since 5.2.99)
556  } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V4_0)) {
557  return 7;
558  } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_V3_4)) {
559  return 6;
560  } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_BIP65)) {
561  return 5;
562  } else if (consensus.NetworkUpgradeActive(nHeight, Consensus::UPGRADE_ZC)) {
563  return 4;
564  } else {
565  return 3;
566  }
567 }
568 
int64_t CAmount
Amount in PIV (Can be negative)
Definition: amount.h:13
void IncrementExtraNonce(std::shared_ptr< CBlock > &pblock, int nHeight, unsigned int &nExtraNonce)
uint64_t nLastBlockTx
int32_t ComputeBlockVersion(const Consensus::Params &consensus, int nHeight)
CMutableTransaction CreateCoinbaseTx(const CScript &scriptPubKeyIn, CBlockIndex *pindexPrev)
bool SolveBlock(std::shared_ptr< CBlock > &pblock, int nHeight)
Modify the nonce/extranonce in a block.
int64_t UpdateTime(CBlockHeader *pblock, const Consensus::Params &consensusParams, const CBlockIndex *pindexPrev)
uint256 CalculateSaplingTreeRoot(CBlock *pblock, int nHeight, const CChainParams &chainparams)
bool SolveProofOfStake(CBlock *pblock, CBlockIndex *pindexPrev, CWallet *pwallet, std::vector< CStakeableOutput > *availableCoins, bool stopPoSOnNewBlock)
uint64_t nLastBlockSize
indexed_modified_transaction_set::nth_index< 0 >::type::iterator modtxiter
indexed_modified_transaction_set::index< ancestor_score >::type::iterator modtxscoreiter
boost::multi_index_container< CTxMemPoolModifiedEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique< modifiedentry_iter, CompareCTxMemPoolIter >, boost::multi_index::ordered_non_unique< boost::multi_index::tag< ancestor_score >, boost::multi_index::identity< CTxMemPoolModifiedEntry >, CompareModifiedEntry > >> indexed_modified_transaction_set
bool SignBlock(CBlock &block, const CKeyStore &keystore)
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:449
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:465
uint256 hash
Definition: transaction.h:35
uint32_t n
Definition: transaction.h:36
void AddToBlock(CTxMemPool::txiter iter)
Add a tx to the block.
std::unique_ptr< CBlockTemplate > CreateNewBlock(const CScript &scriptPubKeyIn, CWallet *pwallet=nullptr, bool fProofOfStake=false, std::vector< CStakeableOutput > *availableCoins=nullptr, bool fNoMempoolTx=false, bool fTestValidity=true, CBlockIndex *prevBlock=nullptr, bool stopPoSOnNewBlock=true, bool fIncludeQfc=true)
Construct a new block template with coinbase to scriptPubKeyIn.
CTxMemPool::setEntries inBlock
void addPackageTxs()
Add transactions based on feerate including unconfirmed ancestors.
bool TestPackageFinality(const CTxMemPool::setEntries &package)
Test if a set of transactions are all final.
unsigned int nBlockMaxSize
void SortForBlock(const CTxMemPool::setEntries &package, CTxMemPool::txiter entry, std::vector< CTxMemPool::txiter > &sortedEntries)
Sort the package in an order that is valid to appear in a block.
void onlyUnconfirmed(CTxMemPool::setEntries &testSet)
Remove confirmed (inBlock) entries from given set.
uint64_t nBlockSize
void appendSaplingTreeRoot()
Add the tip updated incremental merkle tree to the header.
BlockAssembler(const CChainParams &chainparams, const bool defaultPrintPriority)
unsigned int nSizeShielded
void resetBlock()
Clear the block's state and prepare for assembling a new block.
std::unique_ptr< CBlockTemplate > pblocktemplate
const CChainParams & chainparams
void UpdatePackagesForAdded(const CTxMemPool::setEntries &alreadyAdded, indexed_modified_transaction_set &mapModifiedTx)
Add descendants of given transactions to mapModifiedTx with ancestor state updated assuming given tra...
unsigned int nBlockSigOps
bool SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
Return true if given transaction from mapTx has already been evaluated, or if the transaction's cache...
const bool defaultPrintPriority
bool TestPackage(uint64_t packageSize, unsigned int packageSigOps)
Test if a new package would "fit" in the block.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
static const int32_t CURRENT_VERSION
Definition: block.h:26
uint32_t nNonce
Definition: block.h:32
uint256 hashFinalSaplingRoot
Definition: block.h:34
uint32_t nBits
Definition: block.h:31
uint32_t nTime
Definition: block.h:30
int32_t nVersion
Definition: block.h:27
uint256 hashPrevBlock
Definition: block.h:28
uint256 hashMerkleRoot
Definition: block.h:29
uint256 GetHash() const
Definition: block.cpp:15
Definition: block.h:80
std::vector< CTransactionRef > vtx
Definition: block.h:83
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:139
uint256 GetBlockHash() const
Definition: chain.h:215
int64_t GetMedianTimePast() const
Definition: chain.cpp:204
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:151
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:405
CChainParams defines various tweakable parameters of a given instance of the PIVX system.
Definition: chainparams.h:43
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:72
Fee rate in PIV per kilobyte: CAmount / kB.
Definition: feerate.h:20
std::string ToString() const
Definition: feerate.cpp:31
CAmount GetFee(size_t size) const
Definition: feerate.cpp:21
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:72
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:381
bool IsSporkActive(SporkId nSporkID)
Definition: spork.cpp:220
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:471
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:149
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:481
indexed_transaction_set::nth_index< 0 >::type::iterator txiter
Definition: txmempool.h:474
indexed_transaction_set mapTx
Definition: txmempool.h:472
void CalculateDescendants(txiter it, setEntries &setDescendants)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:578
Capture information about block/transaction validation.
Definition: validation.h:24
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
Definition: wallet.h:577
A shielded output to a transaction.
uint256 cmu
The u-coordinate of the note commitment for the output note.
std::string ToString() const
Definition: uint256.cpp:65
std::string GetHex() const
Definition: uint256.cpp:21
256-bit opaque blob.
Definition: uint256.h:138
bool CreateCoinStake(const CBlockIndex *pindexPrev, unsigned int nBits, CMutableTransaction &txNew, int64_t &nTxNewTime, std::vector< CStakeableOutput > *availableCoins, bool stopOnNewBlock=true) const
Definition: wallet.cpp:3367
bool SignCoinStake(CMutableTransaction &txNew) const
Definition: wallet.cpp:3475
void BlockUntilSyncedToCurrentChain()
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1383
@ LOCK
Definition: lockunlock.h:16
#define LogPrint(category,...)
Definition: logging.h:163
void FillBlockPayee(CMutableTransaction &txCoinbase, CMutableTransaction &txCoinstake, const CBlockIndex *pindexPrev, bool fProofOfStake)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:154
@ STAKING
Definition: logging.h:58
@ UPGRADE_V4_0
Definition: params.h:35
@ UPGRADE_V3_4
Definition: params.h:34
@ UPGRADE_V6_0
Definition: params.h:41
@ UPGRADE_V5_0
Definition: params.h:36
@ UPGRADE_BIP65
Definition: params.h:32
@ UPGRADE_ZC
Definition: params.h:30
std::unique_ptr< CQuorumBlockProcessor > quorumBlockProcessor
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:80
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:122
unsigned int GetNextWorkRequired(const CBlockIndex *pindexLast, const CBlockHeader *pblock)
Definition: pow.cpp:19
@ OP_0
Definition: script.h:52
CSporkManager sporkManager
Definition: spork.cpp:29
@ SPORK_20_SAPLING_MAINTENANCE
Definition: sporkid.h:27
A mutable version of CTransaction.
Definition: transaction.h:409
std::vector< CTxOut > vout
Definition: transaction.h:411
std::vector< CTxIn > vin
Definition: transaction.h:410
unsigned int nSigOpCountWithAncestors
uint64_t nSizeWithAncestors
CAmount nModFeesWithAncestors
Parameters that influence chain consensus.
Definition: params.h:171
bool NetworkUpgradeActive(int nHeight, Consensus::UpgradeIndex idx) const
Returns true if the given network upgrade is active as of the given block height.
Definition: params.cpp:12
bool fPowAllowMinDifficultyBlocks
Definition: params.h:173
#define LOCK2(cs1, cs2)
Definition: sync.h:221
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:247
ArgsManager gArgs
Definition: system.cpp:89
bool error(const char *fmt, const Args &... args)
Definition: system.h:77
int64_t GetAdjustedTime()
Definition: timedata.cpp:36
#define strprintf
Definition: tinyformat.h:1056
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:456
bool IsFinalTx(const CTransactionRef &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
Definition: tx_verify.cpp:12
unsigned int GetLegacySigOpCount(const CTransaction &tx)
Count ECDSA signature operations the old-fashioned (pre-0.6) way.
Definition: tx_verify.cpp:27
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:175
bool NetworkUpgradeActive(int nHeight, const Consensus::Params &params, Consensus::UpgradeIndex idx)
Returns true if the given network upgrade is active as of the given block height.
Definition: upgrades.cpp:107
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:13
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
Fees smaller than this (in upiv) are considered zero fee (for relaying, mining and transaction creati...
Definition: validation.cpp:108
CScript COINBASE_FLAGS
Constant stuff for coinbase transactions we create:
Definition: validation.cpp:119
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:206
CAmount GetBlockValue(int nHeight)
Definition: validation.cpp:816
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:84
bool TestBlockValidity(CValidationState &state, const CBlock &block, CBlockIndex *const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckBlockSig)
Check a block is completely valid from start to finish (only works on top of our current best block,...