Bitcoin Core 29.99.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>
10#include <key_io.h>
11#include <node/context.h>
12#include <pow.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
20#include <algorithm>
21#include <memory>
22
25
26COutPoint generatetoaddress(const NodeContext& node, const std::string& address)
27{
28 const auto dest = DecodeDestination(address);
30 BlockAssembler::Options assembler_options;
31 assembler_options.coinbase_output_script = GetScriptForDestination(dest);
32
33 return MineBlock(node, assembler_options);
34}
35
36std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)
37{
38 std::vector<std::shared_ptr<CBlock>> ret{total_height};
39 auto time{params.GenesisBlock().nTime};
40 // NOTE: here `height` does not correspond to the block height but the block height - 1.
41 for (size_t height{0}; height < total_height; ++height) {
42 CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};
43
44 CMutableTransaction coinbase_tx;
45 coinbase_tx.nLockTime = static_cast<uint32_t>(height);
46 coinbase_tx.vin.resize(1);
47 coinbase_tx.vin[0].prevout.SetNull();
48 coinbase_tx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
49 coinbase_tx.vout.resize(1);
50 coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE;
51 coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus());
52 coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0;
53 block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
54
56 block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();
57 block.hashMerkleRoot = BlockMerkleRoot(block);
58 block.nTime = ++time;
59 block.nBits = params.GenesisBlock().nBits;
60 block.nNonce = 0;
61
62 while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {
63 ++block.nNonce;
64 assert(block.nNonce);
65 }
66 }
67 return ret;
68}
69
71{
72 auto block = PrepareBlock(node, assembler_options);
73 auto valid = MineBlock(node, block);
74 assert(!valid.IsNull());
75 return valid;
76}
77
80 std::optional<BlockValidationState> m_state;
81
83 : m_hash{hash},
84 m_state{} {}
85
86protected:
87 void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override
88 {
89 if (block->GetHash() != m_hash) return;
90 m_state = state;
91 }
92};
93
94COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)
95{
96 while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
97 ++block->nNonce;
98 assert(block->nNonce);
99 }
100
101 return ProcessBlock(node, block);
102}
103
104COutPoint ProcessBlock(const NodeContext& node, const std::shared_ptr<CBlock>& block)
105{
106 auto& chainman{*Assert(node.chainman)};
107 const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());
108 bool new_block;
109 BlockValidationStateCatcher bvsc{block->GetHash()};
110 node.validation_signals->RegisterValidationInterface(&bvsc);
111 const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};
112 const bool duplicate{!new_block && processed};
113 assert(!duplicate);
114 node.validation_signals->UnregisterValidationInterface(&bvsc);
115 node.validation_signals->SyncWithValidationInterfaceQueue();
116 const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};
117 assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));
118
119 if (was_valid) return {block->vtx[0]->GetHash(), 0};
120 return {};
121}
122
123std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,
124 const BlockAssembler::Options& assembler_options)
125{
126 auto block = std::make_shared<CBlock>(
127 BlockAssembler{Assert(node.chainman)->ActiveChainstate(), Assert(node.mempool.get()), assembler_options}
128 .CreateNewBlock()
129 ->block);
130
131 LOCK(cs_main);
132 block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
133 block->hashMerkleRoot = BlockMerkleRoot(*block);
134
135 return block;
136}
137std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey)
138{
139 BlockAssembler::Options assembler_options;
140 assembler_options.coinbase_output_script = coinbase_scriptPubKey;
141 ApplyArgsManOptions(*node.args, assembler_options);
142 return PrepareBlock(node, assembler_options);
143}
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:106
uint32_t nBits
Definition: block.h:29
uint32_t nTime
Definition: block.h:28
Definition: block.h:69
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
const CBlock & GenesisBlock() const
Definition: chainparams.h:86
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:81
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:413
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65).
Definition: transaction.h:87
Implement this to subscribe to events generated in validation and mempool.
Generate a new block, without valid proof-of-work.
Definition: miner.h:151
256-bit opaque blob.
Definition: uint256.h:196
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
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:299
Definition: messages.h:20
util::Result< void > ApplyArgsManOptions(const ArgsManager &args, BlockManager::Options &opts)
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:424
@ OP_0
Definition: script.h:76
void BlockChecked(const std::shared_ptr< const CBlock > &block, const BlockValidationState &state) override
Notifies listeners of a block validation result.
Definition: mining.cpp:87
BlockValidationStateCatcher(const uint256 &hash)
Definition: mining.cpp:82
std::optional< BlockValidationState > m_state
Definition: mining.cpp:80
const uint256 m_hash
Definition: mining.cpp:79
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
NodeContext struct containing references to chain state and connection state.
Definition: context.h:56
#define LOCK(cs)
Definition: sync.h:259
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:290
COutPoint generatetoaddress(const NodeContext &node, const std::string &address)
RPC-like helper function, returns the generated coin.
Definition: mining.cpp:26
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:104
std::shared_ptr< CBlock > PrepareBlock(const NodeContext &node, const BlockAssembler::Options &assembler_options)
Definition: mining.cpp:123
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition: mining.cpp:36
COutPoint MineBlock(const NodeContext &node, const node::BlockAssembler::Options &assembler_options)
Returns the generated coin.
Definition: mining.cpp:70
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:19