Bitcoin Core  22.99.0
P2P Digital Currency
bitcoin-util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2020 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 <core_io.h>
15 #include <streams.h>
16 #include <util/system.h>
17 #include <util/translation.h>
18 
19 #include <atomic>
20 #include <cstdio>
21 #include <functional>
22 #include <memory>
23 #include <thread>
24 
25 #include <boost/algorithm/string.hpp>
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  if (!args.IsArgSet("-version")) {
57  strUsage += "\n"
58  "Usage: bitcoin-util [options] [commands] Do stuff\n";
59  strUsage += "\n" + args.GetHelpMessage();
60  }
61 
62  tfm::format(std::cout, "%s", strUsage);
63 
64  if (argc < 2) {
65  tfm::format(std::cerr, "Error: too few parameters\n");
66  return EXIT_FAILURE;
67  }
68  return EXIT_SUCCESS;
69  }
70 
71  // Check for chain settings (Params() calls are only valid after this clause)
72  try {
73  SelectParams(args.GetChainName());
74  } catch (const std::exception& e) {
75  tfm::format(std::cerr, "Error: %s\n", e.what());
76  return EXIT_FAILURE;
77  }
78 
79  return CONTINUE_EXECUTION;
80 }
81 
82 static void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
83 {
84  arith_uint256 target;
85  bool neg, over;
86  target.SetCompact(nBits, &neg, &over);
87  if (target == 0 || neg || over) return;
88  CBlockHeader header = header_orig; // working copy
89  header.nNonce = offset;
90 
91  uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
92  finish = finish - (finish % step) + offset;
93 
94  while (!found && header.nNonce < finish) {
95  const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
96  do {
97  if (UintToArith256(header.GetHash()) <= target) {
98  if (!found.exchange(true)) {
99  header_orig.nNonce = header.nNonce;
100  }
101  return;
102  }
103  header.nNonce += step;
104  } while(header.nNonce != next);
105  }
106 }
107 
108 static int Grind(const std::vector<std::string>& args, std::string& strPrint)
109 {
110  if (args.size() != 1) {
111  strPrint = "Must specify block header to grind";
112  return EXIT_FAILURE;
113  }
114 
115  CBlockHeader header;
116  if (!DecodeHexBlockHeader(header, args[0])) {
117  strPrint = "Could not decode block header";
118  return EXIT_FAILURE;
119  }
120 
121  uint32_t nBits = header.nBits;
122  std::atomic<bool> found{false};
123 
124  std::vector<std::thread> threads;
125  int n_tasks = std::max(1u, std::thread::hardware_concurrency());
126  for (int i = 0; i < n_tasks; ++i) {
127  threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
128  }
129  for (auto& t : threads) {
130  t.join();
131  }
132  if (!found) {
133  strPrint = "Could not satisfy difficulty target";
134  return EXIT_FAILURE;
135  }
136 
138  ss << header;
139  strPrint = HexStr(ss);
140  return EXIT_SUCCESS;
141 }
142 
143 #ifdef WIN32
144 // Export main() and ensure working ASLR on Windows.
145 // Exporting a symbol will prevent the linker from stripping
146 // the .reloc section from the binary, which is a requirement
147 // for ASLR. This is a temporary workaround until a fixed
148 // version of binutils is used for releases.
149 __declspec(dllexport) int main(int argc, char* argv[])
150 #else
151 int main(int argc, char* argv[])
152 #endif
153 {
154  ArgsManager& args = gArgs;
156 
157  try {
158  int ret = AppInitUtil(args, argc, argv);
159  if (ret != CONTINUE_EXECUTION) {
160  return ret;
161  }
162  } catch (const std::exception& e) {
163  PrintExceptionContinue(&e, "AppInitUtil()");
164  return EXIT_FAILURE;
165  } catch (...) {
166  PrintExceptionContinue(nullptr, "AppInitUtil()");
167  return EXIT_FAILURE;
168  }
169 
170  const auto cmd = args.GetCommand();
171  if (!cmd) {
172  tfm::format(std::cerr, "Error: must specify a command\n");
173  return EXIT_FAILURE;
174  }
175 
176  int ret = EXIT_FAILURE;
177  std::string strPrint;
178  try {
179  if (cmd->command == "grind") {
180  ret = Grind(cmd->args, strPrint);
181  } else {
182  assert(false); // unknown command should be caught earlier
183  }
184  } catch (const std::exception& e) {
185  strPrint = std::string("error: ") + e.what();
186  } catch (...) {
187  strPrint = "unknown error";
188  }
189 
190  if (strPrint != "") {
191  tfm::format(ret == 0 ? std::cout : std::cerr, "%s\n", strPrint);
192  }
193 
194  return ret;
195 }
CONTINUE_EXECUTION
static const int CONTINUE_EXECUTION
Definition: bitcoin-util.cpp:27
arith_uint256.h
assert
assert(!tx.IsCoinBase())
tinyformat::format
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
if
if(na.IsAddrV1Compatible())
Definition: deserialize.cpp:213
CBlockHeader::nBits
uint32_t nBits
Definition: block.h:28
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
streams.h
grind_task
static void grind_task(uint32_t nBits, CBlockHeader &header_orig, uint32_t offset, uint32_t step, std::atomic< bool > &found)
Definition: bitcoin-util.cpp:82
ArgsManager::GetHelpMessage
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:668
main
int main(int argc, char *argv[])
Definition: bitcoin-util.cpp:151
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:250
chainparamsbase.h
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
Definition: system.h:166
SetupChainParamsBaseOptions
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
Definition: chainparamsbase.cpp:18
ArgsManager::GetChainName
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:988
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:492
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1295
clientversion.h
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:737
bitcoin-config.h
chainparams.h
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:742
core_io.h
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:29
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:362
ArgsManager::AddArg
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:640
AppInitUtil
static int AppInitUtil(ArgsManager &args, int argc, char *argv[])
Definition: bitcoin-util.cpp:44
DecodeHexBlockHeader
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:208
OptionsCategory::OPTIONS
@ OPTIONS
SelectParams
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
Definition: chainparams.cpp:580
ArgsManager::ParseParameters
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:304
chain.h
gArgs
ArgsManager gArgs
Definition: system.cpp:84
Grind
static int Grind(const std::vector< std::string > &args, std::string &strPrint)
Definition: bitcoin-util.cpp:108
system.h
G_TRANSLATION_FUN
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-util.cpp:29
ArgsManager
Definition: system.h:158
translation.h
UintToArith256
arith_uint256 UintToArith256(const uint256 &a)
Definition: arith_uint256.cpp:253
arith_uint256::SetCompact
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...
Definition: arith_uint256.cpp:203
ArgsManager::GetCommand
std::optional< const Command > GetCommand() const
Get the command and command args (returns std::nullopt if no command provided)
Definition: system.cpp:463
SetupBitcoinUtilArgs
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
Definition: bitcoin-util.cpp:31
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:138
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:779
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:50
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
ArgsManager::AddCommand
void AddCommand(const std::string &cmd, const std::string &help)
Add subcommand.
Definition: system.cpp:628
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12