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