Bitcoin Core  27.99.0
P2P Digital Currency
util_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-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 <clientversion.h>
6 #include <common/signmessage.h> // For MessageSign(), MessageVerify(), MESSAGE_MAGIC
7 #include <hash.h> // For Hash()
8 #include <key.h> // For CKey
9 #include <script/parsing.h>
10 #include <sync.h>
11 #include <test/util/random.h>
12 #include <test/util/setup_common.h>
13 #include <uint256.h>
14 #include <util/bitdeque.h>
15 #include <util/fs.h>
16 #include <util/fs_helpers.h>
17 #include <util/moneystr.h>
18 #include <util/overflow.h>
19 #include <util/readwritefile.h>
20 #include <util/strencodings.h>
21 #include <util/string.h>
22 #include <util/time.h>
23 #include <util/vector.h>
24 
25 #include <array>
26 #include <cmath>
27 #include <fstream>
28 #include <limits>
29 #include <map>
30 #include <optional>
31 #include <stdint.h>
32 #include <string.h>
33 #include <thread>
34 #include <univalue.h>
35 #include <utility>
36 #include <vector>
37 
38 #include <sys/types.h>
39 
40 #ifndef WIN32
41 #include <signal.h>
42 #include <sys/wait.h>
43 #endif
44 
45 #include <boost/test/unit_test.hpp>
46 
47 using namespace std::literals;
48 using util::Join;
49 using util::RemovePrefix;
51 using util::ReplaceAll;
52 using util::Split;
53 using util::SplitString;
54 using util::TrimString;
56 
57 static const std::string STRING_WITH_EMBEDDED_NULL_CHAR{"1"s "\0" "1"s};
58 
59 /* defined in logging.cpp */
60 namespace BCLog {
61  std::string LogEscapeMessage(const std::string& str);
62 }
63 
64 BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
65 
66 namespace {
67 class NoCopyOrMove
68 {
69 public:
70  int i;
71  explicit NoCopyOrMove(int i) : i{i} { }
72 
73  NoCopyOrMove() = delete;
74  NoCopyOrMove(const NoCopyOrMove&) = delete;
75  NoCopyOrMove(NoCopyOrMove&&) = delete;
76  NoCopyOrMove& operator=(const NoCopyOrMove&) = delete;
77  NoCopyOrMove& operator=(NoCopyOrMove&&) = delete;
78 
79  operator bool() const { return i != 0; }
80 
81  int get_ip1() { return i + 1; }
82  bool test()
83  {
84  // Check that Assume can be used within a lambda and still call methods
85  [&]() { Assume(get_ip1()); }();
86  return Assume(get_ip1() != 5);
87  }
88 };
89 } // namespace
90 
92 {
93  // Check that Assert can forward
94  const std::unique_ptr<int> p_two = Assert(std::make_unique<int>(2));
95  // Check that Assert works on lvalues and rvalues
96  const int two = *Assert(p_two);
97  Assert(two == 2);
98  Assert(true);
99  // Check that Assume can be used as unary expression
100  const bool result{Assume(two == 2)};
101  Assert(result);
102 
103  // Check that Assert doesn't require copy/move
104  NoCopyOrMove x{9};
105  Assert(x).i += 3;
106  Assert(x).test();
107 
108  // Check nested Asserts
109  BOOST_CHECK_EQUAL(Assert((Assert(x).test() ? 3 : 0)), 3);
110 
111  // Check -Wdangling-gsl does not trigger when copying the int. (It would
112  // trigger on "const int&")
113  const int nine{*Assert(std::optional<int>{9})};
114  BOOST_CHECK_EQUAL(9, nine);
115 }
116 
117 BOOST_AUTO_TEST_CASE(util_criticalsection)
118 {
120 
121  do {
122  LOCK(cs);
123  break;
124 
125  BOOST_ERROR("break was swallowed!");
126  } while(0);
127 
128  do {
129  TRY_LOCK(cs, lockTest);
130  if (lockTest) {
131  BOOST_CHECK(true); // Needed to suppress "Test case [...] did not check any assertions"
132  break;
133  }
134 
135  BOOST_ERROR("break was swallowed!");
136  } while(0);
137 }
138 
139 static const unsigned char ParseHex_expected[65] = {
140  0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7,
141  0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde,
142  0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12,
143  0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d,
144  0x5f
145 };
147 {
148  std::vector<unsigned char> result;
149  std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected));
150  // Basic test vector
151  result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
152  BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
153  result = TryParseHex<uint8_t>("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f").value();
154  BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
155 
156  // Spaces between bytes must be supported
157  result = ParseHex("12 34 56 78");
158  BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
159  result = TryParseHex<uint8_t>("12 34 56 78").value();
160  BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
161 
162  // Leading space must be supported (used in BerkeleyEnvironment::Salvage)
163  result = ParseHex(" 89 34 56 78");
164  BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
165  result = TryParseHex<uint8_t>(" 89 34 56 78").value();
166  BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
167 
168  // Mixed case and spaces are supported
169  result = ParseHex(" Ff aA ");
170  BOOST_CHECK(result.size() == 2 && result[0] == 0xff && result[1] == 0xaa);
171  result = TryParseHex<uint8_t>(" Ff aA ").value();
172  BOOST_CHECK(result.size() == 2 && result[0] == 0xff && result[1] == 0xaa);
173 
174  // Empty string is supported
175  result = ParseHex("");
176  BOOST_CHECK(result.size() == 0);
177  result = TryParseHex<uint8_t>("").value();
178  BOOST_CHECK(result.size() == 0);
179 
180  // Spaces between nibbles is treated as invalid
181  BOOST_CHECK_EQUAL(ParseHex("AAF F").size(), 0);
182  BOOST_CHECK(!TryParseHex("AAF F").has_value());
183 
184  // Embedded null is treated as invalid
185  const std::string with_embedded_null{" 11 "s
186  " \0 "
187  " 22 "s};
188  BOOST_CHECK_EQUAL(with_embedded_null.size(), 11);
189  BOOST_CHECK_EQUAL(ParseHex(with_embedded_null).size(), 0);
190  BOOST_CHECK(!TryParseHex(with_embedded_null).has_value());
191 
192  // Non-hex is treated as invalid
193  BOOST_CHECK_EQUAL(ParseHex("1234 invalid 1234").size(), 0);
194  BOOST_CHECK(!TryParseHex("1234 invalid 1234").has_value());
195 
196  // Truncated input is treated as invalid
197  BOOST_CHECK_EQUAL(ParseHex("12 3").size(), 0);
198  BOOST_CHECK(!TryParseHex("12 3").has_value());
199 }
200 
202 {
205  "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
206 
208  HexStr(Span{ParseHex_expected}.last(0)),
209  "");
210 
212  HexStr(Span{ParseHex_expected}.first(0)),
213  "");
214 
215  {
216  const std::vector<char> in_s{ParseHex_expected, ParseHex_expected + 5};
217  const Span<const uint8_t> in_u{MakeUCharSpan(in_s)};
218  const Span<const std::byte> in_b{MakeByteSpan(in_s)};
219  const std::string out_exp{"04678afdb0"};
220 
221  BOOST_CHECK_EQUAL(HexStr(in_u), out_exp);
222  BOOST_CHECK_EQUAL(HexStr(in_s), out_exp);
223  BOOST_CHECK_EQUAL(HexStr(in_b), out_exp);
224  }
225 
226  {
227  auto input = std::string();
228  for (size_t i=0; i<256; ++i) {
229  input.push_back(static_cast<char>(i));
230  }
231 
232  auto hex = HexStr(input);
233  BOOST_TEST_REQUIRE(hex.size() == 512);
234  static constexpr auto hexmap = std::string_view("0123456789abcdef");
235  for (size_t i = 0; i < 256; ++i) {
236  auto upper = hexmap.find(hex[i * 2]);
237  auto lower = hexmap.find(hex[i * 2 + 1]);
238  BOOST_TEST_REQUIRE(upper != std::string_view::npos);
239  BOOST_TEST_REQUIRE(lower != std::string_view::npos);
240  BOOST_TEST_REQUIRE(i == upper*16 + lower);
241  }
242  }
243 }
244 
245 BOOST_AUTO_TEST_CASE(span_write_bytes)
246 {
247  std::array mut_arr{uint8_t{0xaa}, uint8_t{0xbb}};
248  const auto mut_bytes{MakeWritableByteSpan(mut_arr)};
249  mut_bytes[1] = std::byte{0x11};
250  BOOST_CHECK_EQUAL(mut_arr.at(0), 0xaa);
251  BOOST_CHECK_EQUAL(mut_arr.at(1), 0x11);
252 }
253 
255 {
256  // Normal version
257  BOOST_CHECK_EQUAL(Join(std::vector<std::string>{}, ", "), "");
258  BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo"}, ", "), "foo");
259  BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo", "bar"}, ", "), "foo, bar");
260 
261  // Version with unary operator
262  const auto op_upper = [](const std::string& s) { return ToUpper(s); };
263  BOOST_CHECK_EQUAL(Join(std::list<std::string>{}, ", ", op_upper), "");
264  BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo"}, ", ", op_upper), "FOO");
265  BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo", "bar"}, ", ", op_upper), "FOO, BAR");
266 }
267 
268 BOOST_AUTO_TEST_CASE(util_ReplaceAll)
269 {
270  const std::string original("A test \"%s\" string '%s'.");
271  auto test_replaceall = [&original](const std::string& search, const std::string& substitute, const std::string& expected) {
272  auto test = original;
273  ReplaceAll(test, search, substitute);
274  BOOST_CHECK_EQUAL(test, expected);
275  };
276 
277  test_replaceall("", "foo", original);
278  test_replaceall(original, "foo", "foo");
279  test_replaceall("%s", "foo", "A test \"foo\" string 'foo'.");
280  test_replaceall("\"", "foo", "A test foo%sfoo string '%s'.");
281  test_replaceall("'", "foo", "A test \"%s\" string foo%sfoo.");
282 }
283 
284 BOOST_AUTO_TEST_CASE(util_TrimString)
285 {
286  BOOST_CHECK_EQUAL(TrimString(" foo bar "), "foo bar");
287  BOOST_CHECK_EQUAL(TrimStringView("\t \n \n \f\n\r\t\v\tfoo \n \f\n\r\t\v\tbar\t \n \f\n\r\t\v\t\n "), "foo \n \f\n\r\t\v\tbar");
288  BOOST_CHECK_EQUAL(TrimString("\t \n foo \n\tbar\t \n "), "foo \n\tbar");
289  BOOST_CHECK_EQUAL(TrimStringView("\t \n foo \n\tbar\t \n ", "fobar"), "\t \n foo \n\tbar\t \n ");
290  BOOST_CHECK_EQUAL(TrimString("foo bar"), "foo bar");
291  BOOST_CHECK_EQUAL(TrimStringView("foo bar", "fobar"), " ");
292  BOOST_CHECK_EQUAL(TrimString(std::string("\0 foo \0 ", 8)), std::string("\0 foo \0", 7));
293  BOOST_CHECK_EQUAL(TrimStringView(std::string(" foo ", 5)), std::string("foo", 3));
294  BOOST_CHECK_EQUAL(TrimString(std::string("\t\t\0\0\n\n", 6)), std::string("\0\0", 2));
295  BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6)), std::string("\x05\x04\x03\x02\x01\x00", 6));
296  BOOST_CHECK_EQUAL(TrimString(std::string("\x05\x04\x03\x02\x01\x00", 6), std::string("\x05\x04\x03\x02\x01", 5)), std::string("\0", 1));
297  BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6), std::string("\x05\x04\x03\x02\x01\x00", 6)), "");
298 }
299 
300 BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime)
301 {
302  BOOST_CHECK_EQUAL(FormatISO8601DateTime(971890963199), "32767-12-31T23:59:59Z");
303  BOOST_CHECK_EQUAL(FormatISO8601DateTime(971890876800), "32767-12-31T00:00:00Z");
304  BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z");
305  BOOST_CHECK_EQUAL(FormatISO8601DateTime(0), "1970-01-01T00:00:00Z");
306 }
307 
308 BOOST_AUTO_TEST_CASE(util_FormatISO8601Date)
309 {
310  BOOST_CHECK_EQUAL(FormatISO8601Date(971890963199), "32767-12-31");
311  BOOST_CHECK_EQUAL(FormatISO8601Date(971890876800), "32767-12-31");
312  BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30");
313  BOOST_CHECK_EQUAL(FormatISO8601Date(0), "1970-01-01");
314 }
315 
316 BOOST_AUTO_TEST_CASE(util_FormatMoney)
317 {
318  BOOST_CHECK_EQUAL(FormatMoney(0), "0.00");
319  BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), "12345.6789");
320  BOOST_CHECK_EQUAL(FormatMoney(-COIN), "-1.00");
321 
322  BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), "100000000.00");
323  BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), "10000000.00");
324  BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), "1000000.00");
325  BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), "100000.00");
326  BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), "10000.00");
327  BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), "1000.00");
328  BOOST_CHECK_EQUAL(FormatMoney(COIN*100), "100.00");
329  BOOST_CHECK_EQUAL(FormatMoney(COIN*10), "10.00");
331  BOOST_CHECK_EQUAL(FormatMoney(COIN/10), "0.10");
332  BOOST_CHECK_EQUAL(FormatMoney(COIN/100), "0.01");
333  BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), "0.001");
334  BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), "0.0001");
335  BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), "0.00001");
336  BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), "0.000001");
337  BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), "0.0000001");
338  BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), "0.00000001");
339 
340  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max()), "92233720368.54775807");
341  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 1), "92233720368.54775806");
342  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 2), "92233720368.54775805");
343  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 3), "92233720368.54775804");
344  // ...
345  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 3), "-92233720368.54775805");
346  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 2), "-92233720368.54775806");
347  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 1), "-92233720368.54775807");
348  BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min()), "-92233720368.54775808");
349 }
350 
351 BOOST_AUTO_TEST_CASE(util_ParseMoney)
352 {
353  BOOST_CHECK_EQUAL(ParseMoney("0.0").value(), 0);
354  BOOST_CHECK_EQUAL(ParseMoney(".").value(), 0);
355  BOOST_CHECK_EQUAL(ParseMoney("0.").value(), 0);
356  BOOST_CHECK_EQUAL(ParseMoney(".0").value(), 0);
357  BOOST_CHECK_EQUAL(ParseMoney(".6789").value(), 6789'0000);
358  BOOST_CHECK_EQUAL(ParseMoney("12345.").value(), COIN * 12345);
359 
360  BOOST_CHECK_EQUAL(ParseMoney("12345.6789").value(), (COIN/10000)*123456789);
361 
362  BOOST_CHECK_EQUAL(ParseMoney("10000000.00").value(), COIN*10000000);
363  BOOST_CHECK_EQUAL(ParseMoney("1000000.00").value(), COIN*1000000);
364  BOOST_CHECK_EQUAL(ParseMoney("100000.00").value(), COIN*100000);
365  BOOST_CHECK_EQUAL(ParseMoney("10000.00").value(), COIN*10000);
366  BOOST_CHECK_EQUAL(ParseMoney("1000.00").value(), COIN*1000);
367  BOOST_CHECK_EQUAL(ParseMoney("100.00").value(), COIN*100);
368  BOOST_CHECK_EQUAL(ParseMoney("10.00").value(), COIN*10);
369  BOOST_CHECK_EQUAL(ParseMoney("1.00").value(), COIN);
370  BOOST_CHECK_EQUAL(ParseMoney("1").value(), COIN);
371  BOOST_CHECK_EQUAL(ParseMoney(" 1").value(), COIN);
372  BOOST_CHECK_EQUAL(ParseMoney("1 ").value(), COIN);
373  BOOST_CHECK_EQUAL(ParseMoney(" 1 ").value(), COIN);
374  BOOST_CHECK_EQUAL(ParseMoney("0.1").value(), COIN/10);
375  BOOST_CHECK_EQUAL(ParseMoney("0.01").value(), COIN/100);
376  BOOST_CHECK_EQUAL(ParseMoney("0.001").value(), COIN/1000);
377  BOOST_CHECK_EQUAL(ParseMoney("0.0001").value(), COIN/10000);
378  BOOST_CHECK_EQUAL(ParseMoney("0.00001").value(), COIN/100000);
379  BOOST_CHECK_EQUAL(ParseMoney("0.000001").value(), COIN/1000000);
380  BOOST_CHECK_EQUAL(ParseMoney("0.0000001").value(), COIN/10000000);
381  BOOST_CHECK_EQUAL(ParseMoney("0.00000001").value(), COIN/100000000);
382  BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001 ").value(), COIN/100000000);
383  BOOST_CHECK_EQUAL(ParseMoney("0.00000001 ").value(), COIN/100000000);
384  BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001").value(), COIN/100000000);
385 
386  // Parsing amount that cannot be represented should fail
387  BOOST_CHECK(!ParseMoney("100000000.00"));
388  BOOST_CHECK(!ParseMoney("0.000000001"));
389 
390  // Parsing empty string should fail
391  BOOST_CHECK(!ParseMoney(""));
392  BOOST_CHECK(!ParseMoney(" "));
393  BOOST_CHECK(!ParseMoney(" "));
394 
395  // Parsing two numbers should fail
396  BOOST_CHECK(!ParseMoney(".."));
397  BOOST_CHECK(!ParseMoney("0..0"));
398  BOOST_CHECK(!ParseMoney("1 2"));
399  BOOST_CHECK(!ParseMoney(" 1 2 "));
400  BOOST_CHECK(!ParseMoney(" 1.2 3 "));
401  BOOST_CHECK(!ParseMoney(" 1 2.3 "));
402 
403  // Embedded whitespace should fail
404  BOOST_CHECK(!ParseMoney(" -1 .2 "));
405  BOOST_CHECK(!ParseMoney(" 1 .2 "));
406  BOOST_CHECK(!ParseMoney(" +1 .2 "));
407 
408  // Attempted 63 bit overflow should fail
409  BOOST_CHECK(!ParseMoney("92233720368.54775808"));
410 
411  // Parsing negative amounts must fail
412  BOOST_CHECK(!ParseMoney("-1"));
413 
414  // Parsing strings with embedded NUL characters should fail
415  BOOST_CHECK(!ParseMoney("\0-1"s));
417  BOOST_CHECK(!ParseMoney("1\0"s));
418 }
419 
421 {
422  BOOST_CHECK(IsHex("00"));
423  BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
424  BOOST_CHECK(IsHex("ff"));
425  BOOST_CHECK(IsHex("FF"));
426 
427  BOOST_CHECK(!IsHex(""));
428  BOOST_CHECK(!IsHex("0"));
429  BOOST_CHECK(!IsHex("a"));
430  BOOST_CHECK(!IsHex("eleven"));
431  BOOST_CHECK(!IsHex("00xx00"));
432  BOOST_CHECK(!IsHex("0x0000"));
433 }
434 
435 BOOST_AUTO_TEST_CASE(util_IsHexNumber)
436 {
437  BOOST_CHECK(IsHexNumber("0x0"));
438  BOOST_CHECK(IsHexNumber("0"));
439  BOOST_CHECK(IsHexNumber("0x10"));
440  BOOST_CHECK(IsHexNumber("10"));
441  BOOST_CHECK(IsHexNumber("0xff"));
442  BOOST_CHECK(IsHexNumber("ff"));
443  BOOST_CHECK(IsHexNumber("0xFfa"));
444  BOOST_CHECK(IsHexNumber("Ffa"));
445  BOOST_CHECK(IsHexNumber("0x00112233445566778899aabbccddeeffAABBCCDDEEFF"));
446  BOOST_CHECK(IsHexNumber("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
447 
448  BOOST_CHECK(!IsHexNumber("")); // empty string not allowed
449  BOOST_CHECK(!IsHexNumber("0x")); // empty string after prefix not allowed
450  BOOST_CHECK(!IsHexNumber("0x0 ")); // no spaces at end,
451  BOOST_CHECK(!IsHexNumber(" 0x0")); // or beginning,
452  BOOST_CHECK(!IsHexNumber("0x 0")); // or middle,
453  BOOST_CHECK(!IsHexNumber(" ")); // etc.
454  BOOST_CHECK(!IsHexNumber("0x0ga")); // invalid character
455  BOOST_CHECK(!IsHexNumber("x0")); // broken prefix
456  BOOST_CHECK(!IsHexNumber("0x0x00")); // two prefixes not allowed
457 
458 }
459 
460 BOOST_AUTO_TEST_CASE(util_seed_insecure_rand)
461 {
463  for (int mod=2;mod<11;mod++)
464  {
465  int mask = 1;
466  // Really rough binomial confidence approximation.
467  int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.);
468  //mask is 2^ceil(log2(mod))-1
469  while(mask<mod-1)mask=(mask<<1)+1;
470 
471  int count = 0;
472  //How often does it get a zero from the uniform range [0,mod)?
473  for (int i = 0; i < 10000; i++) {
474  uint32_t rval;
475  do{
476  rval=InsecureRand32()&mask;
477  }while(rval>=(uint32_t)mod);
478  count += rval==0;
479  }
480  BOOST_CHECK(count<=10000/mod+err);
481  BOOST_CHECK(count>=10000/mod-err);
482  }
483 }
484 
485 BOOST_AUTO_TEST_CASE(util_TimingResistantEqual)
486 {
487  BOOST_CHECK(TimingResistantEqual(std::string(""), std::string("")));
488  BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("")));
489  BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc")));
490  BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa")));
491  BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a")));
492  BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc")));
493  BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba")));
494 }
495 
496 /* Test strprintf formatting directives.
497  * Put a string before and after to ensure sanity of element sizes on stack. */
498 #define B "check_prefix"
499 #define E "check_postfix"
500 BOOST_AUTO_TEST_CASE(strprintf_numbers)
501 {
502  int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */
503  uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */
504  BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E);
505  BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E);
506  BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E);
507 
508  size_t st = 12345678; /* unsigned size_t test value */
509  ssize_t sst = -12345678; /* signed size_t test value */
510  BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E);
511  BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E);
512  BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E);
513 
514  ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */
515  ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */
516  BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E);
517  BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E);
518  BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E);
519 }
520 #undef B
521 #undef E
522 
523 /* Check for mingw/wine issue #3494
524  * Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106'
525  */
527 {
528  BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0);
529 }
530 
531 BOOST_AUTO_TEST_CASE(util_time_GetTime)
532 {
533  SetMockTime(111);
534  // Check that mock time does not change after a sleep
535  for (const auto& num_sleep : {0ms, 1ms}) {
536  UninterruptibleSleep(num_sleep);
537  BOOST_CHECK_EQUAL(111, GetTime()); // Deprecated time getter
538  BOOST_CHECK_EQUAL(111, Now<NodeSeconds>().time_since_epoch().count());
539  BOOST_CHECK_EQUAL(111, TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()));
540  BOOST_CHECK_EQUAL(111, TicksSinceEpoch<SecondsDouble>(Now<NodeSeconds>()));
541  BOOST_CHECK_EQUAL(111, GetTime<std::chrono::seconds>().count());
542  BOOST_CHECK_EQUAL(111000, GetTime<std::chrono::milliseconds>().count());
543  BOOST_CHECK_EQUAL(111000, TicksSinceEpoch<std::chrono::milliseconds>(NodeClock::now()));
544  BOOST_CHECK_EQUAL(111000000, GetTime<std::chrono::microseconds>().count());
545  }
546 
547  SetMockTime(0);
548  // Check that steady time and system time changes after a sleep
549  const auto steady_ms_0 = Now<SteadyMilliseconds>();
550  const auto steady_0 = std::chrono::steady_clock::now();
551  const auto ms_0 = GetTime<std::chrono::milliseconds>();
552  const auto us_0 = GetTime<std::chrono::microseconds>();
554  BOOST_CHECK(steady_ms_0 < Now<SteadyMilliseconds>());
555  BOOST_CHECK(steady_0 + 1ms <= std::chrono::steady_clock::now());
556  BOOST_CHECK(ms_0 < GetTime<std::chrono::milliseconds>());
557  BOOST_CHECK(us_0 < GetTime<std::chrono::microseconds>());
558 }
559 
560 BOOST_AUTO_TEST_CASE(test_IsDigit)
561 {
562  BOOST_CHECK_EQUAL(IsDigit('0'), true);
563  BOOST_CHECK_EQUAL(IsDigit('1'), true);
564  BOOST_CHECK_EQUAL(IsDigit('8'), true);
565  BOOST_CHECK_EQUAL(IsDigit('9'), true);
566 
567  BOOST_CHECK_EQUAL(IsDigit('0' - 1), false);
568  BOOST_CHECK_EQUAL(IsDigit('9' + 1), false);
569  BOOST_CHECK_EQUAL(IsDigit(0), false);
570  BOOST_CHECK_EQUAL(IsDigit(1), false);
571  BOOST_CHECK_EQUAL(IsDigit(8), false);
572  BOOST_CHECK_EQUAL(IsDigit(9), false);
573 }
574 
575 /* Check for overflow */
576 template <typename T>
578 {
579  constexpr T MAXI{std::numeric_limits<T>::max()};
580  BOOST_CHECK(!CheckedAdd(T{1}, MAXI));
581  BOOST_CHECK(!CheckedAdd(MAXI, MAXI));
582  BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{1}, MAXI));
583  BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(MAXI, MAXI));
584 
585  BOOST_CHECK_EQUAL(0, CheckedAdd(T{0}, T{0}).value());
586  BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{0}, MAXI).value());
587  BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{1}, MAXI - 1).value());
588  BOOST_CHECK_EQUAL(MAXI - 1, CheckedAdd(T{1}, MAXI - 2).value());
589  BOOST_CHECK_EQUAL(0, SaturatingAdd(T{0}, T{0}));
590  BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{0}, MAXI));
591  BOOST_CHECK_EQUAL(MAXI, SaturatingAdd(T{1}, MAXI - 1));
592  BOOST_CHECK_EQUAL(MAXI - 1, SaturatingAdd(T{1}, MAXI - 2));
593 }
594 
595 /* Check for overflow or underflow */
596 template <typename T>
597 static void TestAddMatrix()
598 {
599  TestAddMatrixOverflow<T>();
600  constexpr T MINI{std::numeric_limits<T>::min()};
601  constexpr T MAXI{std::numeric_limits<T>::max()};
602  BOOST_CHECK(!CheckedAdd(T{-1}, MINI));
603  BOOST_CHECK(!CheckedAdd(MINI, MINI));
604  BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{-1}, MINI));
605  BOOST_CHECK_EQUAL(MINI, SaturatingAdd(MINI, MINI));
606 
607  BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{0}, MINI).value());
608  BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{-1}, MINI + 1).value());
609  BOOST_CHECK_EQUAL(-1, CheckedAdd(MINI, MAXI).value());
610  BOOST_CHECK_EQUAL(MINI + 1, CheckedAdd(T{-1}, MINI + 2).value());
611  BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{0}, MINI));
612  BOOST_CHECK_EQUAL(MINI, SaturatingAdd(T{-1}, MINI + 1));
613  BOOST_CHECK_EQUAL(MINI + 1, SaturatingAdd(T{-1}, MINI + 2));
614  BOOST_CHECK_EQUAL(-1, SaturatingAdd(MINI, MAXI));
615 }
616 
617 BOOST_AUTO_TEST_CASE(util_overflow)
618 {
619  TestAddMatrixOverflow<unsigned>();
620  TestAddMatrix<signed>();
621 }
622 
623 BOOST_AUTO_TEST_CASE(test_ParseInt32)
624 {
625  int32_t n;
626  // Valid values
627  BOOST_CHECK(ParseInt32("1234", nullptr));
628  BOOST_CHECK(ParseInt32("0", &n) && n == 0);
629  BOOST_CHECK(ParseInt32("1234", &n) && n == 1234);
630  BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal
631  BOOST_CHECK(ParseInt32("2147483647", &n) && n == 2147483647);
632  BOOST_CHECK(ParseInt32("-2147483648", &n) && n == (-2147483647 - 1)); // (-2147483647 - 1) equals INT_MIN
633  BOOST_CHECK(ParseInt32("-1234", &n) && n == -1234);
634  BOOST_CHECK(ParseInt32("00000000000000001234", &n) && n == 1234);
635  BOOST_CHECK(ParseInt32("-00000000000000001234", &n) && n == -1234);
636  BOOST_CHECK(ParseInt32("00000000000000000000", &n) && n == 0);
637  BOOST_CHECK(ParseInt32("-00000000000000000000", &n) && n == 0);
638  // Invalid values
639  BOOST_CHECK(!ParseInt32("", &n));
640  BOOST_CHECK(!ParseInt32(" 1", &n)); // no padding inside
641  BOOST_CHECK(!ParseInt32("1 ", &n));
642  BOOST_CHECK(!ParseInt32("++1", &n));
643  BOOST_CHECK(!ParseInt32("+-1", &n));
644  BOOST_CHECK(!ParseInt32("-+1", &n));
645  BOOST_CHECK(!ParseInt32("--1", &n));
646  BOOST_CHECK(!ParseInt32("1a", &n));
647  BOOST_CHECK(!ParseInt32("aap", &n));
648  BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex
650  // Overflow and underflow
651  BOOST_CHECK(!ParseInt32("-2147483649", nullptr));
652  BOOST_CHECK(!ParseInt32("2147483648", nullptr));
653  BOOST_CHECK(!ParseInt32("-32482348723847471234", nullptr));
654  BOOST_CHECK(!ParseInt32("32482348723847471234", nullptr));
655 }
656 
657 template <typename T>
658 static void RunToIntegralTests()
659 {
661  BOOST_CHECK(!ToIntegral<T>(" 1"));
662  BOOST_CHECK(!ToIntegral<T>("1 "));
663  BOOST_CHECK(!ToIntegral<T>("1a"));
664  BOOST_CHECK(!ToIntegral<T>("1.1"));
665  BOOST_CHECK(!ToIntegral<T>("1.9"));
666  BOOST_CHECK(!ToIntegral<T>("+01.9"));
667  BOOST_CHECK(!ToIntegral<T>("-"));
668  BOOST_CHECK(!ToIntegral<T>("+"));
669  BOOST_CHECK(!ToIntegral<T>(" -1"));
670  BOOST_CHECK(!ToIntegral<T>("-1 "));
671  BOOST_CHECK(!ToIntegral<T>(" -1 "));
672  BOOST_CHECK(!ToIntegral<T>("+1"));
673  BOOST_CHECK(!ToIntegral<T>(" +1"));
674  BOOST_CHECK(!ToIntegral<T>(" +1 "));
675  BOOST_CHECK(!ToIntegral<T>("+-1"));
676  BOOST_CHECK(!ToIntegral<T>("-+1"));
677  BOOST_CHECK(!ToIntegral<T>("++1"));
678  BOOST_CHECK(!ToIntegral<T>("--1"));
679  BOOST_CHECK(!ToIntegral<T>(""));
680  BOOST_CHECK(!ToIntegral<T>("aap"));
681  BOOST_CHECK(!ToIntegral<T>("0x1"));
682  BOOST_CHECK(!ToIntegral<T>("-32482348723847471234"));
683  BOOST_CHECK(!ToIntegral<T>("32482348723847471234"));
684 }
685 
686 BOOST_AUTO_TEST_CASE(test_ToIntegral)
687 {
688  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("1234").value(), 1'234);
689  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("0").value(), 0);
690  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("01234").value(), 1'234);
691  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000001234").value(), 1'234);
692  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000001234").value(), -1'234);
693  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000000000").value(), 0);
694  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000000000").value(), 0);
695  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1234").value(), -1'234);
696  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1").value(), -1);
697 
698  RunToIntegralTests<uint64_t>();
699  RunToIntegralTests<int64_t>();
700  RunToIntegralTests<uint32_t>();
701  RunToIntegralTests<int32_t>();
702  RunToIntegralTests<uint16_t>();
703  RunToIntegralTests<int16_t>();
704  RunToIntegralTests<uint8_t>();
705  RunToIntegralTests<int8_t>();
706 
707  BOOST_CHECK(!ToIntegral<int64_t>("-9223372036854775809"));
708  BOOST_CHECK_EQUAL(ToIntegral<int64_t>("-9223372036854775808").value(), -9'223'372'036'854'775'807LL - 1LL);
709  BOOST_CHECK_EQUAL(ToIntegral<int64_t>("9223372036854775807").value(), 9'223'372'036'854'775'807);
710  BOOST_CHECK(!ToIntegral<int64_t>("9223372036854775808"));
711 
712  BOOST_CHECK(!ToIntegral<uint64_t>("-1"));
713  BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("0").value(), 0U);
714  BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("18446744073709551615").value(), 18'446'744'073'709'551'615ULL);
715  BOOST_CHECK(!ToIntegral<uint64_t>("18446744073709551616"));
716 
717  BOOST_CHECK(!ToIntegral<int32_t>("-2147483649"));
718  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-2147483648").value(), -2'147'483'648LL);
719  BOOST_CHECK_EQUAL(ToIntegral<int32_t>("2147483647").value(), 2'147'483'647);
720  BOOST_CHECK(!ToIntegral<int32_t>("2147483648"));
721 
722  BOOST_CHECK(!ToIntegral<uint32_t>("-1"));
723  BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("0").value(), 0U);
724  BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("4294967295").value(), 4'294'967'295U);
725  BOOST_CHECK(!ToIntegral<uint32_t>("4294967296"));
726 
727  BOOST_CHECK(!ToIntegral<int16_t>("-32769"));
728  BOOST_CHECK_EQUAL(ToIntegral<int16_t>("-32768").value(), -32'768);
729  BOOST_CHECK_EQUAL(ToIntegral<int16_t>("32767").value(), 32'767);
730  BOOST_CHECK(!ToIntegral<int16_t>("32768"));
731 
732  BOOST_CHECK(!ToIntegral<uint16_t>("-1"));
733  BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("0").value(), 0U);
734  BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("65535").value(), 65'535U);
735  BOOST_CHECK(!ToIntegral<uint16_t>("65536"));
736 
737  BOOST_CHECK(!ToIntegral<int8_t>("-129"));
738  BOOST_CHECK_EQUAL(ToIntegral<int8_t>("-128").value(), -128);
739  BOOST_CHECK_EQUAL(ToIntegral<int8_t>("127").value(), 127);
740  BOOST_CHECK(!ToIntegral<int8_t>("128"));
741 
742  BOOST_CHECK(!ToIntegral<uint8_t>("-1"));
743  BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("0").value(), 0U);
744  BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("255").value(), 255U);
745  BOOST_CHECK(!ToIntegral<uint8_t>("256"));
746 }
747 
748 int64_t atoi64_legacy(const std::string& str)
749 {
750  return strtoll(str.c_str(), nullptr, 10);
751 }
752 
753 BOOST_AUTO_TEST_CASE(test_LocaleIndependentAtoi)
754 {
755  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1234"), 1'234);
756  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0"), 0);
757  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("01234"), 1'234);
758  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1234"), -1'234);
759  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" 1"), 1);
760  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1 "), 1);
761  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1a"), 1);
762  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.1"), 1);
763  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("1.9"), 1);
764  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+01.9"), 1);
765  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1"), -1);
766  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1"), -1);
767  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-1 "), -1);
768  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" -1 "), -1);
769  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+1"), 1);
770  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1"), 1);
771  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(" +1 "), 1);
772 
773  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("+-1"), 0);
774  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-+1"), 0);
775  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("++1"), 0);
776  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("--1"), 0);
777  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>(""), 0);
778  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("aap"), 0);
779  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("0x1"), 0);
780  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-32482348723847471234"), -2'147'483'647 - 1);
781  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("32482348723847471234"), 2'147'483'647);
782 
783  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775809"), -9'223'372'036'854'775'807LL - 1LL);
784  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775808"), -9'223'372'036'854'775'807LL - 1LL);
785  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775807"), 9'223'372'036'854'775'807);
786  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775808"), 9'223'372'036'854'775'807);
787 
788  std::map<std::string, int64_t> atoi64_test_pairs = {
789  {"-9223372036854775809", std::numeric_limits<int64_t>::min()},
790  {"-9223372036854775808", -9'223'372'036'854'775'807LL - 1LL},
791  {"9223372036854775807", 9'223'372'036'854'775'807},
792  {"9223372036854775808", std::numeric_limits<int64_t>::max()},
793  {"+-", 0},
794  {"0x1", 0},
795  {"ox1", 0},
796  {"", 0},
797  };
798 
799  for (const auto& pair : atoi64_test_pairs) {
800  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>(pair.first), pair.second);
801  }
802 
803  // Ensure legacy compatibility with previous versions of Bitcoin Core's atoi64
804  for (const auto& pair : atoi64_test_pairs) {
805  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>(pair.first), atoi64_legacy(pair.first));
806  }
807 
808  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("-1"), 0U);
809  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("0"), 0U);
810  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551615"), 18'446'744'073'709'551'615ULL);
811  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551616"), 18'446'744'073'709'551'615ULL);
812 
813  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483649"), -2'147'483'648LL);
814  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483648"), -2'147'483'648LL);
815  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483647"), 2'147'483'647);
816  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483648"), 2'147'483'647);
817 
818  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("-1"), 0U);
819  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("0"), 0U);
820  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967295"), 4'294'967'295U);
821  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967296"), 4'294'967'295U);
822 
823  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32769"), -32'768);
824  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("-32768"), -32'768);
825  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32767"), 32'767);
826  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int16_t>("32768"), 32'767);
827 
828  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("-1"), 0U);
829  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("0"), 0U);
830  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65535"), 65'535U);
831  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint16_t>("65536"), 65'535U);
832 
833  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-129"), -128);
834  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("-128"), -128);
835  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("127"), 127);
836  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int8_t>("128"), 127);
837 
838  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("-1"), 0U);
839  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("0"), 0U);
840  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("255"), 255U);
841  BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint8_t>("256"), 255U);
842 }
843 
844 BOOST_AUTO_TEST_CASE(test_ParseInt64)
845 {
846  int64_t n;
847  // Valid values
848  BOOST_CHECK(ParseInt64("1234", nullptr));
849  BOOST_CHECK(ParseInt64("0", &n) && n == 0LL);
850  BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL);
851  BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal
852  BOOST_CHECK(ParseInt64("2147483647", &n) && n == 2147483647LL);
853  BOOST_CHECK(ParseInt64("-2147483648", &n) && n == -2147483648LL);
854  BOOST_CHECK(ParseInt64("9223372036854775807", &n) && n == int64_t{9223372036854775807});
855  BOOST_CHECK(ParseInt64("-9223372036854775808", &n) && n == int64_t{-9223372036854775807-1});
856  BOOST_CHECK(ParseInt64("-1234", &n) && n == -1234LL);
857  // Invalid values
858  BOOST_CHECK(!ParseInt64("", &n));
859  BOOST_CHECK(!ParseInt64(" 1", &n)); // no padding inside
860  BOOST_CHECK(!ParseInt64("1 ", &n));
861  BOOST_CHECK(!ParseInt64("1a", &n));
862  BOOST_CHECK(!ParseInt64("aap", &n));
863  BOOST_CHECK(!ParseInt64("0x1", &n)); // no hex
865  // Overflow and underflow
866  BOOST_CHECK(!ParseInt64("-9223372036854775809", nullptr));
867  BOOST_CHECK(!ParseInt64("9223372036854775808", nullptr));
868  BOOST_CHECK(!ParseInt64("-32482348723847471234", nullptr));
869  BOOST_CHECK(!ParseInt64("32482348723847471234", nullptr));
870 }
871 
872 BOOST_AUTO_TEST_CASE(test_ParseUInt8)
873 {
874  uint8_t n;
875  // Valid values
876  BOOST_CHECK(ParseUInt8("255", nullptr));
877  BOOST_CHECK(ParseUInt8("0", &n) && n == 0);
878  BOOST_CHECK(ParseUInt8("255", &n) && n == 255);
879  BOOST_CHECK(ParseUInt8("0255", &n) && n == 255); // no octal
880  BOOST_CHECK(ParseUInt8("255", &n) && n == static_cast<uint8_t>(255));
881  BOOST_CHECK(ParseUInt8("+255", &n) && n == 255);
882  BOOST_CHECK(ParseUInt8("00000000000000000012", &n) && n == 12);
883  BOOST_CHECK(ParseUInt8("00000000000000000000", &n) && n == 0);
884  // Invalid values
885  BOOST_CHECK(!ParseUInt8("-00000000000000000000", &n));
886  BOOST_CHECK(!ParseUInt8("", &n));
887  BOOST_CHECK(!ParseUInt8(" 1", &n)); // no padding inside
888  BOOST_CHECK(!ParseUInt8(" -1", &n));
889  BOOST_CHECK(!ParseUInt8("++1", &n));
890  BOOST_CHECK(!ParseUInt8("+-1", &n));
891  BOOST_CHECK(!ParseUInt8("-+1", &n));
892  BOOST_CHECK(!ParseUInt8("--1", &n));
893  BOOST_CHECK(!ParseUInt8("-1", &n));
894  BOOST_CHECK(!ParseUInt8("1 ", &n));
895  BOOST_CHECK(!ParseUInt8("1a", &n));
896  BOOST_CHECK(!ParseUInt8("aap", &n));
897  BOOST_CHECK(!ParseUInt8("0x1", &n)); // no hex
899  // Overflow and underflow
900  BOOST_CHECK(!ParseUInt8("-255", &n));
901  BOOST_CHECK(!ParseUInt8("256", &n));
902  BOOST_CHECK(!ParseUInt8("-123", &n));
903  BOOST_CHECK(!ParseUInt8("-123", nullptr));
904  BOOST_CHECK(!ParseUInt8("256", nullptr));
905 }
906 
907 BOOST_AUTO_TEST_CASE(test_ParseUInt16)
908 {
909  uint16_t n;
910  // Valid values
911  BOOST_CHECK(ParseUInt16("1234", nullptr));
912  BOOST_CHECK(ParseUInt16("0", &n) && n == 0);
913  BOOST_CHECK(ParseUInt16("1234", &n) && n == 1234);
914  BOOST_CHECK(ParseUInt16("01234", &n) && n == 1234); // no octal
915  BOOST_CHECK(ParseUInt16("65535", &n) && n == static_cast<uint16_t>(65535));
916  BOOST_CHECK(ParseUInt16("+65535", &n) && n == 65535);
917  BOOST_CHECK(ParseUInt16("00000000000000000012", &n) && n == 12);
918  BOOST_CHECK(ParseUInt16("00000000000000000000", &n) && n == 0);
919  // Invalid values
920  BOOST_CHECK(!ParseUInt16("-00000000000000000000", &n));
921  BOOST_CHECK(!ParseUInt16("", &n));
922  BOOST_CHECK(!ParseUInt16(" 1", &n)); // no padding inside
923  BOOST_CHECK(!ParseUInt16(" -1", &n));
924  BOOST_CHECK(!ParseUInt16("++1", &n));
925  BOOST_CHECK(!ParseUInt16("+-1", &n));
926  BOOST_CHECK(!ParseUInt16("-+1", &n));
927  BOOST_CHECK(!ParseUInt16("--1", &n));
928  BOOST_CHECK(!ParseUInt16("-1", &n));
929  BOOST_CHECK(!ParseUInt16("1 ", &n));
930  BOOST_CHECK(!ParseUInt16("1a", &n));
931  BOOST_CHECK(!ParseUInt16("aap", &n));
932  BOOST_CHECK(!ParseUInt16("0x1", &n)); // no hex
934  // Overflow and underflow
935  BOOST_CHECK(!ParseUInt16("-65535", &n));
936  BOOST_CHECK(!ParseUInt16("65536", &n));
937  BOOST_CHECK(!ParseUInt16("-123", &n));
938  BOOST_CHECK(!ParseUInt16("-123", nullptr));
939  BOOST_CHECK(!ParseUInt16("65536", nullptr));
940 }
941 
942 BOOST_AUTO_TEST_CASE(test_ParseUInt32)
943 {
944  uint32_t n;
945  // Valid values
946  BOOST_CHECK(ParseUInt32("1234", nullptr));
947  BOOST_CHECK(ParseUInt32("0", &n) && n == 0);
948  BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234);
949  BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal
950  BOOST_CHECK(ParseUInt32("2147483647", &n) && n == 2147483647);
951  BOOST_CHECK(ParseUInt32("2147483648", &n) && n == uint32_t{2147483648});
952  BOOST_CHECK(ParseUInt32("4294967295", &n) && n == uint32_t{4294967295});
953  BOOST_CHECK(ParseUInt32("+1234", &n) && n == 1234);
954  BOOST_CHECK(ParseUInt32("00000000000000001234", &n) && n == 1234);
955  BOOST_CHECK(ParseUInt32("00000000000000000000", &n) && n == 0);
956  // Invalid values
957  BOOST_CHECK(!ParseUInt32("-00000000000000000000", &n));
958  BOOST_CHECK(!ParseUInt32("", &n));
959  BOOST_CHECK(!ParseUInt32(" 1", &n)); // no padding inside
960  BOOST_CHECK(!ParseUInt32(" -1", &n));
961  BOOST_CHECK(!ParseUInt32("++1", &n));
962  BOOST_CHECK(!ParseUInt32("+-1", &n));
963  BOOST_CHECK(!ParseUInt32("-+1", &n));
964  BOOST_CHECK(!ParseUInt32("--1", &n));
965  BOOST_CHECK(!ParseUInt32("-1", &n));
966  BOOST_CHECK(!ParseUInt32("1 ", &n));
967  BOOST_CHECK(!ParseUInt32("1a", &n));
968  BOOST_CHECK(!ParseUInt32("aap", &n));
969  BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex
971  // Overflow and underflow
972  BOOST_CHECK(!ParseUInt32("-2147483648", &n));
973  BOOST_CHECK(!ParseUInt32("4294967296", &n));
974  BOOST_CHECK(!ParseUInt32("-1234", &n));
975  BOOST_CHECK(!ParseUInt32("-32482348723847471234", nullptr));
976  BOOST_CHECK(!ParseUInt32("32482348723847471234", nullptr));
977 }
978 
979 BOOST_AUTO_TEST_CASE(test_ParseUInt64)
980 {
981  uint64_t n;
982  // Valid values
983  BOOST_CHECK(ParseUInt64("1234", nullptr));
984  BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL);
985  BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL);
986  BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal
987  BOOST_CHECK(ParseUInt64("2147483647", &n) && n == 2147483647LL);
988  BOOST_CHECK(ParseUInt64("9223372036854775807", &n) && n == 9223372036854775807ULL);
989  BOOST_CHECK(ParseUInt64("9223372036854775808", &n) && n == 9223372036854775808ULL);
990  BOOST_CHECK(ParseUInt64("18446744073709551615", &n) && n == 18446744073709551615ULL);
991  // Invalid values
992  BOOST_CHECK(!ParseUInt64("", &n));
993  BOOST_CHECK(!ParseUInt64(" 1", &n)); // no padding inside
994  BOOST_CHECK(!ParseUInt64(" -1", &n));
995  BOOST_CHECK(!ParseUInt64("1 ", &n));
996  BOOST_CHECK(!ParseUInt64("1a", &n));
997  BOOST_CHECK(!ParseUInt64("aap", &n));
998  BOOST_CHECK(!ParseUInt64("0x1", &n)); // no hex
1000  // Overflow and underflow
1001  BOOST_CHECK(!ParseUInt64("-9223372036854775809", nullptr));
1002  BOOST_CHECK(!ParseUInt64("18446744073709551616", nullptr));
1003  BOOST_CHECK(!ParseUInt64("-32482348723847471234", nullptr));
1004  BOOST_CHECK(!ParseUInt64("-2147483648", &n));
1005  BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n));
1006  BOOST_CHECK(!ParseUInt64("-1234", &n));
1007 }
1008 
1009 BOOST_AUTO_TEST_CASE(test_FormatParagraph)
1010 {
1011  BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), "");
1012  BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test");
1013  BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), " test");
1014  BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test");
1015  BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest");
1016  BOOST_CHECK_EQUAL(FormatParagraph("testerde test", 4, 0), "testerde\ntest");
1017  BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test");
1018 
1019  // Make sure we don't indent a fully-new line following a too-long line ending
1020  BOOST_CHECK_EQUAL(FormatParagraph("test test\nabc", 4, 4), "test\n test\nabc");
1021 
1022  BOOST_CHECK_EQUAL(FormatParagraph("This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length until it gets here", 79), "This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length\nuntil it gets here");
1023 
1024  // Test wrap length is exact
1025  BOOST_CHECK_EQUAL(FormatParagraph("a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
1026  BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
1027  // Indent should be included in length of lines
1028  BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg h i j k", 79, 4), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\n f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg\n h i j k");
1029 
1030  BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string. This is a second sentence in the very long test string.", 79), "This is a very long test string. This is a second sentence in the very long\ntest string.");
1031  BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
1032  BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
1033  BOOST_CHECK_EQUAL(FormatParagraph("Testing that normal newlines do not get indented.\nLike here.", 79), "Testing that normal newlines do not get indented.\nLike here.");
1034 }
1035 
1036 BOOST_AUTO_TEST_CASE(test_FormatSubVersion)
1037 {
1038  std::vector<std::string> comments;
1039  comments.emplace_back("comment1");
1040  std::vector<std::string> comments2;
1041  comments2.emplace_back("comment1");
1042  comments2.push_back(SanitizeString(std::string("Comment2; .,_?@-; !\"#$%&'()*+/<=>[]\\^`{|}~"), SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014
1043  BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:9.99.0/"));
1044  BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:9.99.0(comment1)/"));
1045  BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:9.99.0(comment1; Comment2; .,_?@-; )/"));
1046 }
1047 
1048 BOOST_AUTO_TEST_CASE(test_ParseFixedPoint)
1049 {
1050  int64_t amount = 0;
1051  BOOST_CHECK(ParseFixedPoint("0", 8, &amount));
1052  BOOST_CHECK_EQUAL(amount, 0LL);
1053  BOOST_CHECK(ParseFixedPoint("1", 8, &amount));
1054  BOOST_CHECK_EQUAL(amount, 100000000LL);
1055  BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount));
1056  BOOST_CHECK_EQUAL(amount, 0LL);
1057  BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount));
1058  BOOST_CHECK_EQUAL(amount, -10000000LL);
1059  BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount));
1060  BOOST_CHECK_EQUAL(amount, 110000000LL);
1061  BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount));
1062  BOOST_CHECK_EQUAL(amount, 110000000LL);
1063  BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount));
1064  BOOST_CHECK_EQUAL(amount, 1100000000LL);
1065  BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount));
1066  BOOST_CHECK_EQUAL(amount, 11000000LL);
1067  BOOST_CHECK(ParseFixedPoint("1000", 8, &amount));
1068  BOOST_CHECK_EQUAL(amount, 100000000000LL);
1069  BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount));
1070  BOOST_CHECK_EQUAL(amount, -100000000000LL);
1071  BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount));
1072  BOOST_CHECK_EQUAL(amount, 1LL);
1073  BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount));
1074  BOOST_CHECK_EQUAL(amount, 1LL);
1075  BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount));
1076  BOOST_CHECK_EQUAL(amount, -1LL);
1077  BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount));
1078  BOOST_CHECK_EQUAL(amount, 100000000000000001LL);
1079  BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount));
1080  BOOST_CHECK_EQUAL(amount, 999999999999999999LL);
1081  BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount));
1082  BOOST_CHECK_EQUAL(amount, -999999999999999999LL);
1083 
1084  BOOST_CHECK(!ParseFixedPoint("", 8, &amount));
1085  BOOST_CHECK(!ParseFixedPoint("-", 8, &amount));
1086  BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount));
1087  BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount));
1088  BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount));
1089  BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount));
1090  BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount));
1091  BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount));
1092  BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount));
1093  BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount));
1094  BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount));
1095  BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount));
1096  BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount));
1097  BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount));
1098  BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount));
1099  BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount));
1100  BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount));
1101  BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount));
1102  BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount));
1103  BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount));
1104  BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount));
1105  BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount));
1106  BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount));
1107  BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount));
1108  BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount));
1109  BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount));
1110  BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount));
1111 
1112  // Test with 3 decimal places for fee rates in sat/vB.
1113  BOOST_CHECK(ParseFixedPoint("0.001", 3, &amount));
1114  BOOST_CHECK_EQUAL(amount, CAmount{1});
1115  BOOST_CHECK(!ParseFixedPoint("0.0009", 3, &amount));
1116  BOOST_CHECK(!ParseFixedPoint("31.00100001", 3, &amount));
1117  BOOST_CHECK(!ParseFixedPoint("31.0011", 3, &amount));
1118  BOOST_CHECK(!ParseFixedPoint("31.99999999", 3, &amount));
1119  BOOST_CHECK(!ParseFixedPoint("31.999999999999999999999", 3, &amount));
1120 }
1121 
1122 #ifndef WIN32 // Cannot do this test on WIN32 due to lack of fork()
1123 static constexpr char LockCommand = 'L';
1124 static constexpr char UnlockCommand = 'U';
1125 static constexpr char ExitCommand = 'X';
1126 enum : char {
1127  ResSuccess = 2, // Start with 2 to avoid accidental collision with common values 0 and 1
1131 };
1132 
1133 [[noreturn]] static void TestOtherProcess(fs::path dirname, fs::path lockname, int fd)
1134 {
1135  char ch;
1136  while (true) {
1137  int rv = read(fd, &ch, 1); // Wait for command
1138  assert(rv == 1);
1139  switch (ch) {
1140  case LockCommand:
1141  ch = [&] {
1142  switch (util::LockDirectory(dirname, lockname)) {
1146  } // no default case, so the compiler can warn about missing cases
1147  assert(false);
1148  }();
1149  rv = write(fd, &ch, 1);
1150  assert(rv == 1);
1151  break;
1152  case UnlockCommand:
1154  ch = ResUnlockSuccess; // Always succeeds
1155  rv = write(fd, &ch, 1);
1156  assert(rv == 1);
1157  break;
1158  case ExitCommand:
1159  close(fd);
1160  exit(0);
1161  default:
1162  assert(0);
1163  }
1164  }
1165 }
1166 #endif
1167 
1168 BOOST_AUTO_TEST_CASE(test_LockDirectory)
1169 {
1170  fs::path dirname = m_args.GetDataDirBase() / "lock_dir";
1171  const fs::path lockname = ".lock";
1172 #ifndef WIN32
1173  // Revert SIGCHLD to default, otherwise boost.test will catch and fail on
1174  // it: there is BOOST_TEST_IGNORE_SIGCHLD but that only works when defined
1175  // at build-time of the boost library
1176  void (*old_handler)(int) = signal(SIGCHLD, SIG_DFL);
1177 
1178  // Fork another process for testing before creating the lock, so that we
1179  // won't fork while holding the lock (which might be undefined, and is not
1180  // relevant as test case as that is avoided with -daemonize).
1181  int fd[2];
1182  BOOST_CHECK_EQUAL(socketpair(AF_UNIX, SOCK_STREAM, 0, fd), 0);
1183  pid_t pid = fork();
1184  if (!pid) {
1185  BOOST_CHECK_EQUAL(close(fd[1]), 0); // Child: close parent end
1186  TestOtherProcess(dirname, lockname, fd[0]);
1187  }
1188  BOOST_CHECK_EQUAL(close(fd[0]), 0); // Parent: close child end
1189 
1190  char ch;
1191  // Lock on non-existent directory should fail
1192  BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1193  BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1195 #endif
1196  // Lock on non-existent directory should fail
1198 
1199  fs::create_directories(dirname);
1200 
1201  // Probing lock on new directory should succeed
1203 
1204  // Persistent lock on new directory should succeed
1206 
1207  // Another lock on the directory from the same thread should succeed
1209 
1210  // Another lock on the directory from a different thread within the same process should succeed
1211  util::LockResult threadresult;
1212  std::thread thr([&] { threadresult = util::LockDirectory(dirname, lockname); });
1213  thr.join();
1215 #ifndef WIN32
1216  // Try to acquire lock in child process while we're holding it, this should fail.
1217  BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1218  BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1220 
1221  // Give up our lock
1223  // Probing lock from our side now should succeed, but not hold on to the lock.
1225 
1226  // Try to acquire the lock in the child process, this should be successful.
1227  BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1228  BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1230 
1231  // When we try to probe the lock now, it should fail.
1233 
1234  // Unlock the lock in the child process
1235  BOOST_CHECK_EQUAL(write(fd[1], &UnlockCommand, 1), 1);
1236  BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1238 
1239  // When we try to probe the lock now, it should succeed.
1241 
1242  // Re-lock the lock in the child process, then wait for it to exit, check
1243  // successful return. After that, we check that exiting the process
1244  // has released the lock as we would expect by probing it.
1245  int processstatus;
1246  BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1247  // The following line invokes the ~CNetCleanup dtor without
1248  // a paired SetupNetworking call. This is acceptable as long as
1249  // ~CNetCleanup is a no-op for non-Windows platforms.
1250  BOOST_CHECK_EQUAL(write(fd[1], &ExitCommand, 1), 1);
1251  BOOST_CHECK_EQUAL(waitpid(pid, &processstatus, 0), pid);
1252  BOOST_CHECK_EQUAL(processstatus, 0);
1254 
1255  // Restore SIGCHLD
1256  signal(SIGCHLD, old_handler);
1257  BOOST_CHECK_EQUAL(close(fd[1]), 0); // Close our side of the socketpair
1258 #endif
1259  // Clean up
1261  fs::remove_all(dirname);
1262 }
1263 
1265 {
1266  BOOST_CHECK_EQUAL(ToLower('@'), '@');
1267  BOOST_CHECK_EQUAL(ToLower('A'), 'a');
1268  BOOST_CHECK_EQUAL(ToLower('Z'), 'z');
1269  BOOST_CHECK_EQUAL(ToLower('['), '[');
1270  BOOST_CHECK_EQUAL(ToLower(0), 0);
1271  BOOST_CHECK_EQUAL(ToLower('\xff'), '\xff');
1272 
1273  BOOST_CHECK_EQUAL(ToLower(""), "");
1274  BOOST_CHECK_EQUAL(ToLower("#HODL"), "#hodl");
1275  BOOST_CHECK_EQUAL(ToLower("\x00\xfe\xff"), "\x00\xfe\xff");
1276 }
1277 
1279 {
1280  BOOST_CHECK_EQUAL(ToUpper('`'), '`');
1281  BOOST_CHECK_EQUAL(ToUpper('a'), 'A');
1282  BOOST_CHECK_EQUAL(ToUpper('z'), 'Z');
1283  BOOST_CHECK_EQUAL(ToUpper('{'), '{');
1284  BOOST_CHECK_EQUAL(ToUpper(0), 0);
1285  BOOST_CHECK_EQUAL(ToUpper('\xff'), '\xff');
1286 
1287  BOOST_CHECK_EQUAL(ToUpper(""), "");
1288  BOOST_CHECK_EQUAL(ToUpper("#hodl"), "#HODL");
1289  BOOST_CHECK_EQUAL(ToUpper("\x00\xfe\xff"), "\x00\xfe\xff");
1290 }
1291 
1292 BOOST_AUTO_TEST_CASE(test_Capitalize)
1293 {
1294  BOOST_CHECK_EQUAL(Capitalize(""), "");
1295  BOOST_CHECK_EQUAL(Capitalize("bitcoin"), "Bitcoin");
1296  BOOST_CHECK_EQUAL(Capitalize("\x00\xfe\xff"), "\x00\xfe\xff");
1297 }
1298 
1299 static std::string SpanToStr(const Span<const char>& span)
1300 {
1301  return std::string(span.begin(), span.end());
1302 }
1303 
1304 BOOST_AUTO_TEST_CASE(test_script_parsing)
1305 {
1306  using namespace script;
1307  std::string input;
1308  Span<const char> sp;
1309  bool success;
1310 
1311  // Const(...): parse a constant, update span to skip it if successful
1312  input = "MilkToastHoney";
1313  sp = input;
1314  success = Const("", sp); // empty
1315  BOOST_CHECK(success);
1316  BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
1317 
1318  success = Const("Milk", sp);
1319  BOOST_CHECK(success);
1320  BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
1321 
1322  success = Const("Bread", sp);
1323  BOOST_CHECK(!success);
1324 
1325  success = Const("Toast", sp);
1326  BOOST_CHECK(success);
1327  BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
1328 
1329  success = Const("Honeybadger", sp);
1330  BOOST_CHECK(!success);
1331 
1332  success = Const("Honey", sp);
1333  BOOST_CHECK(success);
1334  BOOST_CHECK_EQUAL(SpanToStr(sp), "");
1335 
1336  // Func(...): parse a function call, update span to argument if successful
1337  input = "Foo(Bar(xy,z()))";
1338  sp = input;
1339 
1340  success = Func("FooBar", sp);
1341  BOOST_CHECK(!success);
1342 
1343  success = Func("Foo(", sp);
1344  BOOST_CHECK(!success);
1345 
1346  success = Func("Foo", sp);
1347  BOOST_CHECK(success);
1348  BOOST_CHECK_EQUAL(SpanToStr(sp), "Bar(xy,z())");
1349 
1350  success = Func("Bar", sp);
1351  BOOST_CHECK(success);
1352  BOOST_CHECK_EQUAL(SpanToStr(sp), "xy,z()");
1353 
1354  success = Func("xy", sp);
1355  BOOST_CHECK(!success);
1356 
1357  // Expr(...): return expression that span begins with, update span to skip it
1358  Span<const char> result;
1359 
1360  input = "(n*(n-1))/2";
1361  sp = input;
1362  result = Expr(sp);
1363  BOOST_CHECK_EQUAL(SpanToStr(result), "(n*(n-1))/2");
1364  BOOST_CHECK_EQUAL(SpanToStr(sp), "");
1365 
1366  input = "foo,bar";
1367  sp = input;
1368  result = Expr(sp);
1369  BOOST_CHECK_EQUAL(SpanToStr(result), "foo");
1370  BOOST_CHECK_EQUAL(SpanToStr(sp), ",bar");
1371 
1372  input = "(aaaaa,bbbbb()),c";
1373  sp = input;
1374  result = Expr(sp);
1375  BOOST_CHECK_EQUAL(SpanToStr(result), "(aaaaa,bbbbb())");
1376  BOOST_CHECK_EQUAL(SpanToStr(sp), ",c");
1377 
1378  input = "xyz)foo";
1379  sp = input;
1380  result = Expr(sp);
1381  BOOST_CHECK_EQUAL(SpanToStr(result), "xyz");
1382  BOOST_CHECK_EQUAL(SpanToStr(sp), ")foo");
1383 
1384  input = "((a),(b),(c)),xxx";
1385  sp = input;
1386  result = Expr(sp);
1387  BOOST_CHECK_EQUAL(SpanToStr(result), "((a),(b),(c))");
1388  BOOST_CHECK_EQUAL(SpanToStr(sp), ",xxx");
1389 
1390  // Split(...): split a string on every instance of sep, return vector
1391  std::vector<Span<const char>> results;
1392 
1393  input = "xxx";
1394  results = Split(input, 'x');
1395  BOOST_CHECK_EQUAL(results.size(), 4U);
1396  BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
1397  BOOST_CHECK_EQUAL(SpanToStr(results[1]), "");
1398  BOOST_CHECK_EQUAL(SpanToStr(results[2]), "");
1399  BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
1400 
1401  input = "one#two#three";
1402  results = Split(input, '-');
1403  BOOST_CHECK_EQUAL(results.size(), 1U);
1404  BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one#two#three");
1405 
1406  input = "one#two#three";
1407  results = Split(input, '#');
1408  BOOST_CHECK_EQUAL(results.size(), 3U);
1409  BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one");
1410  BOOST_CHECK_EQUAL(SpanToStr(results[1]), "two");
1411  BOOST_CHECK_EQUAL(SpanToStr(results[2]), "three");
1412 
1413  input = "*foo*bar*";
1414  results = Split(input, '*');
1415  BOOST_CHECK_EQUAL(results.size(), 4U);
1416  BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
1417  BOOST_CHECK_EQUAL(SpanToStr(results[1]), "foo");
1418  BOOST_CHECK_EQUAL(SpanToStr(results[2]), "bar");
1419  BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
1420 }
1421 
1422 BOOST_AUTO_TEST_CASE(test_SplitString)
1423 {
1424  // Empty string.
1425  {
1426  std::vector<std::string> result = SplitString("", '-');
1427  BOOST_CHECK_EQUAL(result.size(), 1);
1428  BOOST_CHECK_EQUAL(result[0], "");
1429  }
1430 
1431  // Empty items.
1432  {
1433  std::vector<std::string> result = SplitString("-", '-');
1434  BOOST_CHECK_EQUAL(result.size(), 2);
1435  BOOST_CHECK_EQUAL(result[0], "");
1436  BOOST_CHECK_EQUAL(result[1], "");
1437  }
1438 
1439  // More empty items.
1440  {
1441  std::vector<std::string> result = SplitString("--", '-');
1442  BOOST_CHECK_EQUAL(result.size(), 3);
1443  BOOST_CHECK_EQUAL(result[0], "");
1444  BOOST_CHECK_EQUAL(result[1], "");
1445  BOOST_CHECK_EQUAL(result[2], "");
1446  }
1447 
1448  // Separator is not present.
1449  {
1450  std::vector<std::string> result = SplitString("abc", '-');
1451  BOOST_CHECK_EQUAL(result.size(), 1);
1452  BOOST_CHECK_EQUAL(result[0], "abc");
1453  }
1454 
1455  // Basic behavior.
1456  {
1457  std::vector<std::string> result = SplitString("a-b", '-');
1458  BOOST_CHECK_EQUAL(result.size(), 2);
1459  BOOST_CHECK_EQUAL(result[0], "a");
1460  BOOST_CHECK_EQUAL(result[1], "b");
1461  }
1462 
1463  // Case-sensitivity of the separator.
1464  {
1465  std::vector<std::string> result = SplitString("AAA", 'a');
1466  BOOST_CHECK_EQUAL(result.size(), 1);
1467  BOOST_CHECK_EQUAL(result[0], "AAA");
1468  }
1469 
1470  // multiple split characters
1471  {
1472  using V = std::vector<std::string>;
1473  BOOST_TEST(SplitString("a,b.c:d;e", ",;") == V({"a", "b.c:d", "e"}));
1474  BOOST_TEST(SplitString("a,b.c:d;e", ",;:.") == V({"a", "b", "c", "d", "e"}));
1475  BOOST_TEST(SplitString("a,b.c:d;e", "") == V({"a,b.c:d;e"}));
1476  BOOST_TEST(SplitString("aaa", "bcdefg") == V({"aaa"}));
1477  BOOST_TEST(SplitString("x\0a,b"s, "\0"s) == V({"x", "a,b"}));
1478  BOOST_TEST(SplitString("x\0a,b"s, '\0') == V({"x", "a,b"}));
1479  BOOST_TEST(SplitString("x\0a,b"s, "\0,"s) == V({"x", "a", "b"}));
1480  BOOST_TEST(SplitString("abcdefg", "bcd") == V({"a", "", "", "efg"}));
1481  }
1482 }
1483 
1484 BOOST_AUTO_TEST_CASE(test_LogEscapeMessage)
1485 {
1486  // ASCII and UTF-8 must pass through unaltered.
1487  BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Valid log message貓"), "Valid log message貓");
1488  // Newlines must pass through unaltered.
1489  BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Message\n with newlines\n"), "Message\n with newlines\n");
1490  // Other control characters are escaped in C syntax.
1491  BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("\x01\x7f Corrupted log message\x0d"), R"(\x01\x7f Corrupted log message\x0d)");
1492  // Embedded NULL characters are escaped too.
1493  const std::string NUL("O\x00O", 3);
1494  BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage(NUL), R"(O\x00O)");
1495 }
1496 
1497 namespace {
1498 
1499 struct Tracker
1500 {
1502  const Tracker* origin;
1504  int copies{0};
1505 
1506  Tracker() noexcept : origin(this) {}
1507  Tracker(const Tracker& t) noexcept : origin(t.origin), copies(t.copies + 1) {}
1508  Tracker(Tracker&& t) noexcept : origin(t.origin), copies(t.copies) {}
1509  Tracker& operator=(const Tracker& t) noexcept
1510  {
1511  origin = t.origin;
1512  copies = t.copies + 1;
1513  return *this;
1514  }
1515 };
1516 
1517 }
1518 
1519 BOOST_AUTO_TEST_CASE(test_tracked_vector)
1520 {
1521  Tracker t1;
1522  Tracker t2;
1523  Tracker t3;
1524 
1525  BOOST_CHECK(t1.origin == &t1);
1526  BOOST_CHECK(t2.origin == &t2);
1527  BOOST_CHECK(t3.origin == &t3);
1528 
1529  auto v1 = Vector(t1);
1530  BOOST_CHECK_EQUAL(v1.size(), 1U);
1531  BOOST_CHECK(v1[0].origin == &t1);
1532  BOOST_CHECK_EQUAL(v1[0].copies, 1);
1533 
1534  auto v2 = Vector(std::move(t2));
1535  BOOST_CHECK_EQUAL(v2.size(), 1U);
1536  BOOST_CHECK(v2[0].origin == &t2); // NOLINT(*-use-after-move)
1537  BOOST_CHECK_EQUAL(v2[0].copies, 0);
1538 
1539  auto v3 = Vector(t1, std::move(t2));
1540  BOOST_CHECK_EQUAL(v3.size(), 2U);
1541  BOOST_CHECK(v3[0].origin == &t1);
1542  BOOST_CHECK(v3[1].origin == &t2); // NOLINT(*-use-after-move)
1543  BOOST_CHECK_EQUAL(v3[0].copies, 1);
1544  BOOST_CHECK_EQUAL(v3[1].copies, 0);
1545 
1546  auto v4 = Vector(std::move(v3[0]), v3[1], std::move(t3));
1547  BOOST_CHECK_EQUAL(v4.size(), 3U);
1548  BOOST_CHECK(v4[0].origin == &t1);
1549  BOOST_CHECK(v4[1].origin == &t2);
1550  BOOST_CHECK(v4[2].origin == &t3); // NOLINT(*-use-after-move)
1551  BOOST_CHECK_EQUAL(v4[0].copies, 1);
1552  BOOST_CHECK_EQUAL(v4[1].copies, 1);
1553  BOOST_CHECK_EQUAL(v4[2].copies, 0);
1554 
1555  auto v5 = Cat(v1, v4);
1556  BOOST_CHECK_EQUAL(v5.size(), 4U);
1557  BOOST_CHECK(v5[0].origin == &t1);
1558  BOOST_CHECK(v5[1].origin == &t1);
1559  BOOST_CHECK(v5[2].origin == &t2);
1560  BOOST_CHECK(v5[3].origin == &t3);
1561  BOOST_CHECK_EQUAL(v5[0].copies, 2);
1562  BOOST_CHECK_EQUAL(v5[1].copies, 2);
1563  BOOST_CHECK_EQUAL(v5[2].copies, 2);
1564  BOOST_CHECK_EQUAL(v5[3].copies, 1);
1565 
1566  auto v6 = Cat(std::move(v1), v3);
1567  BOOST_CHECK_EQUAL(v6.size(), 3U);
1568  BOOST_CHECK(v6[0].origin == &t1);
1569  BOOST_CHECK(v6[1].origin == &t1);
1570  BOOST_CHECK(v6[2].origin == &t2);
1571  BOOST_CHECK_EQUAL(v6[0].copies, 1);
1572  BOOST_CHECK_EQUAL(v6[1].copies, 2);
1573  BOOST_CHECK_EQUAL(v6[2].copies, 1);
1574 
1575  auto v7 = Cat(v2, std::move(v4));
1576  BOOST_CHECK_EQUAL(v7.size(), 4U);
1577  BOOST_CHECK(v7[0].origin == &t2);
1578  BOOST_CHECK(v7[1].origin == &t1);
1579  BOOST_CHECK(v7[2].origin == &t2);
1580  BOOST_CHECK(v7[3].origin == &t3);
1581  BOOST_CHECK_EQUAL(v7[0].copies, 1);
1582  BOOST_CHECK_EQUAL(v7[1].copies, 1);
1583  BOOST_CHECK_EQUAL(v7[2].copies, 1);
1584  BOOST_CHECK_EQUAL(v7[3].copies, 0);
1585 
1586  auto v8 = Cat(std::move(v2), std::move(v3));
1587  BOOST_CHECK_EQUAL(v8.size(), 3U);
1588  BOOST_CHECK(v8[0].origin == &t2);
1589  BOOST_CHECK(v8[1].origin == &t1);
1590  BOOST_CHECK(v8[2].origin == &t2);
1591  BOOST_CHECK_EQUAL(v8[0].copies, 0);
1592  BOOST_CHECK_EQUAL(v8[1].copies, 1);
1593  BOOST_CHECK_EQUAL(v8[2].copies, 0);
1594 }
1595 
1597 {
1598  const std::array<unsigned char, 32> privkey_bytes = {
1599  // just some random data
1600  // derived address from this private key: 15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs
1601  0xD9, 0x7F, 0x51, 0x08, 0xF1, 0x1C, 0xDA, 0x6E,
1602  0xEE, 0xBA, 0xAA, 0x42, 0x0F, 0xEF, 0x07, 0x26,
1603  0xB1, 0xF8, 0x98, 0x06, 0x0B, 0x98, 0x48, 0x9F,
1604  0xA3, 0x09, 0x84, 0x63, 0xC0, 0x03, 0x28, 0x66
1605  };
1606 
1607  const std::string message = "Trust no one";
1608 
1609  const std::string expected_signature =
1610  "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=";
1611 
1612  CKey privkey;
1613  std::string generated_signature;
1614 
1615  BOOST_REQUIRE_MESSAGE(!privkey.IsValid(),
1616  "Confirm the private key is invalid");
1617 
1618  BOOST_CHECK_MESSAGE(!MessageSign(privkey, message, generated_signature),
1619  "Sign with an invalid private key");
1620 
1621  privkey.Set(privkey_bytes.begin(), privkey_bytes.end(), true);
1622 
1623  BOOST_REQUIRE_MESSAGE(privkey.IsValid(),
1624  "Confirm the private key is valid");
1625 
1626  BOOST_CHECK_MESSAGE(MessageSign(privkey, message, generated_signature),
1627  "Sign with a valid private key");
1628 
1629  BOOST_CHECK_EQUAL(expected_signature, generated_signature);
1630 }
1631 
1632 BOOST_AUTO_TEST_CASE(message_verify)
1633 {
1635  MessageVerify(
1636  "invalid address",
1637  "signature should be irrelevant",
1638  "message too"),
1640 
1642  MessageVerify(
1643  "3B5fQsEXEaV8v6U3ejYc8XaKXAkyQj2MjV",
1644  "signature should be irrelevant",
1645  "message too"),
1647 
1649  MessageVerify(
1650  "1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
1651  "invalid signature, not in base64 encoding",
1652  "message should be irrelevant"),
1654 
1656  MessageVerify(
1657  "1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
1658  "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1659  "message should be irrelevant"),
1661 
1663  MessageVerify(
1664  "15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
1665  "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
1666  "I never signed this"),
1668 
1670  MessageVerify(
1671  "15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
1672  "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
1673  "Trust no one"),
1675 
1677  MessageVerify(
1678  "11canuhp9X2NocwCq7xNrQYTmUgZAnLK3",
1679  "IIcaIENoYW5jZWxsb3Igb24gYnJpbmsgb2Ygc2Vjb25kIGJhaWxvdXQgZm9yIGJhbmtzIAaHRtbCeDZINyavx14=",
1680  "Trust me"),
1682 }
1683 
1685 {
1686  const std::string unsigned_tx = "...";
1687  const std::string prefixed_message =
1688  std::string(1, (char)MESSAGE_MAGIC.length()) +
1689  MESSAGE_MAGIC +
1690  std::string(1, (char)unsigned_tx.length()) +
1691  unsigned_tx;
1692 
1693  const uint256 signature_hash = Hash(unsigned_tx);
1694  const uint256 message_hash1 = Hash(prefixed_message);
1695  const uint256 message_hash2 = MessageHash(unsigned_tx);
1696 
1697  BOOST_CHECK_EQUAL(message_hash1, message_hash2);
1698  BOOST_CHECK_NE(message_hash1, signature_hash);
1699 }
1700 
1701 BOOST_AUTO_TEST_CASE(remove_prefix)
1702 {
1703  BOOST_CHECK_EQUAL(RemovePrefix("./common/system.h", "./"), "common/system.h");
1704  BOOST_CHECK_EQUAL(RemovePrefixView("foo", "foo"), "");
1705  BOOST_CHECK_EQUAL(RemovePrefix("foo", "fo"), "o");
1706  BOOST_CHECK_EQUAL(RemovePrefixView("foo", "f"), "oo");
1707  BOOST_CHECK_EQUAL(RemovePrefix("foo", ""), "foo");
1708  BOOST_CHECK_EQUAL(RemovePrefixView("fo", "foo"), "fo");
1709  BOOST_CHECK_EQUAL(RemovePrefix("f", "foo"), "f");
1710  BOOST_CHECK_EQUAL(RemovePrefixView("", "foo"), "");
1711  BOOST_CHECK_EQUAL(RemovePrefix("", ""), "");
1712 }
1713 
1714 BOOST_AUTO_TEST_CASE(util_ParseByteUnits)
1715 {
1716  auto noop = ByteUnit::NOOP;
1717 
1718  // no multiplier
1719  BOOST_CHECK_EQUAL(ParseByteUnits("1", noop).value(), 1);
1720  BOOST_CHECK_EQUAL(ParseByteUnits("0", noop).value(), 0);
1721 
1722  BOOST_CHECK_EQUAL(ParseByteUnits("1k", noop).value(), 1000ULL);
1723  BOOST_CHECK_EQUAL(ParseByteUnits("1K", noop).value(), 1ULL << 10);
1724 
1725  BOOST_CHECK_EQUAL(ParseByteUnits("2m", noop).value(), 2'000'000ULL);
1726  BOOST_CHECK_EQUAL(ParseByteUnits("2M", noop).value(), 2ULL << 20);
1727 
1728  BOOST_CHECK_EQUAL(ParseByteUnits("3g", noop).value(), 3'000'000'000ULL);
1729  BOOST_CHECK_EQUAL(ParseByteUnits("3G", noop).value(), 3ULL << 30);
1730 
1731  BOOST_CHECK_EQUAL(ParseByteUnits("4t", noop).value(), 4'000'000'000'000ULL);
1732  BOOST_CHECK_EQUAL(ParseByteUnits("4T", noop).value(), 4ULL << 40);
1733 
1734  // check default multiplier
1735  BOOST_CHECK_EQUAL(ParseByteUnits("5", ByteUnit::K).value(), 5ULL << 10);
1736 
1737  // NaN
1738  BOOST_CHECK(!ParseByteUnits("", noop));
1739  BOOST_CHECK(!ParseByteUnits("foo", noop));
1740 
1741  // whitespace
1742  BOOST_CHECK(!ParseByteUnits("123m ", noop));
1743  BOOST_CHECK(!ParseByteUnits(" 123m", noop));
1744 
1745  // no +-
1746  BOOST_CHECK(!ParseByteUnits("-123m", noop));
1747  BOOST_CHECK(!ParseByteUnits("+123m", noop));
1748 
1749  // zero padding
1750  BOOST_CHECK_EQUAL(ParseByteUnits("020M", noop).value(), 20ULL << 20);
1751 
1752  // fractions not allowed
1753  BOOST_CHECK(!ParseByteUnits("0.5T", noop));
1754 
1755  // overflow
1756  BOOST_CHECK(!ParseByteUnits("18446744073709551615g", noop));
1757 
1758  // invalid unit
1759  BOOST_CHECK(!ParseByteUnits("1x", noop));
1760 }
1761 
1762 BOOST_AUTO_TEST_CASE(util_ReadBinaryFile)
1763 {
1764  fs::path tmpfolder = m_args.GetDataDirBase();
1765  fs::path tmpfile = tmpfolder / "read_binary.dat";
1766  std::string expected_text;
1767  for (int i = 0; i < 30; i++) {
1768  expected_text += "0123456789";
1769  }
1770  {
1771  std::ofstream file{tmpfile};
1772  file << expected_text;
1773  }
1774  {
1775  // read all contents in file
1776  auto [valid, text] = ReadBinaryFile(tmpfile);
1777  BOOST_CHECK(valid);
1778  BOOST_CHECK_EQUAL(text, expected_text);
1779  }
1780  {
1781  // read half contents in file
1782  auto [valid, text] = ReadBinaryFile(tmpfile, expected_text.size() / 2);
1783  BOOST_CHECK(valid);
1784  BOOST_CHECK_EQUAL(text, expected_text.substr(0, expected_text.size() / 2));
1785  }
1786  {
1787  // read from non-existent file
1788  fs::path invalid_file = tmpfolder / "invalid_binary.dat";
1789  auto [valid, text] = ReadBinaryFile(invalid_file);
1790  BOOST_CHECK(!valid);
1791  BOOST_CHECK(text.empty());
1792  }
1793 }
1794 
1795 BOOST_AUTO_TEST_CASE(util_WriteBinaryFile)
1796 {
1797  fs::path tmpfolder = m_args.GetDataDirBase();
1798  fs::path tmpfile = tmpfolder / "write_binary.dat";
1799  std::string expected_text = "bitcoin";
1800  auto valid = WriteBinaryFile(tmpfile, expected_text);
1801  std::string actual_text;
1802  std::ifstream file{tmpfile};
1803  file >> actual_text;
1804  BOOST_CHECK(valid);
1805  BOOST_CHECK_EQUAL(actual_text, expected_text);
1806 }
1807 
1808 BOOST_AUTO_TEST_CASE(clearshrink_test)
1809 {
1810  {
1811  std::vector<uint8_t> v = {1, 2, 3};
1812  ClearShrink(v);
1813  BOOST_CHECK_EQUAL(v.size(), 0);
1814  BOOST_CHECK_EQUAL(v.capacity(), 0);
1815  }
1816 
1817  {
1818  std::vector<bool> v = {false, true, false, false, true, true};
1819  ClearShrink(v);
1820  BOOST_CHECK_EQUAL(v.size(), 0);
1821  BOOST_CHECK_EQUAL(v.capacity(), 0);
1822  }
1823 
1824  {
1825  std::deque<int> v = {1, 3, 3, 7};
1826  ClearShrink(v);
1827  BOOST_CHECK_EQUAL(v.size(), 0);
1828  // std::deque has no capacity() we can observe.
1829  }
1830 }
1831 
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
#define Assert(val)
Identity function.
Definition: check.h:77
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
An encapsulated private key.
Definition: key.h:33
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:119
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:99
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:98
constexpr C * end() const noexcept
Definition: span.h:176
constexpr C * begin() const noexcept
Definition: span.h:175
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
256-bit opaque blob.
Definition: uint256.h:106
std::string FormatSubVersion(const std::string &name, int nClientVersion, const std::vector< std::string > &comments)
Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip...
uint256 MessageHash(const std::string &message)
Hashes a message for signing and verification in a manner that prevents inadvertently signing a trans...
Definition: signmessage.cpp:73
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
Definition: signmessage.cpp:57
const std::string MESSAGE_MAGIC
Text used to signify that a signed message follows and to prevent inadvertently signing a transaction...
Definition: signmessage.cpp:24
MessageVerificationResult MessageVerify(const std::string &address, const std::string &signature, const std::string &message)
Verify a signed message.
Definition: signmessage.cpp:26
BOOST_AUTO_TEST_SUITE_END()
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:86
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
#define T(expected, seed, data)
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 void pool cs
std::string FormatMoney(const CAmount n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:19
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:45
Definition: timer.h:19
std::string LogEscapeMessage(const std::string &str)
Belts and suspenders: make sure outgoing log messages don't contain potentially suspicious characters...
Definition: logging.cpp:313
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:190
bool Const(const std::string &str, Span< const char > &sp)
Parse a constant.
Definition: parsing.cpp:15
Span< const char > Expr(Span< const char > &sp)
Extract the expression that sp begins with.
Definition: parsing.cpp:33
bool Func(const std::string &str, Span< const char > &sp)
Parse a function call.
Definition: parsing.cpp:24
std::vector< T > Split(const Span< const char > &sp, std::string_view separators)
Split a string on any char found in separators, returning a vector.
Definition: string.h:30
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:69
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:59
LockResult
Definition: fs_helpers.h:39
std::string_view RemovePrefixView(std::string_view str, std::string_view prefix)
Definition: string.h:84
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:79
std::string RemovePrefix(std::string_view str, std::string_view prefix)
Definition: string.h:92
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition: string.h:107
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:11
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:52
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
std::optional< T > CheckedAdd(const T i, const T j) noexcept
Definition: overflow.h:24
T SaturatingAdd(const T i, const T j) noexcept
Definition: overflow.h:33
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize)
Read full contents of a file and return them in a std::string.
@ ERR_MALFORMED_SIGNATURE
The provided signature couldn't be parsed (maybe invalid base64).
@ ERR_INVALID_ADDRESS
The provided address is invalid.
@ ERR_ADDRESS_NO_KEY
The provided address is valid but does not refer to a public key.
@ ERR_NOT_SIGNED
The message was not signed with the private key of the provided address.
@ OK
The message verification was successful.
@ ERR_PUBKEY_NOT_RECOVERED
A public key could not be recovered from the provided signature and message.
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) unsigned char member types only.
Definition: span.h:304
Span< const std::byte > MakeByteSpan(V &&v) noexcept
Definition: span.h:277
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
Definition: span.h:282
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
Definition: strencodings.h:152
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
Definition: strencodings.h:246
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:66
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Definition: strencodings.h:31
Basic testing setup.
Definition: setup_common.h:54
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:21
#define LOCK(cs)
Definition: sync.h:257
#define TRY_LOCK(cs, name)
Definition: sync.h:261
@ ZEROS
Seed with a compile time constant of zeros.
static void SeedInsecureRand(SeedRand seed=SeedRand::SEED)
Definition: random.h:35
static uint32_t InsecureRand32()
Definition: random.h:44
static int count
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:17
int64_t GetTime()
Definition: time.cpp:44
std::string FormatISO8601Date(int64_t nTime)
Definition: time.cpp:55
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:32
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition: time.cpp:46
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
bool IsHexNumber(std::string_view str)
Return true if the string is a hex number, optionally prefixed with "0x".
bool ParseInt32(std::string_view str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
bool ParseUInt16(std::string_view str, uint16_t *out)
Convert decimal string to unsigned 16-bit integer with strict parse error feedback.
std::optional< uint64_t > ParseByteUnits(std::string_view str, ByteUnit default_multiplier)
Parse a string with suffix unit [k|K|m|M|g|G|t|T].
std::string ToUpper(std::string_view str)
Returns the uppercase equivalent of the given string.
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
bool ParseUInt8(std::string_view str, uint8_t *out)
Convert decimal string to unsigned 8-bit integer with strict parse error feedback.
bool ParseUInt64(std::string_view str, uint64_t *out)
Convert decimal string to unsigned 64-bit integer with strict parse error feedback.
bool IsHex(std::string_view str)
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 ParseUInt32(std::string_view str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
std::optional< std::vector< Byte > > TryParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
int64_t atoi64_legacy(const std::string &str)
Definition: util_tests.cpp:748
#define E
Definition: util_tests.cpp:499
static void TestOtherProcess(fs::path dirname, fs::path lockname, int fd)
#define B
Definition: util_tests.cpp:498
static constexpr char ExitCommand
static constexpr char UnlockCommand
static void TestAddMatrixOverflow()
Definition: util_tests.cpp:577
static void TestAddMatrix()
Definition: util_tests.cpp:597
BOOST_AUTO_TEST_CASE(util_check)
Definition: util_tests.cpp:91
static const unsigned char ParseHex_expected[65]
Definition: util_tests.cpp:139
static void RunToIntegralTests()
Definition: util_tests.cpp:658
static const std::string STRING_WITH_EMBEDDED_NULL_CHAR
Definition: util_tests.cpp:57
static constexpr char LockCommand
static std::string SpanToStr(const Span< const char > &span)
@ ResErrorWrite
@ ResUnlockSuccess
@ ResSuccess
@ ResErrorLock
assert(!tx.IsCoinBase())
std::vector< typename std::common_type< Args... >::type > Vector(Args &&... args)
Construct a vector with the specified elements.
Definition: vector.h:23
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:34
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition: vector.h:56