Bitcoin Core  28.1.0
P2P Digital Currency
bitcoin-util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-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 <config/bitcoin-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/system.h>
14 #include <compat/compat.h>
15 #include <core_io.h>
16 #include <streams.h>
17 #include <util/exception.h>
18 #include <util/strencodings.h>
19 #include <util/translation.h>
20 
21 #include <atomic>
22 #include <cstdio>
23 #include <functional>
24 #include <memory>
25 #include <thread>
26 
27 static const int CONTINUE_EXECUTION=-1;
28 
29 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
30 
31 static void SetupBitcoinUtilArgs(ArgsManager &argsman)
32 {
33  SetupHelpOptions(argsman);
34 
35  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
36 
37  argsman.AddCommand("grind", "Perform proof of work on hex header string");
38 
40 }
41 
42 // This function returns either one of EXIT_ codes when it's expected to stop the process or
43 // CONTINUE_EXECUTION when it's expected to continue further.
44 static int AppInitUtil(ArgsManager& args, int argc, char* argv[])
45 {
47  std::string error;
48  if (!args.ParseParameters(argc, argv, error)) {
49  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
50  return EXIT_FAILURE;
51  }
52 
53  if (HelpRequested(args) || args.IsArgSet("-version")) {
54  // First part of help message is specific to this utility
55  std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
56 
57  if (args.IsArgSet("-version")) {
58  strUsage += FormatParagraph(LicenseInfo());
59  } else {
60  strUsage += "\n"
61  "Usage: bitcoin-util [options] [commands] Do stuff\n";
62  strUsage += "\n" + args.GetHelpMessage();
63  }
64 
65  tfm::format(std::cout, "%s", strUsage);
66 
67  if (argc < 2) {
68  tfm::format(std::cerr, "Error: too few parameters\n");
69  return EXIT_FAILURE;
70  }
71  return EXIT_SUCCESS;
72  }
73 
74  // Check for chain settings (Params() calls are only valid after this clause)
75  try {
77  } catch (const std::exception& e) {
78  tfm::format(std::cerr, "Error: %s\n", e.what());
79  return EXIT_FAILURE;
80  }
81 
82  return CONTINUE_EXECUTION;
83 }
84 
85 static void grind_task(uint32_t nBits, CBlockHeader header, uint32_t offset, uint32_t step, std::atomic<bool>& found, uint32_t& proposed_nonce)
86 {
87  arith_uint256 target;
88  bool neg, over;
89  target.SetCompact(nBits, &neg, &over);
90  if (target == 0 || neg || over) return;
91  header.nNonce = offset;
92 
93  uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
94  finish = finish - (finish % step) + offset;
95 
96  while (!found && header.nNonce < finish) {
97  const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
98  do {
99  if (UintToArith256(header.GetHash()) <= target) {
100  if (!found.exchange(true)) {
101  proposed_nonce = header.nNonce;
102  }
103  return;
104  }
105  header.nNonce += step;
106  } while(header.nNonce != next);
107  }
108 }
109 
110 static int Grind(const std::vector<std::string>& args, std::string& strPrint)
111 {
112  if (args.size() != 1) {
113  strPrint = "Must specify block header to grind";
114  return EXIT_FAILURE;
115  }
116 
117  CBlockHeader header;
118  if (!DecodeHexBlockHeader(header, args[0])) {
119  strPrint = "Could not decode block header";
120  return EXIT_FAILURE;
121  }
122 
123  uint32_t nBits = header.nBits;
124  std::atomic<bool> found{false};
125  uint32_t proposed_nonce{};
126 
127  std::vector<std::thread> threads;
128  int n_tasks = std::max(1u, std::thread::hardware_concurrency());
129  threads.reserve(n_tasks);
130  for (int i = 0; i < n_tasks; ++i) {
131  threads.emplace_back(grind_task, nBits, header, i, n_tasks, std::ref(found), std::ref(proposed_nonce));
132  }
133  for (auto& t : threads) {
134  t.join();
135  }
136  if (found) {
137  header.nNonce = proposed_nonce;
138  } else {
139  strPrint = "Could not satisfy difficulty target";
140  return EXIT_FAILURE;
141  }
142 
143  DataStream ss{};
144  ss << header;
145  strPrint = HexStr(ss);
146  return EXIT_SUCCESS;
147 }
148 
150 {
153 
154  try {
155  int ret = AppInitUtil(args, argc, argv);
157  return ret;
158  }
159  } catch (const std::exception& e) {
160  PrintExceptionContinue(&e, "AppInitUtil()");
161  return EXIT_FAILURE;
162  } catch (...) {
163  PrintExceptionContinue(nullptr, "AppInitUtil()");
164  return EXIT_FAILURE;
165  }
166 
167  const auto cmd = args.GetCommand();
168  if (!cmd) {
169  tfm::format(std::cerr, "Error: must specify a command\n");
170  return EXIT_FAILURE;
171  }
172 
173  int ret = EXIT_FAILURE;
174  std::string strPrint;
175  try {
176  if (cmd->command == "grind") {
177  ret = Grind(cmd->args, strPrint);
178  } else {
179  assert(false); // unknown command should be caught earlier
180  }
181  } catch (const std::exception& e) {
182  strPrint = std::string("error: ") + e.what();
183  } catch (...) {
184  strPrint = "unknown error";
185  }
186 
187  if (strPrint != "") {
188  tfm::format(ret == 0 ? std::cout : std::cerr, "%s\n", strPrint);
189  }
190 
191  return ret;
192 }
uint32_t nNonce
Definition: block.h:30
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:370
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
return EXIT_SUCCESS
assert(!tx.IsCoinBase())
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
std::string strPrint
const auto cmd
#define PACKAGE_NAME
SetupEnvironment()
Definition: system.cpp:59
int ret
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:178
std::string LicenseInfo()
Returns licensing information (for -version)
static const int CONTINUE_EXECUTION
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:206
static int Grind(const std::vector< std::string > &args, std::string &strPrint)
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:36
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
Definition: args.cpp:749
disable validation
Definition: args.h:104
arith_uint256 UintToArith256(const uint256 &a)
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:591
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: args.cpp:551
ArgsManager & args
Definition: bitcoind.cpp:270
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1059
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: args.cpp:563
if(ret !=CONTINUE_EXECUTION)
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...
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: args.cpp:341
256-bit unsigned big integer.
std::string FormatFullVersion()
ArgsManager gArgs
Definition: args.cpp:41
uint256 GetHash() const
Definition: block.cpp:11
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: args.cpp:665
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:660
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
static int AppInitUtil(ArgsManager &args, int argc, char *argv[])
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...
static void grind_task(uint32_t nBits, CBlockHeader header, uint32_t offset, uint32_t step, std::atomic< bool > &found, uint32_t &proposed_nonce)
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:21
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain type.
uint32_t nBits
Definition: block.h:29
MAIN_FUNCTION