BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
block_assemble.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2018 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <bench/bench.h>
6 #include <chainparams.h>
7 #include <coins.h>
8 #include <consensus/merkle.h>
9 #include <consensus/validation.h>
10 #include <miner.h>
11 #include <policy/policy.h>
12 #include <pow.h>
13 #include <scheduler.h>
14 #include <txdb.h>
15 #include <txmempool.h>
16 #include <utiltime.h>
17 #include <validation.h>
18 #include <validationinterface.h>
19 
20 #include <boost/thread.hpp>
21 
22 #include <list>
23 #include <vector>
24 
25 static std::shared_ptr<CBlock> PrepareBlock(const CScript& coinbase_scriptPubKey)
26 {
27  auto block = std::make_shared<CBlock>(
29  .CreateNewBlock(coinbase_scriptPubKey, /* fMineWitnessTx */ true)
30  ->block);
31 
32  block->nTime = ::chainActive.Tip()->GetMedianTimePast() + 1;
33  block->hashMerkleRoot = BlockMerkleRoot(*block);
34 
35  return block;
36 }
37 
38 
39 static CTxIn MineBlock(const CScript& coinbase_scriptPubKey)
40 {
41  auto block = PrepareBlock(coinbase_scriptPubKey);
42 
43  while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
44  ++block->nNonce;
45  assert(block->nNonce);
46  }
47 
48  bool processed{ProcessNewBlock(Params(), block, true, nullptr)};
49  assert(processed);
50 
51  return CTxIn{block->vtx[0]->GetHash(), 0};
52 }
53 
54 
55 static void AssembleBlock(benchmark::State& state)
56 {
57  const std::vector<unsigned char> op_true{OP_TRUE};
58  CScriptWitness witness;
59  witness.stack.push_back(op_true);
60 
61  uint256 witness_program;
62  CSHA3().Write(&op_true[0], op_true.size()).Finalize(witness_program.begin());
63 
64  const CScript SCRIPT_PUB{CScript(OP_0) << std::vector<unsigned char>{witness_program.begin(), witness_program.end()}};
65 
66  // Switch to regtest so we can mine faster
67  // Also segwit is active, so we can include witness transactions
69 
71 
72  boost::thread_group thread_group;
73  CScheduler scheduler;
74  {
75  ::pblocktree.reset(new CBlockTreeDB(1 << 20, true));
76  ::pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));
77  ::pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));
78 
79  const CChainParams& chainparams = Params();
80  thread_group.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler));
82  LoadGenesisBlock(chainparams);
83  CValidationState state;
84  ActivateBestChain(state, chainparams);
85  assert(::chainActive.Tip() != nullptr);
86  const bool witness_enabled{IsWitnessEnabled(::chainActive.Tip(), chainparams.GetConsensus())};
87  assert(witness_enabled);
88  }
89 
90  // Collect some loose transactions that spend the coinbases of our mined blocks
91  constexpr size_t NUM_BLOCKS{200};
92  std::array<CTransactionRef, NUM_BLOCKS - COINBASE_MATURITY + 1> txs;
93  for (size_t b{0}; b < NUM_BLOCKS; ++b) {
95  tx.vin.push_back(MineBlock(SCRIPT_PUB));
96  tx.vin.back().scriptWitness = witness;
97  tx.vout.emplace_back(1337, SCRIPT_PUB);
98  if (NUM_BLOCKS - b >= COINBASE_MATURITY)
99  txs.at(b) = MakeTransactionRef(tx);
100  }
101  {
102  LOCK(::cs_main); // Required for ::AcceptToMemoryPool.
103 
104  for (const auto& txr : txs) {
105  CValidationState state;
106  bool ret{::AcceptToMemoryPool(::mempool, state, txr, nullptr /* pfMissingInputs */, nullptr /* plTxnReplaced */, false /* bypass_limits */, /* nAbsurdFee */ 0)};
107  assert(ret);
108  }
109  }
110 
111  while (state.KeepRunning()) {
112  PrepareBlock(SCRIPT_PUB);
113  }
114 
115  thread_group.interrupt_all();
116  thread_group.join_all();
119 }
120 
121 BENCHMARK(AssembleBlock, 700);
CTxMemPool mempool
static const std::string REGTEST
bool LoadGenesisBlock(const CChainParams &chainparams)
Ensures we have a genesis block in the block tree, possibly writing one to disk.
std::vector< CTxIn > vin
Definition: transaction.h:362
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
std::vector< std::vector< unsigned char > > stack
Definition: script.h:566
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
bool ProcessNewBlock(const CChainParams &chainparams, const std::shared_ptr< const CBlock > pblock, bool fForceProcessing, bool *fNewBlock)
Process an incoming block.
unsigned char * begin()
Definition: uint256.h:56
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:402
bool ActivateBestChain(CValidationState &state, const CChainParams &chainparams, std::shared_ptr< const CBlock > pblock)
Find the best known block, and make it the tip of the block chain.
unsigned char * end()
Definition: uint256.h:61
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:986
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:298
CCriticalSection cs_main
Definition: validation.cpp:216
BENCHMARK(AssembleBlock, 700)
Access to the block database (blocks/index/)
Definition: txdb.h:86
An input of a transaction.
Definition: transaction.h:61
#define LOCK(cs)
Definition: sync.h:181
std::unique_ptr< CCoinsViewDB > pcoinsdbview
Global variable that points to the coins database (protected by cs_main)
Definition: validation.cpp:297
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given BIP70 chain name.
CMainSignals & GetMainSignals()
void serviceQueue()
Definition: scheduler.cpp:33
Generate a new block, without valid proof-of-work.
Definition: miner.h:127
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:75
std::vector< CTxOut > vout
Definition: transaction.h:363
int64_t GetMedianTimePast() const
Definition: chain.h:309
A hasher class for SHA3-256.
Definition: sha3.h:14
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
Capture information about block/transaction validation.
Definition: validation.h:26
256-bit opaque blob.
Definition: uint256.h:122
const CChainParams & Params()
Return the currently selected parameters.
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:384
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:44
void InitScriptExecutionCache()
Initializes the script-execution cache.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
CSHA3 & Write(const unsigned char *data, size_t len)
Definition: sha3.cpp:30
std::unique_ptr< CBlockTreeDB > pblocktree
Global variable that points to the active block tree (protected by cs_main)
Definition: validation.cpp:299
bool IsWitnessEnabled(const CBlockIndex *pindexPrev, const Consensus::Params &params)
Check whether witness commitments are required for block.
A mutable version of CTransaction.
Definition: transaction.h:360
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
Definition: script.h:59
Definition: script.h:51