Bitcoin Core  21.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 <clientversion.h>
11 #include <coins.h>
12 #include <consensus/consensus.h>
13 #include <core_io.h>
14 #include <key_io.h>
15 #include <policy/rbf.h>
16 #include <primitives/transaction.h>
17 #include <script/script.h>
18 #include <script/sign.h>
19 #include <script/signingprovider.h>
20 #include <univalue.h>
21 #include <util/moneystr.h>
22 #include <util/rbf.h>
23 #include <util/strencodings.h>
24 #include <util/string.h>
25 #include <util/system.h>
26 #include <util/translation.h>
27 
28 #include <atomic>
29 #include <functional>
30 #include <memory>
31 #include <stdio.h>
32 #include <thread>
33 
34 #include <boost/algorithm/string.hpp>
35 
36 static const int CONTINUE_EXECUTION=-1;
37 
38 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
39 
40 static void SetupBitcoinUtilArgs(ArgsManager &argsman)
41 {
42  SetupHelpOptions(argsman);
43 
44  argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
45 
47 }
48 
49 // This function returns either one of EXIT_ codes when it's expected to stop the process or
50 // CONTINUE_EXECUTION when it's expected to continue further.
51 static int AppInitUtil(int argc, char* argv[])
52 {
54  std::string error;
55  if (!gArgs.ParseParameters(argc, argv, error)) {
56  tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error);
57  return EXIT_FAILURE;
58  }
59 
60  // Check for chain settings (Params() calls are only valid after this clause)
61  try {
63  } catch (const std::exception& e) {
64  tfm::format(std::cerr, "Error: %s\n", e.what());
65  return EXIT_FAILURE;
66  }
67 
68  if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
69  // First part of help message is specific to this utility
70  std::string strUsage = PACKAGE_NAME " bitcoin-util utility version " + FormatFullVersion() + "\n";
71  if (!gArgs.IsArgSet("-version")) {
72  strUsage += "\n"
73  "Usage: bitcoin-util [options] [commands] Do stuff\n";
74  strUsage += "\n" + gArgs.GetHelpMessage();
75  }
76 
77  tfm::format(std::cout, "%s", strUsage);
78 
79  if (argc < 2) {
80  tfm::format(std::cerr, "Error: too few parameters\n");
81  return EXIT_FAILURE;
82  }
83  return EXIT_SUCCESS;
84  }
85  return CONTINUE_EXECUTION;
86 }
87 
88 static void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic<bool>& found)
89 {
90  arith_uint256 target;
91  bool neg, over;
92  target.SetCompact(nBits, &neg, &over);
93  if (target == 0 || neg || over) return;
94  CBlockHeader header = header_orig; // working copy
95  header.nNonce = offset;
96 
97  uint32_t finish = std::numeric_limits<uint32_t>::max() - step;
98  finish = finish - (finish % step) + offset;
99 
100  while (!found && header.nNonce < finish) {
101  const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;
102  do {
103  if (UintToArith256(header.GetHash()) <= target) {
104  if (!found.exchange(true)) {
105  header_orig.nNonce = header.nNonce;
106  }
107  return;
108  }
109  header.nNonce += step;
110  } while(header.nNonce != next);
111  }
112 }
113 
114 static int Grind(int argc, char* argv[], std::string& strPrint)
115 {
116  if (argc != 1) {
117  strPrint = "Must specify block header to grind";
118  return 1;
119  }
120 
121  CBlockHeader header;
122  if (!DecodeHexBlockHeader(header, argv[0])) {
123  strPrint = "Could not decode block header";
124  return 1;
125  }
126 
127  uint32_t nBits = header.nBits;
128  std::atomic<bool> found{false};
129 
130  std::vector<std::thread> threads;
131  int n_tasks = std::max(1u, std::thread::hardware_concurrency());
132  for (int i = 0; i < n_tasks; ++i) {
133  threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );
134  }
135  for (auto& t : threads) {
136  t.join();
137  }
138  if (!found) {
139  strPrint = "Could not satisfy difficulty target";
140  return 1;
141  }
142 
144  ss << header;
145  strPrint = HexStr(ss);
146  return 0;
147 }
148 
149 static int CommandLineUtil(int argc, char* argv[])
150 {
151  if (argc <= 1) return 1;
152 
153  std::string strPrint;
154  int nRet = 0;
155 
156  try {
157  while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {
158  --argc;
159  ++argv;
160  }
161 
162  char* command = argv[1];
163  if (strcmp(command, "grind") == 0) {
164  nRet = Grind(argc-2, argv+2, strPrint);
165  } else {
166  strPrint = strprintf("Unknown command %s", command);
167  nRet = 1;
168  }
169  }
170  catch (const std::exception& e) {
171  strPrint = std::string("error: ") + e.what();
172  nRet = EXIT_FAILURE;
173  }
174  catch (...) {
175  PrintExceptionContinue(nullptr, "CommandLineUtil()");
176  throw;
177  }
178 
179  if (strPrint != "") {
180  tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint);
181  }
182  return nRet;
183 }
184 
185 #ifdef WIN32
186 // Export main() and ensure working ASLR on Windows.
187 // Exporting a symbol will prevent the linker from stripping
188 // the .reloc section from the binary, which is a requirement
189 // for ASLR. This is a temporary workaround until a fixed
190 // version of binutils is used for releases.
191 __declspec(dllexport) int main(int argc, char* argv[])
192 #else
193 int main(int argc, char* argv[])
194 #endif
195 {
197 
198  try {
199  int ret = AppInitUtil(argc, argv);
200  if (ret != CONTINUE_EXECUTION)
201  return ret;
202  }
203  catch (const std::exception& e) {
204  PrintExceptionContinue(&e, "AppInitUtil()");
205  return EXIT_FAILURE;
206  } catch (...) {
207  PrintExceptionContinue(nullptr, "AppInitUtil()");
208  return EXIT_FAILURE;
209  }
210 
211  int ret = EXIT_FAILURE;
212  try {
213  ret = CommandLineUtil(argc, argv);
214  }
215  catch (const std::exception& e) {
216  PrintExceptionContinue(&e, "CommandLineUtil()");
217  } catch (...) {
218  PrintExceptionContinue(nullptr, "CommandLineUtil()");
219  }
220  return ret;
221 }
CONTINUE_EXECUTION
static const int CONTINUE_EXECUTION
Definition: bitcoin-util.cpp:36
arith_uint256.h
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
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
key_io.h
SetupHelpOptions
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:657
moneystr.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:88
transaction.h
ArgsManager::GetHelpMessage
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:583
string.h
SetupEnvironment
void SetupEnvironment()
Definition: system.cpp:1287
main
int main(int argc, char *argv[])
Definition: bitcoin-util.cpp:193
arith_uint256
256-bit unsigned big integer.
Definition: arith_uint256.h:250
ArgsManager::ALLOW_ANY
@ ALLOW_ANY
Definition: system.h:174
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:982
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:407
clientversion.h
bitcoin-config.h
core_io.h
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
rbf.h
signingprovider.h
CBlockHeader::nNonce
uint32_t nNonce
Definition: block.h:29
HelpRequested
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:652
strencodings.h
AppInitUtil
static int AppInitUtil(int argc, char *argv[])
Definition: bitcoin-util.cpp:51
PACKAGE_NAME
#define PACKAGE_NAME
Definition: bitcoin-config.h:365
ArgsManager::AddArg
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:555
univalue.h
consensus.h
IsSwitchChar
bool IsSwitchChar(char c)
Definition: system.h:132
DecodeHexBlockHeader
bool DecodeHexBlockHeader(CBlockHeader &, const std::string &hex_header)
Definition: core_read.cpp:208
sign.h
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:557
ArgsManager::ParseParameters
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:286
coins.h
CommandLineUtil
static int CommandLineUtil(int argc, char *argv[])
Definition: bitcoin-util.cpp:149
system.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
G_TRANSLATION_FUN
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoin-util.cpp:38
ArgsManager
Definition: system.h:166
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
gArgs
ArgsManager gArgs
Definition: system.cpp:79
if
if(expired !=0)
Definition: validation.cpp:350
SetupBitcoinUtilArgs
static void SetupBitcoinUtilArgs(ArgsManager &argsman)
Definition: bitcoin-util.cpp:40
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:166
script.h
Grind
static int Grind(int argc, char *argv[], std::string &strPrint)
Definition: bitcoin-util.cpp:114
FormatFullVersion
std::string FormatFullVersion()
Definition: clientversion.cpp:50
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:50
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
PrintExceptionContinue
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:694
rbf.h
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12