Bitcoin Core 31.99.0
P2P Digital Currency
bitcoin-util.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-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 <bitcoin-build-config.h> // IWYU pragma: keep
6
7#include <arith_uint256.h>
8#include <chain.h>
9#include <chainparams.h>
10#include <chainparamsbase.h>
11#include <clientversion.h>
12#include <common/args.h>
13#include <common/license_info.h>
14#include <common/system.h>
15#include <compat/compat.h>
16#include <core_io.h>
17#include <streams.h>
18#include <univalue.h>
19#include <util/exception.h>
20#include <util/strencodings.h>
21#include <util/translation.h>
22
23#include <atomic>
24#include <cstdio>
25#include <functional>
26#include <memory>
27#include <thread>
28
29static const int CONTINUE_EXECUTION=-1;
30
32
33static void SetupBitcoinUtilArgs(ArgsManager &argsman)
34{
35 SetupHelpOptions(argsman);
36
37 argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
38
39 argsman.AddCommand("grind", "Perform proof of work on hex header string");
40 argsman.AddCommand("getchainparams", "Get hardcoded parameters for the selected chain");
41
43}
44
45// This function returns either one of EXIT_ codes when it's expected to stop the process or
46// CONTINUE_EXECUTION when it's expected to continue further.
47static int AppInitUtil(ArgsManager& args, int argc, char* argv[])
48{
50 std::string error;
51 if (!args.ParseParameters(argc, argv, error)) {
52 tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
53 return EXIT_FAILURE;
54 }
55
56 if (HelpRequested(args) || args.GetBoolArg("-version", false)) {
57 // First part of help message is specific to this utility
58 std::string strUsage = CLIENT_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
59
60 if (args.GetBoolArg("-version", false)) {
61 strUsage += FormatParagraph(LicenseInfo());
62 } else {
63 strUsage += "\n"
64 "The bitcoin-util tool provides bitcoin related functionality that does not rely on the ability to access a running node. Available [commands] are listed below.\n"
65 "\n"
66 "Usage: bitcoin-util [options] [command]\n"
67 "or: bitcoin-util [options] grind <hex-block-header>\n";
68 strUsage += "\n" + args.GetHelpMessage();
69 }
70
71 tfm::format(std::cout, "%s", strUsage);
72
73 if (argc < 2) {
74 tfm::format(std::cerr, "Error: too few parameters\n");
75 return EXIT_FAILURE;
76 }
77 return EXIT_SUCCESS;
78 }
79
80 // Check for chain settings (Params() calls are only valid after this clause)
81 try {
83 } catch (const std::exception& e) {
84 tfm::format(std::cerr, "Error: %s\n", e.what());
85 return EXIT_FAILURE;
86 }
87
88 return CONTINUE_EXECUTION;
89}
90
91static void grind_task(uint32_t nBits, CBlockHeader header, uint32_t offset, uint32_t step, std::atomic<bool>& found, uint32_t& proposed_nonce)
92{
93 arith_uint256 target;
94 bool neg, over;
95 target.SetCompact(nBits, &neg, &over);
96 if (target == 0 || neg || over) return;
97 header.nNonce = offset;
98
99 uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
100 finish = finish - (finish % step) + offset;
101
102 while (!found && header.nNonce < finish) {
103 const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
104 do {
105 if (UintToArith256(header.GetHash()) <= target) {
106 if (!found.exchange(true)) {
107 proposed_nonce = header.nNonce;
108 }
109 return;
110 }
111 header.nNonce += step;
112 } while(header.nNonce != next);
113 }
114}
115
116static int Grind(const std::vector<std::string>& args, std::string& strPrint)
117{
118 if (args.size() != 1) {
119 strPrint = "Must specify block header to grind";
120 return EXIT_FAILURE;
121 }
122
123 CBlockHeader header;
124 if (!DecodeHexBlockHeader(header, args[0])) {
125 strPrint = "Could not decode block header";
126 return EXIT_FAILURE;
127 }
128
129 uint32_t nBits = header.nBits;
130 std::atomic<bool> found{false};
131 uint32_t proposed_nonce{};
132
133 std::vector<std::thread> threads;
134 int n_tasks = std::max(1u, std::thread::hardware_concurrency());
135 threads.reserve(n_tasks);
136 for (int i = 0; i < n_tasks; ++i) {
137 threads.emplace_back(grind_task, nBits, header, i, n_tasks, std::ref(found), std::ref(proposed_nonce));
138 }
139 for (auto& t : threads) {
140 t.join();
141 }
142 if (found) {
143 header.nNonce = proposed_nonce;
144 } else {
145 strPrint = "Could not satisfy difficulty target";
146 return EXIT_FAILURE;
147 }
148
149 DataStream ss{};
150 ss << header;
151 strPrint = HexStr(ss);
152 return EXIT_SUCCESS;
153}
154
155static int GetChainParams(const std::vector<std::string>& args, std::string& strPrint)
156{
157 if (!args.empty()) {
158 strPrint = "getchainparams does not take arguments";
159 return EXIT_FAILURE;
160 }
161
162 const auto& params = Params();
163 const auto& consensus = params.GetConsensus();
164
165 UniValue result{UniValue::VOBJ};
166 result.pushKV("chain", params.GetChainTypeString());
167 result.pushKV("test_chain", params.IsTestChain());
168 result.pushKV("genesis", HexStr(consensus.hashGenesisBlock));
169 result.pushKV("subsidy_halving_interval", consensus.nSubsidyHalvingInterval);
170
171 if (consensus.signet_blocks) {
172 UniValue signet{UniValue::VOBJ};
173 signet.pushKV("challenge", HexStr(consensus.signet_challenge));
174 result.pushKV("signet", signet);
175 }
176
177 {
179 pow.pushKV("limit", consensus.powLimit.ToString());
180 if (!consensus.fPowNoRetargeting) {
181 pow.pushKV("target_spacing", TicksSeconds(consensus.PowTargetSpacing()));
182 pow.pushKV("difficulty_retarget_interval", consensus.DifficultyAdjustmentInterval());
183 std::string mindiff_blocks = (consensus.fPowAllowMinDifficultyBlocks ?
184 (consensus.enforce_BIP94 ? "bip94" : "yes") : "no");
185 pow.pushKV("mindiff_blocks", mindiff_blocks);
186 }
187 result.pushKV("pow", pow);
188 }
189
190 {
192 net.pushKV("default_port", params.GetDefaultPort());
193 net.pushKV("magic", HexStr(params.MessageStart()));
195 for (const auto& seed : params.DNSSeeds()) {
196 dns.push_back(seed);
197 }
198 net.pushKV("dns_seeds", dns);
199 result.pushKV("net", net);
200 }
201
202 {
204 addr.pushKV("bech32_hrp", params.Bech32HRP());
205 result.pushKV("addresses", addr);
206 }
207
208 strPrint = result.write(/*prettyIndent=*/2);
209 return EXIT_SUCCESS;
210}
211
213{
216
217 try {
218 int ret = AppInitUtil(args, argc, argv);
220 return ret;
221 }
222 } catch (const std::exception& e) {
223 PrintExceptionContinue(&e, "AppInitUtil()");
224 return EXIT_FAILURE;
225 } catch (...) {
226 PrintExceptionContinue(nullptr, "AppInitUtil()");
227 return EXIT_FAILURE;
228 }
229
230 const auto cmd = args.GetCommand();
231 if (!cmd) {
232 tfm::format(std::cerr, "Error: must specify a command\n");
233 return EXIT_FAILURE;
234 }
235
236 int ret = EXIT_FAILURE;
237 std::string strPrint;
238 try {
239 if (cmd->command == "grind") {
240 ret = Grind(cmd->args, strPrint);
241 } else if (cmd->command == "getchainparams") {
242 ret = GetChainParams(cmd->args, strPrint);
243 } else {
244 assert(false); // unknown command should be caught earlier
245 }
246 } catch (const std::exception& e) {
247 strPrint = std::string("error: ") + e.what();
248 } catch (...) {
249 strPrint = "unknown error";
250 }
251
252 if (strPrint != "") {
253 tfm::format(ret == 0 ? std::cout : std::cerr, "%s\n", strPrint);
254 }
255
256 return ret;
257}
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:812
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:817
ArgsManager gArgs
Definition: args.cpp:38
arith_uint256 UintToArith256(const uint256 &a)
static void grind_task(uint32_t nBits, CBlockHeader header, uint32_t offset, uint32_t step, std::atomic< bool > &found, uint32_t &proposed_nonce)
static const int CONTINUE_EXECUTION
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
if(ret !=CONTINUE_EXECUTION)
static int GetChainParams(const std::vector< std::string > &args, std::string &strPrint)
const auto cmd
int ret
SetupEnvironment()
Definition: system.cpp:64
static int Grind(const std::vector< std::string > &args, std::string &strPrint)
const TranslateFn G_TRANSLATION_FUN
Translate string to current locale using Qt.
static int AppInitUtil(ArgsManager &args, int argc, char *argv[])
MAIN_FUNCTION
std::string strPrint
return EXIT_SUCCESS
ArgsManager & args
Definition: bitcoind.cpp:280
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain type.
const CChainParams & Params()
Return the currently selected parameters.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
bool ParseParameters(int argc, const char *const argv[], std::string &error) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: args.cpp:175
ChainType GetChainType() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:910
@ ALLOW_ANY
disable validation
Definition: args.h:114
void AddCommand(const std::string &cmd, const std::string &help, std::set< std::string > options={}) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add command.
Definition: args.cpp:633
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Add argument.
Definition: args.cpp:657
std::optional< const Command > GetCommand() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:368
bool GetBoolArg(const std::string &strArg, bool fDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return boolean argument or default value.
Definition: args.cpp:571
std::string GetHelpMessage() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get the help string.
Definition: args.cpp:720
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:27
uint32_t nNonce
Definition: block.h:35
uint32_t nBits
Definition: block.h:34
uint256 GetHash() const
Definition: block.cpp:14
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:165
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
256-bit unsigned big integer.
arith_uint256 & SetCompact(uint32_t nCompact, bool *pfNegative=nullptr, bool *pfOverflow=nullptr)
The "compact" format is a representation of a whole number N using an unsigned 32bit number similar t...
std::string FormatFullVersion()
bool DecodeHexBlockHeader(CBlockHeader &header, const std::string &hex_header)
Definition: core_io.cpp:235
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:36
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
std::string LicenseInfo()
Returns licensing information (for -version)
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
Definition: translation.h:16
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
constexpr int64_t TicksSeconds(Duration d)
Definition: time.h:88
assert(!tx.IsCoinBase())