Bitcoin Core  29.1.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2022 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 <test/util/mining.h>
6 
7 #include <chainparams.h>
8 #include <consensus/merkle.h>
9 #include <consensus/validation.h>
10 #include <key_io.h>
11 #include <node/context.h>
12 #include <pow.h>
13 #include <primitives/transaction.h>
14 #include <test/util/script.h>
15 #include <util/check.h>
16 #include <validation.h>
17 #include <validationinterface.h>
18 #include <versionbits.h>
19 
21 using node::NodeContext;
22 
23 COutPoint generatetoaddress(const NodeContext& node, const std::string& address)
24 {
25  const auto dest = DecodeDestination(address);
27  BlockAssembler::Options assembler_options;
28  assembler_options.coinbase_output_script = GetScriptForDestination(dest);
29 
30  return MineBlock(node, assembler_options);
31 }
32 
33 std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)
34 {
35  std::vector<std::shared_ptr<CBlock>> ret{total_height};
36  auto time{params.GenesisBlock().nTime};
37  for (size_t height{0}; height < total_height; ++height) {
38  CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};
39 
40  CMutableTransaction coinbase_tx;
41  coinbase_tx.vin.resize(1);
42  coinbase_tx.vin[0].prevout.SetNull();
43  coinbase_tx.vout.resize(1);
44  coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE;
45  coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus());
46  coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0;
47  block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
48 
49  block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;
50  block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();
51  block.hashMerkleRoot = BlockMerkleRoot(block);
52  block.nTime = ++time;
53  block.nBits = params.GenesisBlock().nBits;
54  block.nNonce = 0;
55 
56  while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {
57  ++block.nNonce;
58  assert(block.nNonce);
59  }
60  }
61  return ret;
62 }
63 
65 {
66  auto block = PrepareBlock(node, assembler_options);
67  auto valid = MineBlock(node, block);
68  assert(!valid.IsNull());
69  return valid;
70 }
71 
73  const uint256 m_hash;
74  std::optional<BlockValidationState> m_state;
75 
77  : m_hash{hash},
78  m_state{} {}
79 
80 protected:
81  void BlockChecked(const CBlock& block, const BlockValidationState& state) override
82  {
83  if (block.GetHash() != m_hash) return;
84  m_state = state;
85  }
86 };
87 
88 COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)
89 {
90  while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
91  ++block->nNonce;
92  assert(block->nNonce);
93  }
94 
95  auto& chainman{*Assert(node.chainman)};
96  const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());
97  bool new_block;
98  BlockValidationStateCatcher bvsc{block->GetHash()};
99  node.validation_signals->RegisterValidationInterface(&bvsc);
100  const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};
101  const bool duplicate{!new_block && processed};
102  assert(!duplicate);
103  node.validation_signals->UnregisterValidationInterface(&bvsc);
104  node.validation_signals->SyncWithValidationInterfaceQueue();
105  const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};
106  assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));
107 
108  if (was_valid) return {block->vtx[0]->GetHash(), 0};
109  return {};
110 }
111 
112 std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,
113  const BlockAssembler::Options& assembler_options)
114 {
115  auto block = std::make_shared<CBlock>(
116  BlockAssembler{Assert(node.chainman)->ActiveChainstate(), Assert(node.mempool.get()), assembler_options}
117  .CreateNewBlock()
118  ->block);
119 
120  LOCK(cs_main);
121  block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
122  block->hashMerkleRoot = BlockMerkleRoot(*block);
123 
124  return block;
125 }
126 std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey)
127 {
128  BlockAssembler::Options assembler_options;
129  assembler_options.coinbase_output_script = coinbase_scriptPubKey;
130  ApplyArgsManOptions(*node.args, assembler_options);
131  return PrepareBlock(node, assembler_options);
132 }
int ret
std::shared_ptr< CBlock > PrepareBlock(const NodeContext &node, const BlockAssembler::Options &assembler_options)
Definition: mining.cpp:112
void BlockChecked(const CBlock &block, const BlockValidationState &state) override
Notifies listeners of a block validation result.
Definition: mining.cpp:81
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())
Generate a new block, without valid proof-of-work.
Definition: miner.h:143
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
Definition: block.h:68
std::vector< CTxIn > vin
Definition: transaction.h:379
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
const uint256 m_hash
Definition: mining.cpp:73
const CBlock & GenesisBlock() const
Definition: chainparams.h:98
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:80
Definition: script.h:76
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
Implement this to subscribe to events generated in validation and mempool.
uint32_t nTime
Definition: block.h:28
std::optional< BlockValidationState > m_state
Definition: mining.cpp:74
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
COutPoint MineBlock(const NodeContext &node, const node::BlockAssembler::Options &assembler_options)
Returns the generated coin.
Definition: mining.cpp:64
#define LOCK(cs)
Definition: sync.h:257
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:140
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
std::vector< CTxOut > vout
Definition: transaction.h:380
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
Definition: messages.h:20
uint256 GetHash() const
Definition: block.cpp:11
256-bit opaque blob.
Definition: uint256.h:201
const CChainParams & Params()
Return the currently selected parameters.
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:14
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
A mutable version of CTransaction.
Definition: transaction.h:377
BlockValidationStateCatcher(const uint256 &hash)
Definition: mining.cpp:76
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:299
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition: mining.cpp:33
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
COutPoint generatetoaddress(const NodeContext &node, const std::string &address)
RPC-like helper function, returns the generated coin.
Definition: mining.cpp:23
#define Assert(val)
Identity function.
Definition: check.h:85
uint32_t nBits
Definition: block.h:29