Bitcoin Core 31.99.0
P2P Digital Currency
mining.cpp
Go to the documentation of this file.
1// Copyright (c) 2019-present 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 <addresstype.h>
8#include <chain.h>
9#include <chainparams.h>
10#include <consensus/merkle.h>
12#include <interfaces/mining.h>
13#include <key_io.h>
14#include <node/context.h>
15#include <pow.h>
16#include <primitives/block.h>
18#include <script/script.h>
19#include <sync.h>
20#include <test/util/script.h>
21#include <uint256.h>
22#include <util/check.h>
23#include <validation.h>
24#include <validationinterface.h>
25#include <versionbits.h>
26
27#include <cstdint>
28#include <memory>
29#include <optional>
30#include <utility>
31
33
34COutPoint generatetoaddress(const NodeContext& node, const std::string& address)
35{
36 const auto dest = DecodeDestination(address);
38 return MineBlock(node, {
39 .coinbase_output_script = GetScriptForDestination(dest),
40 });
41}
42
43std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)
44{
45 std::vector<std::shared_ptr<CBlock>> ret{total_height};
46 auto time{params.GenesisBlock().nTime};
47 // NOTE: here `height` does not correspond to the block height but the block height - 1.
48 for (size_t height{0}; height < total_height; ++height) {
49 CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};
50
51 CMutableTransaction coinbase_tx;
52 coinbase_tx.nLockTime = static_cast<uint32_t>(height);
53 coinbase_tx.vin.resize(1);
54 coinbase_tx.vin[0].prevout.SetNull();
55 coinbase_tx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
56 coinbase_tx.vout.resize(1);
57 coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE;
58 coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus());
59 // Always include OP_0 as a dummy extraNonce.
60 coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0;
61 block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
62
64 block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();
65 block.hashMerkleRoot = BlockMerkleRoot(block);
66 block.nTime = ++time;
67 block.nBits = params.GenesisBlock().nBits;
68 block.nNonce = 0;
69
70 while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {
71 ++block.nNonce;
72 assert(block.nNonce);
73 }
74 }
75 return ret;
76}
77
78bool BuildChain(const NodeContext& node, const CBlockIndex* pindex,
79 const CScript& coinbase_script_pub_key,
80 size_t length,
81 std::vector<std::shared_ptr<CBlock>>& chain)
82{
83 auto mining{interfaces::MakeMining(node)};
84 const Consensus::Params& consensus{Assert(node.chainman)->GetConsensus()};
85
86 chain.resize(length);
87 for (auto& chain_block : chain) {
88 auto block_template{mining->createNewBlock({
89 .use_mempool = false,
90 .coinbase_output_script = coinbase_script_pub_key,
91 }, /*cooldown=*/false)};
92 CBlock block{Assert(block_template)->getBlock()};
93
94 // The template is built on the active tip, so repoint it at pindex and
95 // redo the fields that depend on the predecessor.
96 block.hashPrevBlock = pindex->GetBlockHash();
97 block.nTime = pindex->nTime + 1;
98 {
99 CMutableTransaction tx_coinbase{*block.vtx.at(0)};
100 tx_coinbase.nLockTime = static_cast<uint32_t>(pindex->nHeight);
101 tx_coinbase.vin.at(0).scriptSig = CScript{} << pindex->nHeight + 1;
102 block.vtx.at(0) = MakeTransactionRef(std::move(tx_coinbase));
103 block.hashMerkleRoot = BlockMerkleRoot(block);
104 }
105
106 while (!CheckProofOfWork(block.GetHash(), block.nBits, consensus)) ++block.nNonce;
107
108 chain_block = std::make_shared<CBlock>(std::move(block));
109
111 if (!Assert(node.chainman)->ProcessNewBlockHeaders({{*chain_block}}, true, state, &pindex)) {
112 return false;
113 }
114 }
115
116 return true;
117}
118
120{
121 auto block = PrepareBlock(node, assembler_options);
122 auto valid = MineBlock(node, block);
123 assert(!valid.IsNull());
124 return valid;
125}
126
129 std::optional<BlockValidationState> m_state;
130
132 : m_hash{hash},
133 m_state{} {}
134
135protected:
136 void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override
137 {
138 if (block->GetHash() != m_hash) return;
139 m_state = state;
140 }
141};
142
143COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)
144{
145 while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
146 ++block->nNonce;
147 assert(block->nNonce);
148 }
149
150 return ProcessBlock(node, block);
151}
152
153COutPoint ProcessBlock(const NodeContext& node, const std::shared_ptr<CBlock>& block)
154{
155 auto& chainman{*Assert(node.chainman)};
156 const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());
157 bool new_block;
158 BlockValidationStateCatcher bvsc{block->GetHash()};
159 node.validation_signals->RegisterValidationInterface(&bvsc);
160 const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};
161 const bool duplicate{!new_block && processed};
162 assert(!duplicate);
163 node.validation_signals->UnregisterValidationInterface(&bvsc);
164 node.validation_signals->SyncWithValidationInterfaceQueue();
165 const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};
166 assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));
167
168 if (was_valid) return {block->vtx[0]->GetHash(), 0};
169 return {};
170}
171
172std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,
173 const node::BlockCreateOptions& assembler_options)
174{
175 auto mining = interfaces::MakeMining(node);
176 auto block_template = mining->createNewBlock(assembler_options, /*cooldown=*/false);
177 auto block = std::make_shared<CBlock>(Assert(block_template)->getBlock());
178
179 LOCK(cs_main);
180 block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
181 block->hashMerkleRoot = BlockMerkleRoot(*block);
182
183 return block;
184}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
int ret
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:116
uint32_t nBits
Definition: block.h:34
uint32_t nTime
Definition: block.h:33
Definition: block.h:74
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:94
uint32_t nTime
Definition: chain.h:142
uint256 GetBlockHash() const
Definition: chain.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:106
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
const CBlock & GenesisBlock() const
Definition: chainparams.h:94
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:89
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
static constexpr uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:82
Implement this to subscribe to events generated in validation and mempool.
256-bit opaque blob.
Definition: uint256.h:196
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:77
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:300
std::unique_ptr< Mining > MakeMining(const node::NodeContext &node, bool wait_loaded=true)
Return implementation of Mining interface.
Definition: messages.h:21
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
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
@ OP_0
Definition: script.h:77
void BlockChecked(const std::shared_ptr< const CBlock > &block, const BlockValidationState &state) override
Notifies listeners of a block validation result.
Definition: mining.cpp:136
BlockValidationStateCatcher(const uint256 &hash)
Definition: mining.cpp:131
std::optional< BlockValidationState > m_state
Definition: mining.cpp:129
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
Parameters that influence chain consensus.
Definition: params.h:88
Block template creation options.
Definition: mining_types.h:33
NodeContext struct containing references to chain state and connection state.
Definition: context.h:59
#define LOCK(cs)
Definition: sync.h:268
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
std::shared_ptr< CBlock > PrepareBlock(const NodeContext &node, const node::BlockCreateOptions &assembler_options)
Prepare a block to be mined.
Definition: mining.cpp:172
COutPoint generatetoaddress(const NodeContext &node, const std::string &address)
RPC-like helper function, returns the generated coin.
Definition: mining.cpp:34
COutPoint ProcessBlock(const NodeContext &node, const std::shared_ptr< CBlock > &block)
Returns the generated coin (or Null if the block was invalid).
Definition: mining.cpp:153
COutPoint MineBlock(const NodeContext &node, const node::BlockCreateOptions &assembler_options)
Returns the generated coin.
Definition: mining.cpp:119
bool BuildChain(const NodeContext &node, const CBlockIndex *pindex, const CScript &coinbase_script_pub_key, size_t length, std::vector< std::shared_ptr< CBlock > > &chain)
Build a chain of length coinbase-only blocks on top of pindex (which need not be the active tip,...
Definition: mining.cpp:78
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition: mining.cpp:43
const CScript P2WSH_OP_TRUE
Definition: script.h:13
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())
constexpr int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:19