Bitcoin Core  26.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>
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  const auto coinbase_script = GetScriptForDestination(dest);
28 
29  return MineBlock(node, coinbase_script);
30 }
31 
32 std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)
33 {
34  std::vector<std::shared_ptr<CBlock>> ret{total_height};
35  auto time{params.GenesisBlock().nTime};
36  for (size_t height{0}; height < total_height; ++height) {
37  CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};
38 
39  CMutableTransaction coinbase_tx;
40  coinbase_tx.vin.resize(1);
41  coinbase_tx.vin[0].prevout.SetNull();
42  coinbase_tx.vout.resize(1);
43  coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE;
44  coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus());
45  coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0;
46  block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};
47 
48  block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;
49  block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();
50  block.hashMerkleRoot = BlockMerkleRoot(block);
51  block.nTime = ++time;
52  block.nBits = params.GenesisBlock().nBits;
53  block.nNonce = 0;
54 
55  while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {
56  ++block.nNonce;
57  assert(block.nNonce);
58  }
59  }
60  return ret;
61 }
62 
63 COutPoint MineBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey)
64 {
65  auto block = PrepareBlock(node, coinbase_scriptPubKey);
66  auto valid = MineBlock(node, block);
67  assert(!valid.IsNull());
68  return valid;
69 }
70 
72  const uint256 m_hash;
73  std::optional<BlockValidationState> m_state;
74 
76  : m_hash{hash},
77  m_state{} {}
78 
79 protected:
80  void BlockChecked(const CBlock& block, const BlockValidationState& state) override
81  {
82  if (block.GetHash() != m_hash) return;
83  m_state = state;
84  }
85 };
86 
87 COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)
88 {
89  while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
90  ++block->nNonce;
91  assert(block->nNonce);
92  }
93 
94  auto& chainman{*Assert(node.chainman)};
95  const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());
96  bool new_block;
97  BlockValidationStateCatcher bvsc{block->GetHash()};
99  const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};
100  const bool duplicate{!new_block && processed};
101  assert(!duplicate);
104  const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};
105  assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));
106 
107  if (was_valid) return {block->vtx[0]->GetHash(), 0};
108  return {};
109 }
110 
111 std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey,
112  const BlockAssembler::Options& assembler_options)
113 {
114  auto block = std::make_shared<CBlock>(
115  BlockAssembler{Assert(node.chainman)->ActiveChainstate(), Assert(node.mempool.get()), assembler_options}
116  .CreateNewBlock(coinbase_scriptPubKey)
117  ->block);
118 
119  LOCK(cs_main);
120  block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;
121  block->hashMerkleRoot = BlockMerkleRoot(*block);
122 
123  return block;
124 }
125 std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node, const CScript& coinbase_scriptPubKey)
126 {
127  BlockAssembler::Options assembler_options;
128  ApplyArgsManOptions(*node.args, assembler_options);
129  return PrepareBlock(node, coinbase_scriptPubKey, assembler_options);
130 }
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:77
uint32_t nBits
Definition: block.h:29
uint32_t nTime
Definition: block.h:28
uint256 GetHash() const
Definition: block.cpp:11
Definition: block.h:69
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:81
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:93
const CBlock & GenesisBlock() const
Definition: chainparams.h:97
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:414
Implement this to subscribe to events generated in validation and mempool.
Generate a new block, without valid proof-of-work.
Definition: miner.h:135
256-bit opaque blob.
Definition: uint256.h:106
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:292
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
Definition: init.h:25
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:125
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
@ OP_0
Definition: script.h:75
BlockValidationStateCatcher(const uint256 &hash)
Definition: mining.cpp:75
std::optional< BlockValidationState > m_state
Definition: mining.cpp:73
void BlockChecked(const CBlock &block, const BlockValidationState &state) override
Notifies listeners of a block validation result.
Definition: mining.cpp:80
const uint256 m_hash
Definition: mining.cpp:72
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:48
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
COutPoint generatetoaddress(const NodeContext &node, const std::string &address)
RPC-like helper function, returns the generated coin.
Definition: mining.cpp:23
COutPoint MineBlock(const NodeContext &node, const CScript &coinbase_scriptPubKey)
Returns the generated coin.
Definition: mining.cpp:63
std::vector< std::shared_ptr< CBlock > > CreateBlockChain(size_t total_height, const CChainParams &params)
Create a blockchain, starting from genesis.
Definition: mining.cpp:32
std::shared_ptr< CBlock > PrepareBlock(const NodeContext &node, const CScript &coinbase_scriptPubKey, const BlockAssembler::Options &assembler_options)
Definition: mining.cpp:111
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION
What block version to use for new blocks (pre versionbits)
Definition: versionbits.h:14