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