Bitcoin Core  24.1.0
P2P Digital Currency
bitcoin-util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2021 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/system.h>
18 #include <util/translation.h>
19 #include <version.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_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
86 {
87  arith_uint256 target;
88  bool neg, over;
89  target.SetCompact(nBits, &neg, &over);
90  if (target == 0 || neg || over) return;
91  CBlockHeader header = header_orig; // working copy
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  header_orig.nNonce = 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 
127  std::vector<std::thread> threads;
128  int n_tasks = std::max(1u, std::thread::hardware_concurrency());
129  for (int i = 0; i < n_tasks; ++i) {
130  threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
131  }
132  for (auto& t : threads) {
133  t.join();
134  }
135  if (!found) {
136  strPrint = "Could not satisfy difficulty target";
137  return EXIT_FAILURE;
138  }
139 
141  ss << header;
142  strPrint = HexStr(ss);
143  return EXIT_SUCCESS;
144 }
145 
147 {
150 
151  try {
152  int ret = AppInitUtil(args, argc, argv);
154  return ret;
155  }
156  } catch (const std::exception& e) {
157  PrintExceptionContinue(&e, "AppInitUtil()");
158  return EXIT_FAILURE;
159  } catch (...) {
160  PrintExceptionContinue(nullptr, "AppInitUtil()");
161  return EXIT_FAILURE;
162  }
163 
164  const auto cmd = args.GetCommand();
165  if (!cmd) {
166  tfm::format(std::cerr, "Error: must specify a command\n");
167  return EXIT_FAILURE;
168  }
169 
170  int ret = EXIT_FAILURE;
171  std::string strPrint;
172  try {
173  if (cmd->command == "grind") {
174  ret = Grind(cmd->args, strPrint);
175  } else {
176  assert(false); // unknown command should be caught earlier
177  }
178  } catch (const std::exception& e) {
179  strPrint = std::string("error: ") + e.what();
180  } catch (...) {
181  strPrint = "unknown error";
182  }
183 
184  if (strPrint != "") {
185  tfm::format(ret == 0 ? std::cout : std::cerr, "%s\n", strPrint);
186  }
187 
188  return ret;
189 }
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: system.cpp:500
ArgsManager gArgs
Definition: system.cpp:86
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
return EXIT_SUCCESS
assert(!tx.IsCoinBase())
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:808
std::string strPrint
const auto cmd
#define PACKAGE_NAME
static void grind_task(uint32_t nBits, CBlockHeader &header_orig, uint32_t offset, uint32_t step, std::atomic< bool > &found)
SetupEnvironment()
Definition: system.cpp:1374
int ret
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:300
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:185
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:205
static int Grind(const std::vector< std::string > &args, std::string &strPrint)
ArgsManager args
disable validation
Definition: system.h:180
arith_uint256 UintToArith256(const uint256 &a)
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:739
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:699
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:813
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
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:1062
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:711
if(ret !=CONTINUE_EXECUTION)
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: system.cpp:850
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: system.cpp:471
256-bit unsigned big integer.
std::string FormatFullVersion()
uint256 GetHash() const
Definition: block.cpp:11
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
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...
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:1058
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
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
uint32_t nBits
Definition: block.h:29
MAIN_FUNCTION