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