Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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 <key_io.h>
15#include <node/context.h>
16#include <node/miner.h>
17#include <pow.h>
18#include <primitives/block.h>
20#include <script/script.h>
21#include <sync.h>
22#include <test/util/script.h>
23#include <uint256.h>
24#include <util/check.h>
25#include <validation.h>
26#include <validationinterface.h>
27#include <versionbits.h>
28
29#include <cstdint>
30#include <memory>
31#include <optional>
32#include <utility>
33
35
36COutPoint generatetoaddress(const NodeContext& node, const std::string& address)
37{
38 const auto dest = DecodeDestination(address);
40 return MineBlock(node, {
41 .coinbase_output_script = GetScriptForDestination(dest),
42 });
43}
44
45std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)
46{
47 std::vector<std::shared_ptr<CBlock>> ret{total_height};
48 auto time{params.GenesisBlock().nTime};
49 // NOTE: here `height` does not correspond to the block height but the block height - 1.
50 for (size_t height{0}; height < total_height; ++height) {
51 CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};
52
54 coinbase_tx.nLockTime = static_cast<uint32_t>(height);
55 coinbase_tx.vin = {
56 CTxIn{
57 COutPoint{},
58 CScript{} << (height + 1) << OP_0, // Always include OP_0 as a dummy extraNonce.
59 CTxIn::MAX_SEQUENCE_NONFINAL, // Make sure timelock is enforced.
60 },
61 };
62 coinbase_tx.vout = {
63 CTxOut{GetBlockSubsidy(height + 1, params.GetConsensus()), P2WSH_OP_TRUE},
64 };
65 block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
66
68 block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();
69 block.hashMerkleRoot = BlockMerkleRoot(block);
70 block.nTime = ++time;
71 block.nBits = params.GenesisBlock().nBits;
72 block.nNonce = 0;
73
74 while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {
75 ++block.nNonce;
76 assert(block.nNonce);
77 }
78 }
79 return ret;
80}
81
82bool BuildChain(const NodeContext& node, const CBlockIndex* pindex,
84 size_t length,
85 std::vector<std::shared_ptr<CBlock>>& chain)
86{
87 auto& block_template_manager{*Assert(node.block_template_manager)};
88 const Consensus::Params& consensus{Assert(node.chainman)->GetConsensus()};
89
90 chain.resize(length);
91 for (auto& chain_block : chain) {
92 auto block_template{block_template_manager.CreateNewTemplate({
93 .use_mempool = false,
94 .coinbase_output_script = coinbase_script_pub_key,
95 })};
96 CBlock block{Assert(block_template)->block};
97
98 // The template is built on the active tip, so repoint it at pindex and
99 // redo the fields that depend on the predecessor.
100 block.hashPrevBlock = pindex->GetBlockHash();
101 block.nTime = pindex->nTime + 1;
102 {
103 CMutableTransaction tx_coinbase{*block.vtx.at(0)};
104 tx_coinbase.nLockTime = static_cast<uint32_t>(pindex->nHeight);
105 tx_coinbase.vin.at(0).scriptSig = CScript{} << pindex->nHeight + 1;
106 block.vtx.at(0) = MakeTransactionRef(std::move(tx_coinbase));
107 block.hashMerkleRoot = BlockMerkleRoot(block);
108 }
109
110 while (!CheckProofOfWork(block.GetHash(), block.nBits, consensus)) ++block.nNonce;
111
112 chain_block = std::make_shared<CBlock>(std::move(block));
113
115 if (!Assert(node.chainman)->ProcessNewBlockHeaders({{*chain_block}}, true, state, &pindex)) {
116 return false;
117 }
118 }
119
120 return true;
121}
122
124{
125 auto block = PrepareBlock(node, assembler_options);
126 auto valid = MineBlock(node, block);
127 assert(!valid.IsNull());
128 return valid;
129}
130
131COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)
132{
133 while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
134 ++block->nNonce;
135 assert(block->nNonce);
136 }
137
138 return ProcessBlock(node, block);
139}
140
141COutPoint ProcessBlock(const NodeContext& node, const std::shared_ptr<CBlock>& block)
142{
143 auto& chainman{*Assert(node.chainman)};
144 const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());
145 bool new_block;
146 node::BlockValidationStateCatcher bvsc{block->GetHash()};
147 node.validation_signals->RegisterValidationInterface(&bvsc);
148 const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};
149 const bool duplicate{!new_block && processed};
151 node.validation_signals->UnregisterValidationInterface(&bvsc);
152 node.validation_signals->SyncWithValidationInterfaceQueue();
153 const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};
154 assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));
155
156 if (was_valid) return {block->vtx[0]->GetHash(), 0};
157 return {};
158}
159
160std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,
162{
163 auto& block_template_manager = *Assert(node.block_template_manager);
164 auto block_template = block_template_manager.CreateNewTemplate(assembler_options);
165 auto block = std::make_shared<CBlock>(Assert(block_template)->block);
166
167 LOCK(cs_main);
168 block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
169 block->hashMerkleRoot = BlockMerkleRoot(*block);
170
171 return block;
172}
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:119
uint32_t nBits
Definition block.h:34
uint32_t nTime
Definition block.h:33
uint256 hashPrevBlock
Definition block.h:31
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:30
Serialized script, used inside transaction inputs and outputs.
Definition script.h:406
An input of a transaction.
Definition transaction.h:63
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:83
An output of a transaction.
Captures the validation state reported for a specific block.
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition merkle.cpp:76
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:297
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)
static RPCMethod generatetoaddress()
Definition mining.cpp:294
@ OP_0
Definition script.h:77
A mutable version of CTransaction.
Parameters that influence chain consensus.
Definition params.h:88
Block template creation options.
NodeContext struct containing references to chain state and connection state.
Definition context.h:57
#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:160
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:141
COutPoint MineBlock(const NodeContext &node, const node::BlockCreateOptions &assembler_options)
Returns the generated coin.
Definition mining.cpp:123
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:82
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition mining.cpp:45
static const CScript P2WSH_OP_TRUE
Definition script.h:13
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
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