Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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>
7#include <compat/compat.h>
8#include <hash.h>
9#include <key.h>
10#include <script/parsing.h>
11#include <span.h>
12#include <sync.h>
13#include <test/util/common.h>
14#include <test/util/random.h>
16#include <test/util/time.h>
17#include <uint256.h>
18#include <univalue.h>
19#include <util/bitdeque.h>
20#include <util/byte_units.h>
21#include <util/fs.h>
22#include <util/fs_helpers.h>
23#include <util/moneystr.h>
24#include <util/overflow.h>
25#include <util/readwritefile.h>
26#include <util/strencodings.h>
27#include <util/string.h>
28#include <util/time.h>
29#include <util/tokenbucket.h>
30#include <util/vector.h>
31
32#include <array>
33#include <cmath>
34#include <cstdint>
35#include <cstring>
36#include <fstream>
37#include <limits>
38#include <map>
39#include <optional>
40#include <string>
41#include <thread>
42#include <type_traits>
43#include <utility>
44#include <vector>
45
46#include <sys/types.h>
47
48#ifndef WIN32
49#include <sys/wait.h>
50#endif
51
52#include <boost/test/unit_test.hpp>
53
54using namespace std::literals;
55using namespace util::hex_literals;
57using util::Join;
61using util::Split;
65
66static const std::string STRING_WITH_EMBEDDED_NULL_CHAR{"1"s "\0" "1"s};
67
69
70namespace {
71class NoCopyOrMove
72{
73public:
74 int i;
75 explicit NoCopyOrMove(int i) : i{i} { }
76
77 NoCopyOrMove() = delete;
78 NoCopyOrMove(const NoCopyOrMove&) = delete;
79 NoCopyOrMove(NoCopyOrMove&&) = delete;
80 NoCopyOrMove& operator=(const NoCopyOrMove&) = delete;
81 NoCopyOrMove& operator=(NoCopyOrMove&&) = delete;
82
83 operator bool() const { return i != 0; }
84
85 int get_ip1() { return i + 1; }
86 bool test()
87 {
88 // Check that Assume can be used within a lambda and still call methods
89 [&]() { Assume(get_ip1()); }();
90 return Assume(get_ip1() != 5);
91 }
92};
93} // namespace
94
96{
97 // Check that Assert can forward
98 const std::unique_ptr<int> p_two = Assert(std::make_unique<int>(2));
99 // Check that Assert works on lvalues and rvalues
100 const int two = *Assert(p_two);
101 Assert(two == 2);
102 Assert(true);
103 // Check that Assume can be used as unary expression
104 const bool result{Assume(two == 2)};
105 Assert(result);
106
107 // Check that Assert doesn't require copy/move
108 NoCopyOrMove x{9};
109 Assert(x).i += 3;
110 Assert(x).test();
111
112 // Check nested Asserts
113 BOOST_CHECK_EQUAL(Assert((Assert(x).test() ? 3 : 0)), 3);
114
115 // Check -Wdangling-gsl does not trigger when copying the int. (It would
116 // trigger on "const int&")
117 const int nine{*Assert(std::optional<int>{9})};
119}
120
122{
124
125 do {
126 LOCK(cs);
127 break;
128
129 BOOST_ERROR("break was swallowed!");
130 } while(0);
131
132 do {
134 if (lockTest) {
135 BOOST_CHECK(true); // Needed to suppress "Test case [...] did not check any assertions"
136 break;
137 }
138
139 BOOST_ERROR("break was swallowed!");
140 } while(0);
141}
142
143constexpr char HEX_PARSE_INPUT[] = "04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f";
145 0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7,
146 0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde,
147 0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12,
148 0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d,
149 0x5f
150};
151static_assert((sizeof(HEX_PARSE_INPUT) - 1) == 2 * sizeof(HEX_PARSE_OUTPUT));
153{
154 std::vector<unsigned char> result;
155
156 // Basic test vector
157 std::vector<unsigned char> expected(std::begin(HEX_PARSE_OUTPUT), std::end(HEX_PARSE_OUTPUT));
158 constexpr std::array<std::byte, 65> hex_literal_array{operator""_hex<util::detail::Hex(HEX_PARSE_INPUT)>()};
160 BOOST_CHECK_EQUAL_COLLECTIONS(hex_literal_span.begin(), hex_literal_span.end(), expected.begin(), expected.end());
161
162 const std::vector<std::byte> hex_literal_vector{operator""_hex_v<util::detail::Hex(HEX_PARSE_INPUT)>()};
164 BOOST_CHECK_EQUAL_COLLECTIONS(hex_literal_vec_span.begin(), hex_literal_vec_span.end(), expected.begin(), expected.end());
165
166 constexpr std::array<uint8_t, 65> hex_literal_array_uint8{operator""_hex_u8<util::detail::Hex(HEX_PARSE_INPUT)>()};
167 BOOST_CHECK_EQUAL_COLLECTIONS(hex_literal_array_uint8.begin(), hex_literal_array_uint8.end(), expected.begin(), expected.end());
168
170 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
171
172 result = ParseHex(HEX_PARSE_INPUT);
173 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
174
175 result = TryParseHex<uint8_t>(HEX_PARSE_INPUT).value();
176 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
177
178 // Spaces between bytes must be supported
179 expected = {0x12, 0x34, 0x56, 0x78};
180 result = ParseHex("12 34 56 78");
181 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
182 result = TryParseHex<uint8_t>("12 34 56 78").value();
183 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
184
185 // Leading space must be supported
186 expected = {0x89, 0x34, 0x56, 0x78};
187 result = ParseHex(" 89 34 56 78");
188 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
189 result = TryParseHex<uint8_t>(" 89 34 56 78").value();
190 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
191
192 // Mixed case and spaces are supported
193 expected = {0xff, 0xaa};
194 result = ParseHex(" Ff aA ");
195 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
196 result = TryParseHex<uint8_t>(" Ff aA ").value();
197 BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
198
199 // Empty string is supported
200 static_assert(""_hex.empty());
201 static_assert(""_hex_u8.empty());
202 BOOST_CHECK_EQUAL(""_hex_v.size(), 0);
203 BOOST_CHECK_EQUAL(""_hex_v_u8.size(), 0);
204 BOOST_CHECK_EQUAL(ParseHex("").size(), 0);
205 BOOST_CHECK_EQUAL(TryParseHex<uint8_t>("").value().size(), 0);
206
207 // Spaces between nibbles is treated as invalid
208 BOOST_CHECK_EQUAL(ParseHex("AAF F").size(), 0);
209 BOOST_CHECK(!TryParseHex("AAF F").has_value());
210
211 // Embedded null is treated as invalid
212 const std::string with_embedded_null{" 11 "s
213 " \0 "
214 " 22 "s};
218
219 // Non-hex is treated as invalid
220 BOOST_CHECK_EQUAL(ParseHex("1234 invalid 1234").size(), 0);
221 BOOST_CHECK(!TryParseHex("1234 invalid 1234").has_value());
222
223 // Truncated input is treated as invalid
224 BOOST_CHECK_EQUAL(ParseHex("12 3").size(), 0);
225 BOOST_CHECK(!TryParseHex("12 3").has_value());
226}
227
229{
230 BOOST_CHECK_EQUAL(ConstevalHexDigit('0'), 0);
231 BOOST_CHECK_EQUAL(ConstevalHexDigit('9'), 9);
232 BOOST_CHECK_EQUAL(ConstevalHexDigit('a'), 0xa);
233 BOOST_CHECK_EQUAL(ConstevalHexDigit('f'), 0xf);
234}
235
237{
239 BOOST_CHECK_EQUAL(HexStr(std::span{HEX_PARSE_OUTPUT}.last(0)), "");
240 BOOST_CHECK_EQUAL(HexStr(std::span{HEX_PARSE_OUTPUT}.first(0)), "");
241
242 {
243 constexpr std::string_view out_exp{"04678afdb0"};
244 constexpr std::span in_s{HEX_PARSE_OUTPUT, out_exp.size() / 2};
245 const std::span<const uint8_t> in_u{MakeUCharSpan(in_s)};
246 const std::span<const std::byte> in_b{MakeByteSpan(in_s)};
247
251 }
252
253 {
254 auto input = std::string();
255 for (size_t i=0; i<256; ++i) {
256 input.push_back(static_cast<char>(i));
257 }
258
259 auto hex = HexStr(input);
260 BOOST_TEST_REQUIRE(hex.size() == 512);
261 static constexpr auto hexmap = std::string_view("0123456789abcdef");
262 for (size_t i = 0; i < 256; ++i) {
263 auto upper = hexmap.find(hex[i * 2]);
264 auto lower = hexmap.find(hex[i * 2 + 1]);
265 BOOST_TEST_REQUIRE(upper != std::string_view::npos);
266 BOOST_TEST_REQUIRE(lower != std::string_view::npos);
267 BOOST_TEST_REQUIRE(i == upper*16 + lower);
268 }
269 }
270}
271
273{
274 std::array mut_arr{uint8_t{0xaa}, uint8_t{0xbb}};
276 mut_bytes[1] = std::byte{0x11};
277 BOOST_CHECK_EQUAL(mut_arr.at(0), 0xaa);
278 BOOST_CHECK_EQUAL(mut_arr.at(1), 0x11);
279}
280
282{
283 // Normal version
284 BOOST_CHECK_EQUAL(Join(std::vector<std::string>{}, ", "), "");
285 BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo"}, ", "), "foo");
286 BOOST_CHECK_EQUAL(Join(std::vector<std::string>{"foo", "bar"}, ", "), "foo, bar");
287
288 // Version with unary operator
289 const auto op_upper = [](const std::string& s) { return ToUpper(s); };
290 BOOST_CHECK_EQUAL(Join(std::list<std::string>{}, ", ", op_upper), "");
291 BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo"}, ", ", op_upper), "FOO");
292 BOOST_CHECK_EQUAL(Join(std::list<std::string>{"foo", "bar"}, ", ", op_upper), "FOO, BAR");
293}
294
296{
297 const std::string original("A test \"%s\" string '%s'.");
298 auto test_replaceall{[](std::string test, std::string_view search, std::string_view substitute, std::string_view expected) {
299 ReplaceAll(test, search, substitute);
300 BOOST_CHECK_EQUAL(test, expected);
301 }};
302
303 test_replaceall(original, "", "foo", original);
304 test_replaceall(original, "missing", "foo", original);
305 test_replaceall(original, original, "foo", "foo");
306 test_replaceall(original, "%s", "foo", "A test \"foo\" string 'foo'.");
307 test_replaceall(original, "\"", "foo", "A test foo%sfoo string '%s'.");
308 test_replaceall(original, "'", "foo", "A test \"%s\" string foo%sfoo.");
309 test_replaceall("a.b", ".", "x", "axb");
310 test_replaceall("%w and %w", "%w", "$&$`$'$1$$", "$&$`$'$1$$ and $&$`$'$1$$");
311 test_replaceall("x", "x", "xx", "xx");
312}
313
315{
316 BOOST_CHECK_EQUAL(TrimString(" foo bar "), "foo bar");
317 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");
318 BOOST_CHECK_EQUAL(TrimString("\t \n foo \n\tbar\t \n "), "foo \n\tbar");
319 BOOST_CHECK_EQUAL(TrimStringView("\t \n foo \n\tbar\t \n ", "fobar"), "\t \n foo \n\tbar\t \n ");
320 BOOST_CHECK_EQUAL(TrimString("foo bar"), "foo bar");
321 BOOST_CHECK_EQUAL(TrimStringView("foo bar", "fobar"), " ");
322 BOOST_CHECK_EQUAL(TrimString(std::string("\0 foo \0 ", 8)), std::string("\0 foo \0", 7));
323 BOOST_CHECK_EQUAL(TrimStringView(std::string(" foo ", 5)), std::string("foo", 3));
324 BOOST_CHECK_EQUAL(TrimString(std::string("\t\t\0\0\n\n", 6)), std::string("\0\0", 2));
325 BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6)), std::string("\x05\x04\x03\x02\x01\x00", 6));
326 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));
327 BOOST_CHECK_EQUAL(TrimStringView(std::string("\x05\x04\x03\x02\x01\x00", 6), std::string("\x05\x04\x03\x02\x01\x00", 6)), "");
328}
329
331{
332 BOOST_CHECK_EQUAL(ParseISO8601DateTime("1969-12-31T23:59:59Z").value(), -1);
333 BOOST_CHECK_EQUAL(ParseISO8601DateTime("1970-01-01T00:00:00Z").value(), 0);
334 BOOST_CHECK_EQUAL(ParseISO8601DateTime("1970-01-01T00:00:01Z").value(), 1);
335 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T00:00:01Z").value(), 946684801);
336 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2011-09-30T23:36:17Z").value(), 1317425777);
337 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2100-12-31T23:59:59Z").value(), 4133980799);
338 BOOST_CHECK_EQUAL(ParseISO8601DateTime("9999-12-31T23:59:59Z").value(), 253402300799);
339
340 // Accept edge-cases, where the time overflows. They are not produced by
341 // FormatISO8601DateTime, so this can be changed in the future, if needed.
342 // For now, keep compatibility with the previous implementation.
343 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T99:00:00Z").value(), 947041200);
344 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T00:99:00Z").value(), 946690740);
345 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T00:00:99Z").value(), 946684899);
346 BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T99:99:99Z").value(), 947047239);
347
348 // Reject date overflows.
349 BOOST_CHECK(!ParseISO8601DateTime("2000-99-01T00:00:00Z"));
350 BOOST_CHECK(!ParseISO8601DateTime("2000-01-99T00:00:00Z"));
351
352 // Reject out-of-range years
353 BOOST_CHECK(!ParseISO8601DateTime("32768-12-31T23:59:59Z"));
354 BOOST_CHECK(!ParseISO8601DateTime("32767-12-31T23:59:59Z"));
355 BOOST_CHECK(!ParseISO8601DateTime("32767-12-31T00:00:00Z"));
356 BOOST_CHECK(!ParseISO8601DateTime("999-12-31T00:00:00Z"));
357
358 // Reject invalid format
359 const std::string valid{"2000-01-01T00:00:01Z"};
360 BOOST_CHECK(ParseISO8601DateTime(valid).has_value());
361 for (auto mut{0U}; mut < valid.size(); ++mut) {
362 std::string invalid{valid};
363 invalid[mut] = 'a';
365 }
366}
367
369{
370 BOOST_CHECK_EQUAL(FormatISO8601DateTime(971890963199), "32767-12-31T23:59:59Z");
371 BOOST_CHECK_EQUAL(FormatISO8601DateTime(971890876800), "32767-12-31T00:00:00Z");
372
373 BOOST_CHECK_EQUAL(FormatISO8601DateTime(-1), "1969-12-31T23:59:59Z");
374 BOOST_CHECK_EQUAL(FormatISO8601DateTime(0), "1970-01-01T00:00:00Z");
375 BOOST_CHECK_EQUAL(FormatISO8601DateTime(1), "1970-01-01T00:00:01Z");
376 BOOST_CHECK_EQUAL(FormatISO8601DateTime(946684801), "2000-01-01T00:00:01Z");
377 BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z");
378 BOOST_CHECK_EQUAL(FormatISO8601DateTime(4133980799), "2100-12-31T23:59:59Z");
379 BOOST_CHECK_EQUAL(FormatISO8601DateTime(253402300799), "9999-12-31T23:59:59Z");
380}
381
383{
384 BOOST_CHECK_EQUAL(FormatISO8601Date(971890963199), "32767-12-31");
385 BOOST_CHECK_EQUAL(FormatISO8601Date(971890876800), "32767-12-31");
386
387 BOOST_CHECK_EQUAL(FormatISO8601Date(0), "1970-01-01");
388 BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30");
389}
390
391
393{
394 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(std::numeric_limits<int64_t>::max()), "");
395 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(253402300800), "");
396 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(253402300799), "Fri, 31 Dec 9999 23:59:59 GMT");
397 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(253402214400), "Fri, 31 Dec 9999 00:00:00 GMT");
398 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(1717429609), "Mon, 03 Jun 2024 15:46:49 GMT");
399 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(0), "Thu, 01 Jan 1970 00:00:00 GMT");
400 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(-1), "Wed, 31 Dec 1969 23:59:59 GMT");
401 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(-1717429609), "Sat, 31 Jul 1915 08:13:11 GMT");
402 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(-62167219200), "Sat, 01 Jan 0000 00:00:00 GMT");
403 BOOST_CHECK_EQUAL(FormatRFC1123DateTime(-62167219201), "");
404}
405
407{
408 BOOST_CHECK_EQUAL(FormatMoney(0), "0.00");
409 BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), "12345.6789");
411
412 BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), "100000000.00");
413 BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), "10000000.00");
414 BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), "1000000.00");
415 BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), "100000.00");
416 BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), "10000.00");
417 BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), "1000.00");
418 BOOST_CHECK_EQUAL(FormatMoney(COIN*100), "100.00");
419 BOOST_CHECK_EQUAL(FormatMoney(COIN*10), "10.00");
422 BOOST_CHECK_EQUAL(FormatMoney(COIN/100), "0.01");
423 BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), "0.001");
424 BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), "0.0001");
425 BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), "0.00001");
426 BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), "0.000001");
427 BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), "0.0000001");
428 BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), "0.00000001");
429
430 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max()), "92233720368.54775807");
431 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 1), "92233720368.54775806");
432 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 2), "92233720368.54775805");
433 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::max() - 3), "92233720368.54775804");
434 // ...
435 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 3), "-92233720368.54775805");
436 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 2), "-92233720368.54775806");
437 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min() + 1), "-92233720368.54775807");
438 BOOST_CHECK_EQUAL(FormatMoney(std::numeric_limits<CAmount>::min()), "-92233720368.54775808");
439}
440
442{
443 BOOST_CHECK_EQUAL(ParseMoney("0.0").value(), 0);
444 BOOST_CHECK_EQUAL(ParseMoney(".").value(), 0);
445 BOOST_CHECK_EQUAL(ParseMoney("0.").value(), 0);
446 BOOST_CHECK_EQUAL(ParseMoney(".0").value(), 0);
447 BOOST_CHECK_EQUAL(ParseMoney(".6789").value(), 6789'0000);
448 BOOST_CHECK_EQUAL(ParseMoney("12345.").value(), COIN * 12345);
449
450 BOOST_CHECK_EQUAL(ParseMoney("12345.6789").value(), (COIN/10000)*123456789);
451
452 BOOST_CHECK_EQUAL(ParseMoney("10000000.00").value(), COIN*10000000);
453 BOOST_CHECK_EQUAL(ParseMoney("1000000.00").value(), COIN*1000000);
454 BOOST_CHECK_EQUAL(ParseMoney("100000.00").value(), COIN*100000);
455 BOOST_CHECK_EQUAL(ParseMoney("10000.00").value(), COIN*10000);
456 BOOST_CHECK_EQUAL(ParseMoney("1000.00").value(), COIN*1000);
457 BOOST_CHECK_EQUAL(ParseMoney("100.00").value(), COIN*100);
458 BOOST_CHECK_EQUAL(ParseMoney("10.00").value(), COIN*10);
459 BOOST_CHECK_EQUAL(ParseMoney("1.00").value(), COIN);
460 BOOST_CHECK_EQUAL(ParseMoney("1").value(), COIN);
461 BOOST_CHECK_EQUAL(ParseMoney(" 1").value(), COIN);
462 BOOST_CHECK_EQUAL(ParseMoney("1 ").value(), COIN);
463 BOOST_CHECK_EQUAL(ParseMoney(" 1 ").value(), COIN);
464 BOOST_CHECK_EQUAL(ParseMoney("0.1").value(), COIN/10);
465 BOOST_CHECK_EQUAL(ParseMoney("0.01").value(), COIN/100);
466 BOOST_CHECK_EQUAL(ParseMoney("0.001").value(), COIN/1000);
467 BOOST_CHECK_EQUAL(ParseMoney("0.0001").value(), COIN/10000);
468 BOOST_CHECK_EQUAL(ParseMoney("0.00001").value(), COIN/100000);
469 BOOST_CHECK_EQUAL(ParseMoney("0.000001").value(), COIN/1000000);
470 BOOST_CHECK_EQUAL(ParseMoney("0.0000001").value(), COIN/10000000);
471 BOOST_CHECK_EQUAL(ParseMoney("0.00000001").value(), COIN/100000000);
472 BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001 ").value(), COIN/100000000);
473 BOOST_CHECK_EQUAL(ParseMoney("0.00000001 ").value(), COIN/100000000);
474 BOOST_CHECK_EQUAL(ParseMoney(" 0.00000001").value(), COIN/100000000);
475
476 // Parsing amount that cannot be represented should fail
477 BOOST_CHECK(!ParseMoney("100000000.00"));
478 BOOST_CHECK(!ParseMoney("0.000000001"));
479
480 // Parsing empty string should fail
482 BOOST_CHECK(!ParseMoney(" "));
483 BOOST_CHECK(!ParseMoney(" "));
484
485 // Parsing two numbers should fail
486 BOOST_CHECK(!ParseMoney(".."));
487 BOOST_CHECK(!ParseMoney("0..0"));
488 BOOST_CHECK(!ParseMoney("1 2"));
489 BOOST_CHECK(!ParseMoney(" 1 2 "));
490 BOOST_CHECK(!ParseMoney(" 1.2 3 "));
491 BOOST_CHECK(!ParseMoney(" 1 2.3 "));
492
493 // Embedded whitespace should fail
494 BOOST_CHECK(!ParseMoney(" -1 .2 "));
495 BOOST_CHECK(!ParseMoney(" 1 .2 "));
496 BOOST_CHECK(!ParseMoney(" +1 .2 "));
497
498 // Attempted 63 bit overflow should fail
499 BOOST_CHECK(!ParseMoney("92233720368.54775808"));
500
501 // Parsing negative amounts must fail
502 BOOST_CHECK(!ParseMoney("-1"));
503
504 // Parsing strings with embedded NUL characters should fail
505 BOOST_CHECK(!ParseMoney("\0-1"s));
507 BOOST_CHECK(!ParseMoney("1\0"s));
508}
509
511{
512 BOOST_CHECK(IsHex("00"));
513 BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
514 BOOST_CHECK(IsHex("ff"));
515 BOOST_CHECK(IsHex("FF"));
516
517 BOOST_CHECK(!IsHex(""));
518 BOOST_CHECK(!IsHex("0"));
519 BOOST_CHECK(!IsHex("a"));
520 BOOST_CHECK(!IsHex("eleven"));
521 BOOST_CHECK(!IsHex("00xx00"));
522 BOOST_CHECK(!IsHex("0x0000"));
523}
524
526{
527 SeedRandomForTest(SeedRand::ZEROS);
528 for (int mod=2;mod<11;mod++)
529 {
530 int mask = 1;
531 // Really rough binomial confidence approximation.
532 int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.);
533 //mask is 2^ceil(log2(mod))-1
534 while(mask<mod-1)mask=(mask<<1)+1;
535
536 int count = 0;
537 //How often does it get a zero from the uniform range [0,mod)?
538 for (int i = 0; i < 10000; i++) {
540 do{
541 rval=m_rng.rand32()&mask;
542 }while(rval>=(uint32_t)mod);
543 count += rval==0;
544 }
545 BOOST_CHECK(count<=10000/mod+err);
546 BOOST_CHECK(count>=10000/mod-err);
547 }
548}
549
551{
552 BOOST_CHECK(TimingResistantEqual(std::string(""), std::string("")));
553 BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("")));
554 BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc")));
555 BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa")));
556 BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a")));
557 BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc")));
558 BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba")));
559}
560
561/* Test strprintf formatting directives.
562 * Put a string before and after to ensure sanity of element sizes on stack. */
563#define B "check_prefix"
564#define E "check_postfix"
566{
567 int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */
568 uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */
569 BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E);
570 BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E);
571 BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E);
572
573 size_t st = 12345678; /* unsigned size_t test value */
574 ssize_t sst = -12345678; /* signed size_t test value */
575 BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E);
576 BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E);
577 BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E);
578
579 ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */
580 ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */
581 BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E);
582 BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E);
583 BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E);
584}
585#undef B
586#undef E
587
604
613
615{
616 BOOST_CHECK_EQUAL(IsDigit('0'), true);
617 BOOST_CHECK_EQUAL(IsDigit('1'), true);
618 BOOST_CHECK_EQUAL(IsDigit('8'), true);
619 BOOST_CHECK_EQUAL(IsDigit('9'), true);
620
621 BOOST_CHECK_EQUAL(IsDigit('0' - 1), false);
622 BOOST_CHECK_EQUAL(IsDigit('9' + 1), false);
623 BOOST_CHECK_EQUAL(IsDigit(0), false);
624 BOOST_CHECK_EQUAL(IsDigit(1), false);
625 BOOST_CHECK_EQUAL(IsDigit(8), false);
626 BOOST_CHECK_EQUAL(IsDigit(9), false);
627}
628
629/* Check for overflow */
630template <typename T>
632{
633 constexpr T MAXI{std::numeric_limits<T>::max()};
638
639 BOOST_CHECK_EQUAL(0, CheckedAdd(T{0}, T{0}).value());
640 BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{0}, MAXI).value());
641 BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{1}, MAXI - 1).value());
642 BOOST_CHECK_EQUAL(MAXI - 1, CheckedAdd(T{1}, MAXI - 2).value());
647}
648
649/* Check for overflow or underflow */
650template <typename T>
651static void TestAddMatrix()
652{
654 constexpr T MINI{std::numeric_limits<T>::min()};
655 constexpr T MAXI{std::numeric_limits<T>::max()};
660
661 BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{0}, MINI).value());
662 BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{-1}, MINI + 1).value());
663 BOOST_CHECK_EQUAL(-1, CheckedAdd(MINI, MAXI).value());
664 BOOST_CHECK_EQUAL(MINI + 1, CheckedAdd(T{-1}, MINI + 2).value());
667 BOOST_CHECK_EQUAL(MINI + 1, SaturatingAdd(T{-1}, MINI + 2));
669}
670
676
677template <typename T>
679{
684 BOOST_CHECK(!ToIntegral<T>("1.1"));
685 BOOST_CHECK(!ToIntegral<T>("1.9"));
686 BOOST_CHECK(!ToIntegral<T>("+01.9"));
689 BOOST_CHECK(!ToIntegral<T>(" -1"));
690 BOOST_CHECK(!ToIntegral<T>("-1 "));
691 BOOST_CHECK(!ToIntegral<T>(" -1 "));
693 BOOST_CHECK(!ToIntegral<T>(" +1"));
694 BOOST_CHECK(!ToIntegral<T>(" +1 "));
695 BOOST_CHECK(!ToIntegral<T>("+-1"));
696 BOOST_CHECK(!ToIntegral<T>("-+1"));
697 BOOST_CHECK(!ToIntegral<T>("++1"));
698 BOOST_CHECK(!ToIntegral<T>("--1"));
700 BOOST_CHECK(!ToIntegral<T>("aap"));
701 BOOST_CHECK(!ToIntegral<T>("0x1"));
702 BOOST_CHECK(!ToIntegral<T>("-32482348723847471234"));
703 BOOST_CHECK(!ToIntegral<T>("32482348723847471234"));
704}
705
707{
708 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("1234").value(), 1'234);
709 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("0").value(), 0);
710 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("01234").value(), 1'234);
711 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000001234").value(), 1'234);
712 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000001234").value(), -1'234);
713 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("00000000000000000000").value(), 0);
714 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-00000000000000000000").value(), 0);
715 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1234").value(), -1'234);
716 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-1").value(), -1);
717
726
727 BOOST_CHECK(!ToIntegral<int64_t>("-9223372036854775809"));
728 BOOST_CHECK_EQUAL(ToIntegral<int64_t>("-9223372036854775808").value(), -9'223'372'036'854'775'807LL - 1LL);
729 BOOST_CHECK_EQUAL(ToIntegral<int64_t>("9223372036854775807").value(), 9'223'372'036'854'775'807);
730 BOOST_CHECK(!ToIntegral<int64_t>("9223372036854775808"));
731
734 BOOST_CHECK_EQUAL(ToIntegral<uint64_t>("18446744073709551615").value(), 18'446'744'073'709'551'615ULL);
735 BOOST_CHECK(!ToIntegral<uint64_t>("18446744073709551616"));
736
737 BOOST_CHECK(!ToIntegral<int32_t>("-2147483649"));
738 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("-2147483648").value(), -2'147'483'648LL);
739 BOOST_CHECK_EQUAL(ToIntegral<int32_t>("2147483647").value(), 2'147'483'647);
740 BOOST_CHECK(!ToIntegral<int32_t>("2147483648"));
741
744 BOOST_CHECK_EQUAL(ToIntegral<uint32_t>("4294967295").value(), 4'294'967'295U);
745 BOOST_CHECK(!ToIntegral<uint32_t>("4294967296"));
746
748 BOOST_CHECK_EQUAL(ToIntegral<int16_t>("-32768").value(), -32'768);
749 BOOST_CHECK_EQUAL(ToIntegral<int16_t>("32767").value(), 32'767);
751
754 BOOST_CHECK_EQUAL(ToIntegral<uint16_t>("65535").value(), 65'535U);
756
758 BOOST_CHECK_EQUAL(ToIntegral<int8_t>("-128").value(), -128);
759 BOOST_CHECK_EQUAL(ToIntegral<int8_t>("127").value(), 127);
761
764 BOOST_CHECK_EQUAL(ToIntegral<uint8_t>("255").value(), 255U);
766}
767
768int64_t atoi64_legacy(const std::string& str)
769{
770 return strtoll(str.c_str(), nullptr, 10);
771}
772
774{
792
800 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-32482348723847471234"), -2'147'483'647 - 1);
801 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("32482348723847471234"), 2'147'483'647);
802
803 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775809"), -9'223'372'036'854'775'807LL - 1LL);
804 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("-9223372036854775808"), -9'223'372'036'854'775'807LL - 1LL);
805 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775807"), 9'223'372'036'854'775'807);
806 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int64_t>("9223372036854775808"), 9'223'372'036'854'775'807);
807
808 std::map<std::string, int64_t> atoi64_test_pairs = {
809 {"-9223372036854775809", std::numeric_limits<int64_t>::min()},
810 {"-9223372036854775808", -9'223'372'036'854'775'807LL - 1LL},
811 {"9223372036854775807", 9'223'372'036'854'775'807},
812 {"9223372036854775808", std::numeric_limits<int64_t>::max()},
813 {"+-", 0},
814 {"0x1", 0},
815 {"ox1", 0},
816 {"", 0},
817 };
818
819 for (const auto& pair : atoi64_test_pairs) {
821 }
822
823 // Ensure legacy compatibility with previous versions of Bitcoin Core's atoi64
824 for (const auto& pair : atoi64_test_pairs) {
826 }
827
830 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551615"), 18'446'744'073'709'551'615ULL);
831 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint64_t>("18446744073709551616"), 18'446'744'073'709'551'615ULL);
832
833 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483649"), -2'147'483'648LL);
834 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("-2147483648"), -2'147'483'648LL);
835 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483647"), 2'147'483'647);
836 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<int32_t>("2147483648"), 2'147'483'647);
837
840 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967295"), 4'294'967'295U);
841 BOOST_CHECK_EQUAL(LocaleIndependentAtoi<uint32_t>("4294967296"), 4'294'967'295U);
842
847
852
857
862}
863
865{
866 std::optional<uint64_t> n;
867 // Valid values
868 n = ToIntegral<uint64_t>("1234", 16);
869 BOOST_CHECK_EQUAL(*n, 0x1234);
870 n = ToIntegral<uint64_t>("a", 16);
871 BOOST_CHECK_EQUAL(*n, 0xA);
872 n = ToIntegral<uint64_t>("0000000a", 16);
873 BOOST_CHECK_EQUAL(*n, 0xA);
874 n = ToIntegral<uint64_t>("100", 16);
875 BOOST_CHECK_EQUAL(*n, 0x100);
876 n = ToIntegral<uint64_t>("DEADbeef", 16);
877 BOOST_CHECK_EQUAL(*n, 0xDEADbeef);
878 n = ToIntegral<uint64_t>("FfFfFfFf", 16);
879 BOOST_CHECK_EQUAL(*n, 0xFfFfFfFf);
880 n = ToIntegral<uint64_t>("123456789", 16);
881 BOOST_CHECK_EQUAL(*n, 0x123456789ULL);
882 n = ToIntegral<uint64_t>("0", 16);
883 BOOST_CHECK_EQUAL(*n, 0);
884 n = ToIntegral<uint64_t>("FfFfFfFfFfFfFfFf", 16);
885 BOOST_CHECK_EQUAL(*n, 0xFfFfFfFfFfFfFfFfULL);
887 // Invalid values
890 BOOST_CHECK(!ToIntegral<uint64_t>("10 00", 16));
892 BOOST_CHECK(!ToIntegral<uint64_t>("0xAB", 16));
893 BOOST_CHECK(!ToIntegral<uint64_t>("FfFfFfFfFfFfFfFf0", 16));
894}
895
897{
898 BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), "");
899 BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test");
900 BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), " test");
901 BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test");
902 BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest");
903 BOOST_CHECK_EQUAL(FormatParagraph("testerde test", 4, 0), "testerde\ntest");
904 BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test");
905
906 // Make sure we don't indent a fully-new line following a too-long line ending
907 BOOST_CHECK_EQUAL(FormatParagraph("test test\nabc", 4, 4), "test\n test\nabc");
908
909 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");
910
911 // Test wrap length is exact
912 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");
913 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");
914 // Indent should be included in length of lines
915 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");
916
917 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.");
918 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.");
919 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.");
920 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.");
921}
922
924{
925 std::vector<std::string> comments;
926 comments.emplace_back("comment1");
927 std::vector<std::string> comments2;
928 comments2.emplace_back("comment1");
929 comments2.push_back(SanitizeString("Comment2; .,_?@-; !\"#$%&'()*+/<=>[]\\^`{|}~", SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014
930 BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:9.99.0/"));
931 BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:9.99.0(comment1)/"));
932 BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:9.99.0(comment1; Comment2; .,_?@-; )/"));
933}
934
936{
937 int64_t amount = 0;
938 BOOST_CHECK(ParseFixedPoint("0", 8, &amount));
939 BOOST_CHECK_EQUAL(amount, 0LL);
940 BOOST_CHECK(ParseFixedPoint("1", 8, &amount));
941 BOOST_CHECK_EQUAL(amount, 100000000LL);
942 BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount));
943 BOOST_CHECK_EQUAL(amount, 0LL);
944 BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount));
945 BOOST_CHECK_EQUAL(amount, -10000000LL);
946 BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount));
947 BOOST_CHECK_EQUAL(amount, 110000000LL);
948 BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount));
949 BOOST_CHECK_EQUAL(amount, 110000000LL);
950 BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount));
951 BOOST_CHECK_EQUAL(amount, 1100000000LL);
952 BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount));
953 BOOST_CHECK_EQUAL(amount, 11000000LL);
954 BOOST_CHECK(ParseFixedPoint("1000", 8, &amount));
955 BOOST_CHECK_EQUAL(amount, 100000000000LL);
956 BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount));
957 BOOST_CHECK_EQUAL(amount, -100000000000LL);
958 BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount));
959 BOOST_CHECK_EQUAL(amount, 1LL);
960 BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount));
961 BOOST_CHECK_EQUAL(amount, 1LL);
962 BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount));
963 BOOST_CHECK_EQUAL(amount, -1LL);
964 BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount));
965 BOOST_CHECK_EQUAL(amount, 100000000000000001LL);
966 BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount));
967 BOOST_CHECK_EQUAL(amount, 999999999999999999LL);
968 BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount));
969 BOOST_CHECK_EQUAL(amount, -999999999999999999LL);
970
971 BOOST_CHECK(!ParseFixedPoint("", 8, &amount));
972 BOOST_CHECK(!ParseFixedPoint("-", 8, &amount));
973 BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount));
974 BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount));
975 BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount));
976 BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount));
977 BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount));
978 BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount));
979 BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount));
980 BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount));
981 BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount));
982 BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount));
983 BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount));
984 BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount));
985 BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount));
986 BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount));
987 BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount));
988 BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount));
989 BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount));
990 BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount));
991 BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount));
992 BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount));
993 BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount));
994 BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount));
995 BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount));
996 BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount));
997 BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount));
998
999 // Test with 3 decimal places for fee rates in sat/vB.
1000 BOOST_CHECK(ParseFixedPoint("0.001", 3, &amount));
1001 BOOST_CHECK_EQUAL(amount, CAmount{1});
1002 BOOST_CHECK(!ParseFixedPoint("0.0009", 3, &amount));
1003 BOOST_CHECK(!ParseFixedPoint("31.00100001", 3, &amount));
1004 BOOST_CHECK(!ParseFixedPoint("31.0011", 3, &amount));
1005 BOOST_CHECK(!ParseFixedPoint("31.99999999", 3, &amount));
1006 BOOST_CHECK(!ParseFixedPoint("31.999999999999999999999", 3, &amount));
1007}
1008
1009#ifndef WIN32 // Cannot do this test on WIN32 due to lack of fork()
1010static constexpr char LockCommand = 'L';
1011static constexpr char UnlockCommand = 'U';
1012static constexpr char ExitCommand = 'X';
1013enum : char {
1014 ResSuccess = 2, // Start with 2 to avoid accidental collision with common values 0 and 1
1018};
1019
1020[[noreturn]] static void TestOtherProcess(fs::path dirname, fs::path lockname, int fd)
1021{
1022 char ch;
1023 while (true) {
1024 int rv = read(fd, &ch, 1); // Wait for command
1025 assert(rv == 1);
1026 switch (ch) {
1027 case LockCommand:
1028 ch = [&] {
1029 switch (util::LockDirectory(dirname, lockname)) {
1033 } // no default case, so the compiler can warn about missing cases
1034 assert(false);
1035 }();
1036 rv = write(fd, &ch, 1);
1037 assert(rv == 1);
1038 break;
1039 case UnlockCommand:
1041 ch = ResUnlockSuccess; // Always succeeds
1042 rv = write(fd, &ch, 1);
1043 assert(rv == 1);
1044 break;
1045 case ExitCommand:
1046 close(fd);
1047 exit(0);
1048 default:
1049 assert(0);
1050 }
1051 }
1052}
1053#endif
1054
1056{
1057 fs::path dirname = m_args.GetDataDirBase() / "lock_dir";
1058 const fs::path lockname = ".lock";
1059#ifndef WIN32
1060 // Fork another process for testing before creating the lock, so that we
1061 // won't fork while holding the lock (which might be undefined, and is not
1062 // relevant as test case as that is avoided with -daemonize).
1063 int fd[2];
1065 pid_t pid = fork();
1066 if (!pid) {
1067 BOOST_CHECK_EQUAL(close(fd[1]), 0); // Child: close parent end
1068 TestOtherProcess(dirname, lockname, fd[0]);
1069 }
1070 BOOST_CHECK_EQUAL(close(fd[0]), 0); // Parent: close child end
1071
1072 char ch;
1073 // Lock on non-existent directory should fail
1074 BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1075 BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1077#endif
1078 // Lock on non-existent directory should fail
1080
1081 fs::create_directories(dirname);
1082
1083 // Probing lock on new directory should succeed
1085
1086 // Persistent lock on new directory should succeed
1088
1089 // Another lock on the directory from the same thread should succeed
1091
1092 // Another lock on the directory from a different thread within the same process should succeed
1094 std::thread thr([&] { threadresult = util::LockDirectory(dirname, lockname); });
1095 thr.join();
1097#ifndef WIN32
1098 // Try to acquire lock in child process while we're holding it, this should fail.
1099 BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1100 BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1102
1103 // Give up our lock
1105 // Probing lock from our side now should succeed, but not hold on to the lock.
1107
1108 // Try to acquire the lock in the child process, this should be successful.
1109 BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1110 BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1112
1113 // When we try to probe the lock now, it should fail.
1115
1116 // Unlock the lock in the child process
1117 BOOST_CHECK_EQUAL(write(fd[1], &UnlockCommand, 1), 1);
1118 BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
1120
1121 // When we try to probe the lock now, it should succeed.
1123
1124 // Re-lock the lock in the child process, then wait for it to exit, check
1125 // successful return. After that, we check that exiting the process
1126 // has released the lock as we would expect by probing it.
1127 int processstatus;
1128 BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
1129 // The following line invokes the ~CNetCleanup dtor without
1130 // a paired SetupNetworking call. This is acceptable as long as
1131 // ~CNetCleanup is a no-op for non-Windows platforms.
1132 BOOST_CHECK_EQUAL(write(fd[1], &ExitCommand, 1), 1);
1136
1137 BOOST_CHECK_EQUAL(close(fd[1]), 0); // Close our side of the socketpair
1138#endif
1139 // Clean up
1141 fs::remove(dirname / lockname);
1142 fs::remove(dirname);
1143}
1144
1146{
1147 BOOST_CHECK_EQUAL(ToLower('@'), '@');
1148 BOOST_CHECK_EQUAL(ToLower('A'), 'a');
1149 BOOST_CHECK_EQUAL(ToLower('Z'), 'z');
1150 BOOST_CHECK_EQUAL(ToLower('['), '[');
1152 BOOST_CHECK_EQUAL(ToLower('\xff'), '\xff');
1153
1154 BOOST_CHECK_EQUAL(ToLower(""), "");
1155 BOOST_CHECK_EQUAL(ToLower("#HODL"), "#hodl");
1156 BOOST_CHECK_EQUAL(ToLower("\x00\xfe\xff"sv), "\x00\xfe\xff"sv);
1157}
1158
1160{
1161 BOOST_CHECK_EQUAL(ToUpper('`'), '`');
1162 BOOST_CHECK_EQUAL(ToUpper('a'), 'A');
1163 BOOST_CHECK_EQUAL(ToUpper('z'), 'Z');
1164 BOOST_CHECK_EQUAL(ToUpper('{'), '{');
1166 BOOST_CHECK_EQUAL(ToUpper('\xff'), '\xff');
1167
1168 BOOST_CHECK_EQUAL(ToUpper(""), "");
1169 BOOST_CHECK_EQUAL(ToUpper("#hodl"), "#HODL");
1170 BOOST_CHECK_EQUAL(ToUpper("\x00\xfe\xff"sv), "\x00\xfe\xff"sv);
1171}
1172
1174{
1176 BOOST_CHECK_EQUAL(Capitalize("bitcoin"), "Bitcoin");
1177 BOOST_CHECK_EQUAL(Capitalize("\x00\xfe\xff"s), "\x00\xfe\xff"sv);
1178}
1179
1180static std::string SpanToStr(const std::span<const char>& span)
1181{
1182 return std::string(span.begin(), span.end());
1183}
1184
1186{
1187 using namespace script;
1188 std::string input;
1189 std::span<const char> sp;
1190 bool success;
1191
1192 // Const(...): parse a constant, update span to skip it if successful
1193 input = "MilkToastHoney";
1194 sp = input;
1195 success = Const("", sp); // empty
1196 BOOST_CHECK(success);
1197 BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
1198
1199 success = Const("Milk", sp, /*skip=*/false);
1200 BOOST_CHECK(success);
1201 BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
1202
1203 success = Const("Milk", sp);
1204 BOOST_CHECK(success);
1205 BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
1206
1207 success = Const("Bread", sp, /*skip=*/false);
1208 BOOST_CHECK(!success);
1209
1210 success = Const("Bread", sp);
1211 BOOST_CHECK(!success);
1212
1213 success = Const("Toast", sp, /*skip=*/false);
1214 BOOST_CHECK(success);
1215 BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
1216
1217 success = Const("Toast", sp);
1218 BOOST_CHECK(success);
1219 BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
1220
1221 success = Const("Honeybadger", sp);
1222 BOOST_CHECK(!success);
1223
1224 success = Const("Honey", sp, /*skip=*/false);
1225 BOOST_CHECK(success);
1226 BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
1227
1228 success = Const("Honey", sp);
1229 BOOST_CHECK(success);
1231 // Func(...): parse a function call, update span to argument if successful
1232 input = "Foo(Bar(xy,z()))";
1233 sp = input;
1234
1235 success = Func("FooBar", sp);
1236 BOOST_CHECK(!success);
1237
1238 success = Func("Foo(", sp);
1239 BOOST_CHECK(!success);
1240
1241 success = Func("Foo", sp);
1242 BOOST_CHECK(success);
1243 BOOST_CHECK_EQUAL(SpanToStr(sp), "Bar(xy,z())");
1244
1245 success = Func("Bar", sp);
1246 BOOST_CHECK(success);
1247 BOOST_CHECK_EQUAL(SpanToStr(sp), "xy,z()");
1248
1249 success = Func("xy", sp);
1250 BOOST_CHECK(!success);
1251
1252 // Expr(...): return expression that span begins with, update span to skip it
1253 std::span<const char> result;
1254
1255 input = "(n*(n-1))/2";
1256 sp = input;
1257 result = Expr(sp);
1258 BOOST_CHECK_EQUAL(SpanToStr(result), "(n*(n-1))/2");
1260
1261 input = "foo,bar";
1262 sp = input;
1263 result = Expr(sp);
1264 BOOST_CHECK_EQUAL(SpanToStr(result), "foo");
1265 BOOST_CHECK_EQUAL(SpanToStr(sp), ",bar");
1266
1267 input = "(aaaaa,bbbbb()),c";
1268 sp = input;
1269 result = Expr(sp);
1270 BOOST_CHECK_EQUAL(SpanToStr(result), "(aaaaa,bbbbb())");
1272
1273 input = "xyz)foo";
1274 sp = input;
1275 result = Expr(sp);
1276 BOOST_CHECK_EQUAL(SpanToStr(result), "xyz");
1277 BOOST_CHECK_EQUAL(SpanToStr(sp), ")foo");
1278
1279 input = "((a),(b),(c)),xxx";
1280 sp = input;
1281 result = Expr(sp);
1282 BOOST_CHECK_EQUAL(SpanToStr(result), "((a),(b),(c))");
1283 BOOST_CHECK_EQUAL(SpanToStr(sp), ",xxx");
1284
1285 // Split(...): split a string on every instance of sep, return vector
1286 std::vector<std::span<const char>> results;
1287
1288 input = "xxx";
1289 results = Split(input, 'x');
1290 BOOST_CHECK_EQUAL(results.size(), 4U);
1295
1296 input = "one#two#three";
1297 results = Split(input, '-');
1298 BOOST_CHECK_EQUAL(results.size(), 1U);
1299 BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one#two#three");
1300
1301 input = "one#two#three";
1302 results = Split(input, '#');
1303 BOOST_CHECK_EQUAL(results.size(), 3U);
1306 BOOST_CHECK_EQUAL(SpanToStr(results[2]), "three");
1307
1308 results = Split(input, '#', /*include_sep=*/true);
1309 BOOST_CHECK_EQUAL(results.size(), 3U);
1310 BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one#");
1311 BOOST_CHECK_EQUAL(SpanToStr(results[1]), "two#");
1312 BOOST_CHECK_EQUAL(SpanToStr(results[2]), "three");
1313
1314 input = "*foo*bar*";
1315 results = Split(input, '*');
1316 BOOST_CHECK_EQUAL(results.size(), 4U);
1321
1322 results = Split(input, '*', /*include_sep=*/true);
1323 BOOST_CHECK_EQUAL(results.size(), 4U);
1325 BOOST_CHECK_EQUAL(SpanToStr(results[1]), "foo*");
1326 BOOST_CHECK_EQUAL(SpanToStr(results[2]), "bar*");
1328}
1329
1331{
1332 // Empty string.
1333 {
1334 std::vector<std::string> result = SplitString("", '-');
1335 BOOST_CHECK_EQUAL(result.size(), 1);
1336 BOOST_CHECK_EQUAL(result[0], "");
1337 }
1338
1339 // Empty items.
1340 {
1341 std::vector<std::string> result = SplitString("-", '-');
1342 BOOST_CHECK_EQUAL(result.size(), 2);
1343 BOOST_CHECK_EQUAL(result[0], "");
1344 BOOST_CHECK_EQUAL(result[1], "");
1345 }
1346
1347 // More empty items.
1348 {
1349 std::vector<std::string> result = SplitString("--", '-');
1350 BOOST_CHECK_EQUAL(result.size(), 3);
1351 BOOST_CHECK_EQUAL(result[0], "");
1352 BOOST_CHECK_EQUAL(result[1], "");
1353 BOOST_CHECK_EQUAL(result[2], "");
1354 }
1355
1356 // Separator is not present.
1357 {
1358 std::vector<std::string> result = SplitString("abc", '-');
1359 BOOST_CHECK_EQUAL(result.size(), 1);
1360 BOOST_CHECK_EQUAL(result[0], "abc");
1361 }
1362
1363 // Basic behavior.
1364 {
1365 std::vector<std::string> result = SplitString("a-b", '-');
1366 BOOST_CHECK_EQUAL(result.size(), 2);
1367 BOOST_CHECK_EQUAL(result[0], "a");
1368 BOOST_CHECK_EQUAL(result[1], "b");
1369 }
1370
1371 // Case-sensitivity of the separator.
1372 {
1373 std::vector<std::string> result = SplitString("AAA", 'a');
1374 BOOST_CHECK_EQUAL(result.size(), 1);
1375 BOOST_CHECK_EQUAL(result[0], "AAA");
1376 }
1377
1378 // multiple split characters
1379 {
1380 using V = std::vector<std::string>;
1381 BOOST_TEST(SplitString("a,b.c:d;e", ",;") == V({"a", "b.c:d", "e"}));
1382 BOOST_TEST(SplitString("a,b.c:d;e", ",;:.") == V({"a", "b", "c", "d", "e"}));
1383 BOOST_TEST(SplitString("a,b.c:d;e", "") == V({"a,b.c:d;e"}));
1384 BOOST_TEST(SplitString("aaa", "bcdefg") == V({"aaa"}));
1385 BOOST_TEST(SplitString("x\0a,b"s, "\0"s) == V({"x", "a,b"}));
1386 BOOST_TEST(SplitString("x\0a,b"s, '\0') == V({"x", "a,b"}));
1387 BOOST_TEST(SplitString("x\0a,b"s, "\0,"s) == V({"x", "a", "b"}));
1388 BOOST_TEST(SplitString("abcdefg", "bcd") == V({"a", "", "", "efg"}));
1389 }
1390}
1391
1392namespace {
1393
1394struct Tracker
1395{
1397 const Tracker* origin;
1399 int copies{0};
1400
1401 Tracker() noexcept : origin(this) {}
1402 Tracker(const Tracker& t) noexcept : origin(t.origin), copies(t.copies + 1) {}
1403 Tracker(Tracker&& t) noexcept : origin(t.origin), copies(t.copies) {}
1404 Tracker& operator=(const Tracker& t) noexcept
1405 {
1406 if (this != &t) {
1407 origin = t.origin;
1408 copies = t.copies + 1;
1409 }
1410 return *this;
1411 }
1412};
1413
1414}
1415
1417{
1418 Tracker t1;
1419 Tracker t2;
1420 Tracker t3;
1421
1422 BOOST_CHECK(t1.origin == &t1);
1423 BOOST_CHECK(t2.origin == &t2);
1424 BOOST_CHECK(t3.origin == &t3);
1425
1426 auto v1 = Vector(t1);
1427 BOOST_CHECK_EQUAL(v1.size(), 1U);
1428 BOOST_CHECK(v1[0].origin == &t1);
1429 BOOST_CHECK_EQUAL(v1[0].copies, 1);
1430
1431 auto v2 = Vector(std::move(t2));
1432 BOOST_CHECK_EQUAL(v2.size(), 1U);
1433 BOOST_CHECK(v2[0].origin == &t2); // NOLINT(*-use-after-move)
1434 BOOST_CHECK_EQUAL(v2[0].copies, 0);
1435
1436 auto v3 = Vector(t1, std::move(t2));
1437 BOOST_CHECK_EQUAL(v3.size(), 2U);
1438 BOOST_CHECK(v3[0].origin == &t1);
1439 BOOST_CHECK(v3[1].origin == &t2); // NOLINT(*-use-after-move)
1440 BOOST_CHECK_EQUAL(v3[0].copies, 1);
1441 BOOST_CHECK_EQUAL(v3[1].copies, 0);
1442
1443 auto v4 = Vector(std::move(v3[0]), v3[1], std::move(t3));
1444 BOOST_CHECK_EQUAL(v4.size(), 3U);
1445 BOOST_CHECK(v4[0].origin == &t1);
1446 BOOST_CHECK(v4[1].origin == &t2);
1447 BOOST_CHECK(v4[2].origin == &t3); // NOLINT(*-use-after-move)
1448 BOOST_CHECK_EQUAL(v4[0].copies, 1);
1449 BOOST_CHECK_EQUAL(v4[1].copies, 1);
1450 BOOST_CHECK_EQUAL(v4[2].copies, 0);
1451
1452 auto v5 = Cat(v1, v4);
1453 BOOST_CHECK_EQUAL(v5.size(), 4U);
1454 BOOST_CHECK(v5[0].origin == &t1);
1455 BOOST_CHECK(v5[1].origin == &t1);
1456 BOOST_CHECK(v5[2].origin == &t2);
1457 BOOST_CHECK(v5[3].origin == &t3);
1458 BOOST_CHECK_EQUAL(v5[0].copies, 2);
1459 BOOST_CHECK_EQUAL(v5[1].copies, 2);
1460 BOOST_CHECK_EQUAL(v5[2].copies, 2);
1461 BOOST_CHECK_EQUAL(v5[3].copies, 1);
1462
1463 auto v6 = Cat(std::move(v1), v3);
1464 BOOST_CHECK_EQUAL(v6.size(), 3U);
1465 BOOST_CHECK(v6[0].origin == &t1);
1466 BOOST_CHECK(v6[1].origin == &t1);
1467 BOOST_CHECK(v6[2].origin == &t2);
1468 BOOST_CHECK_EQUAL(v6[0].copies, 1);
1469 BOOST_CHECK_EQUAL(v6[1].copies, 2);
1470 BOOST_CHECK_EQUAL(v6[2].copies, 1);
1471
1472 auto v7 = Cat(v2, std::move(v4));
1473 BOOST_CHECK_EQUAL(v7.size(), 4U);
1474 BOOST_CHECK(v7[0].origin == &t2);
1475 BOOST_CHECK(v7[1].origin == &t1);
1476 BOOST_CHECK(v7[2].origin == &t2);
1477 BOOST_CHECK(v7[3].origin == &t3);
1478 BOOST_CHECK_EQUAL(v7[0].copies, 1);
1479 BOOST_CHECK_EQUAL(v7[1].copies, 1);
1480 BOOST_CHECK_EQUAL(v7[2].copies, 1);
1481 BOOST_CHECK_EQUAL(v7[3].copies, 0);
1482
1483 auto v8 = Cat(std::move(v2), std::move(v3));
1484 BOOST_CHECK_EQUAL(v8.size(), 3U);
1485 BOOST_CHECK(v8[0].origin == &t2);
1486 BOOST_CHECK(v8[1].origin == &t1);
1487 BOOST_CHECK(v8[2].origin == &t2);
1488 BOOST_CHECK_EQUAL(v8[0].copies, 0);
1489 BOOST_CHECK_EQUAL(v8[1].copies, 1);
1490 BOOST_CHECK_EQUAL(v8[2].copies, 0);
1491}
1492
1494{
1495 const std::array<unsigned char, 32> privkey_bytes = {
1496 // just some random data
1497 // derived address from this private key: 15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs
1498 0xD9, 0x7F, 0x51, 0x08, 0xF1, 0x1C, 0xDA, 0x6E,
1499 0xEE, 0xBA, 0xAA, 0x42, 0x0F, 0xEF, 0x07, 0x26,
1500 0xB1, 0xF8, 0x98, 0x06, 0x0B, 0x98, 0x48, 0x9F,
1501 0xA3, 0x09, 0x84, 0x63, 0xC0, 0x03, 0x28, 0x66
1502 };
1503
1504 const std::string message = "Trust no one";
1505
1506 const std::string expected_signature =
1507 "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=";
1508
1509 CKey privkey;
1510 std::string generated_signature;
1511
1512 BOOST_REQUIRE_MESSAGE(!privkey.IsValid(),
1513 "Confirm the private key is invalid");
1514
1516 "Sign with an invalid private key");
1517
1518 privkey.Set(privkey_bytes.begin(), privkey_bytes.end(), true);
1519
1521 "Confirm the private key is valid");
1522
1524 "Sign with a valid private key");
1525
1527}
1528
1530{
1533 "invalid address",
1534 "signature should be irrelevant",
1535 "message too"),
1537
1540 "3B5fQsEXEaV8v6U3ejYc8XaKXAkyQj2MjV",
1541 "signature should be irrelevant",
1542 "message too"),
1544
1547 "1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
1548 "invalid signature, not in base64 encoding",
1549 "message should be irrelevant"),
1551
1554 "1KqbBpLy5FARmTPD4VZnDDpYjkUvkr82Pm",
1555 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
1556 "message should be irrelevant"),
1558
1561 "15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
1562 "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
1563 "I never signed this"),
1565
1568 "15CRxFdyRpGZLW9w8HnHvVduizdL5jKNbs",
1569 "IPojfrX2dfPnH26UegfbGQQLrdK844DlHq5157/P6h57WyuS/Qsl+h/WSVGDF4MUi4rWSswW38oimDYfNNUBUOk=",
1570 "Trust no one"),
1572
1575 "11canuhp9X2NocwCq7xNrQYTmUgZAnLK3",
1576 "IIcaIENoYW5jZWxsb3Igb24gYnJpbmsgb2Ygc2Vjb25kIGJhaWxvdXQgZm9yIGJhbmtzIAaHRtbCeDZINyavx14=",
1577 "Trust me"),
1579}
1580
1582{
1583 const std::string unsigned_tx = "...";
1584 const std::string prefixed_message =
1585 std::string(1, (char)MESSAGE_MAGIC.length()) +
1587 std::string(1, (char)unsigned_tx.length()) +
1589
1593
1596}
1597
1599{
1600 BOOST_CHECK_EQUAL(RemovePrefix("./common/system.h", "./"), "common/system.h");
1601 BOOST_CHECK_EQUAL(RemovePrefixView("foo", "foo"), "");
1602 BOOST_CHECK_EQUAL(RemovePrefix("foo", "fo"), "o");
1603 BOOST_CHECK_EQUAL(RemovePrefixView("foo", "f"), "oo");
1604 BOOST_CHECK_EQUAL(RemovePrefix("foo", ""), "foo");
1605 BOOST_CHECK_EQUAL(RemovePrefixView("fo", "foo"), "fo");
1606 BOOST_CHECK_EQUAL(RemovePrefix("f", "foo"), "f");
1607 BOOST_CHECK_EQUAL(RemovePrefixView("", "foo"), "");
1608 BOOST_CHECK_EQUAL(RemovePrefix("", ""), "");
1609}
1610
1612{
1613 auto noop = ByteUnit::NOOP;
1614
1615 // no multiplier
1616 BOOST_CHECK_EQUAL(ParseByteUnits("1", noop).value(), 1);
1617 BOOST_CHECK_EQUAL(ParseByteUnits("0", noop).value(), 0);
1618
1619 BOOST_CHECK_EQUAL(ParseByteUnits("1k", noop).value(), 1000ULL);
1620 BOOST_CHECK_EQUAL(ParseByteUnits("1K", noop).value(), 1ULL << 10);
1621
1622 BOOST_CHECK_EQUAL(ParseByteUnits("2m", noop).value(), 2'000'000ULL);
1623 BOOST_CHECK_EQUAL(ParseByteUnits("2M", noop).value(), 2_MiB);
1624
1625 BOOST_CHECK_EQUAL(ParseByteUnits("3g", noop).value(), 3'000'000'000ULL);
1626 BOOST_CHECK_EQUAL(ParseByteUnits("3G", noop).value(), 3_GiB);
1627
1628 BOOST_CHECK_EQUAL(ParseByteUnits("4t", noop).value(), 4'000'000'000'000ULL);
1629 BOOST_CHECK_EQUAL(ParseByteUnits("4T", noop).value(), 4ULL << 40);
1630
1631 // check default multiplier
1632 BOOST_CHECK_EQUAL(ParseByteUnits("5", ByteUnit::K).value(), 5ULL << 10);
1633
1634 // NaN
1637
1638 // whitespace
1639 BOOST_CHECK(!ParseByteUnits("123m ", noop));
1640 BOOST_CHECK(!ParseByteUnits(" 123m", noop));
1641
1642 // no +-
1643 BOOST_CHECK(!ParseByteUnits("-123m", noop));
1644 BOOST_CHECK(!ParseByteUnits("+123m", noop));
1645
1646 // zero padding
1647 BOOST_CHECK_EQUAL(ParseByteUnits("020M", noop).value(), 20_MiB);
1648
1649 // fractions not allowed
1650 BOOST_CHECK(!ParseByteUnits("0.5T", noop));
1651
1652 // overflow
1653 BOOST_CHECK(!ParseByteUnits("18446744073709551615g", noop));
1654
1655 // invalid unit
1657}
1658
1660{
1661 fs::path tmpfolder = m_args.GetDataDirBase();
1662 fs::path tmpfile = tmpfolder / "read_binary.dat";
1663 std::string expected_text;
1664 for (int i = 0; i < 30; i++) {
1665 expected_text += "0123456789";
1666 }
1667 {
1668 std::ofstream file{tmpfile.std_path()};
1669 file << expected_text;
1670 }
1671 {
1672 // read all contents in file
1673 auto [valid, text] = ReadBinaryFile(tmpfile);
1674 BOOST_CHECK(valid);
1676 }
1677 {
1678 // read half contents in file
1679 auto [valid, text] = ReadBinaryFile(tmpfile, expected_text.size() / 2);
1680 BOOST_CHECK(valid);
1681 BOOST_CHECK_EQUAL(text, expected_text.substr(0, expected_text.size() / 2));
1682 }
1683 {
1684 // read from non-existent file
1685 fs::path invalid_file = tmpfolder / "invalid_binary.dat";
1686 auto [valid, text] = ReadBinaryFile(invalid_file);
1687 BOOST_CHECK(!valid);
1688 BOOST_CHECK(text.empty());
1689 }
1690}
1691
1693{
1694 fs::path tmpfolder = m_args.GetDataDirBase();
1695 fs::path tmpfile = tmpfolder / "write_binary.dat";
1696 std::string expected_text = "bitcoin";
1697 auto valid = WriteBinaryFile(tmpfile, expected_text);
1698 std::string actual_text;
1699 std::ifstream file{tmpfile.std_path()};
1700 file >> actual_text;
1701 BOOST_CHECK(valid);
1703}
1704
1706{
1707 {
1708 std::vector<uint8_t> v = {1, 2, 3};
1709 ClearShrink(v);
1710 BOOST_CHECK_EQUAL(v.size(), 0);
1711 BOOST_CHECK_EQUAL(v.capacity(), 0);
1712 }
1713
1714 {
1715 std::vector<bool> v = {false, true, false, false, true, true};
1716 ClearShrink(v);
1717 BOOST_CHECK_EQUAL(v.size(), 0);
1718 BOOST_CHECK_EQUAL(v.capacity(), 0);
1719 }
1720
1721 {
1722 std::deque<int> v = {1, 3, 3, 7};
1723 ClearShrink(v);
1724 BOOST_CHECK_EQUAL(v.size(), 0);
1725 // std::deque has no capacity() we can observe.
1726 }
1727}
1728
1729template <typename T>
1731{
1732 constexpr auto MAX{std::numeric_limits<T>::max()};
1733
1734 // Basic operations
1739 BOOST_CHECK_EQUAL(CheckedLeftShift<T>(MAX >> 1, 1), MAX - 1);
1740
1741 // Max left shift
1742 BOOST_CHECK_EQUAL(CheckedLeftShift<T>(1, std::numeric_limits<T>::digits - 1), MAX / 2 + 1);
1743
1744 // Overflow cases
1745 BOOST_CHECK(!CheckedLeftShift<T>((MAX >> 1) + 1, 1));
1747 BOOST_CHECK(!CheckedLeftShift<T>(1, std::numeric_limits<T>::digits));
1748 BOOST_CHECK(!CheckedLeftShift<T>(1, std::numeric_limits<T>::digits + 1));
1749
1750 if constexpr (std::is_signed_v<T>) {
1751 constexpr auto MIN{std::numeric_limits<T>::min()};
1752 // Negative input
1755 BOOST_CHECK_EQUAL(CheckedLeftShift<T>((MIN >> 1) + 1, 1), MIN + 2);
1757 // Overflow negative
1758 BOOST_CHECK(!CheckedLeftShift<T>((MIN >> 1) - 1, 1));
1761 }
1762}
1763
1764template <typename T>
1766{
1767 constexpr auto MAX{std::numeric_limits<T>::max()};
1768
1769 // Basic operations
1774 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>(MAX >> 1, 1), MAX - 1);
1775
1776 // Max left shift
1777 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>(1, std::numeric_limits<T>::digits - 1), MAX / 2 + 1);
1778
1779 // Saturation cases
1780 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>((MAX >> 1) + 1, 1), MAX);
1782 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>(1, std::numeric_limits<T>::digits), MAX);
1783 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>(1, std::numeric_limits<T>::digits + 1), MAX);
1784
1785 if constexpr (std::is_signed_v<T>) {
1786 constexpr auto MIN{std::numeric_limits<T>::min()};
1787 // Negative input
1790 BOOST_CHECK_EQUAL(SaturatingLeftShift<T>((MIN >> 1) + 1, 1), MIN + 2);
1792 // Saturation negative
1796 }
1797}
1798
1807
1816
1817template <class Int, auto bytes>
1818concept BraceInitializesTo = requires { Int{bytes}; };
1819
1821{
1822 // Basic equivalences and simple arithmetic operations
1824 BOOST_CHECK_EQUAL(1_MiB, 1 << 20);
1825 BOOST_CHECK_EQUAL(1_MiB, 1024 * 1024);
1826 BOOST_CHECK_EQUAL(1_MiB, 0x100000U);
1827 BOOST_CHECK_EQUAL(1_MiB, 1048576U);
1828 BOOST_CHECK_EQUAL(2ULL * 1_MiB, 2ULL << 20);
1829 BOOST_CHECK_EQUAL((3_MiB + 123) / double(1_MiB), (3_MiB + 123) / 1024.0 / 1024.0);
1830
1831 // Specific codebase values
1832 BOOST_CHECK_EQUAL(4_MiB, 1 << 22);
1833 BOOST_CHECK_EQUAL(8_MiB, 1 << 23);
1834 BOOST_CHECK_EQUAL(16_MiB, 0x1000000U);
1835 BOOST_CHECK_EQUAL(16_MiB, 1 << 24);
1836 BOOST_CHECK_EQUAL(32_MiB, 0x2000000U);
1837 BOOST_CHECK_EQUAL(32_MiB, 32U << 20);
1838 BOOST_CHECK_EQUAL(50_MiB / 1_MiB, 50U);
1839 BOOST_CHECK_EQUAL(50_MiB, 52428800U);
1840 BOOST_CHECK_EQUAL(128_MiB, 0x8000000U);
1841 BOOST_CHECK_EQUAL(550_MiB, 550ULL * 1024 * 1024);
1842
1843 // 4095 MiB fits in uint32_t bytes. 4096 MiB requires the uint64_t return type.
1847 BOOST_CHECK_EQUAL(4095_MiB, uint32_t{4095} << 20);
1848 BOOST_CHECK_EQUAL(4096_MiB, uint64_t{4096} << 20);
1849}
1850
1852{
1853 // Type combinations used by current CeilDiv callsites.
1854 BOOST_CHECK((std::is_same_v<decltype(CeilDiv(uint32_t{0}, 8u)), uint32_t>));
1855 BOOST_CHECK((std::is_same_v<decltype(CeilDiv(size_t{0}, 8u)), size_t>));
1856 BOOST_CHECK((std::is_same_v<decltype(CeilDiv(unsigned{0}, size_t{1})), size_t>));
1857
1858 // `common/bloom.cpp` and `cuckoocache.h` patterns.
1862
1863 // `key_io.cpp`, `rest.cpp`, `merkleblock.cpp`, `strencodings.cpp` patterns.
1864 BOOST_CHECK_EQUAL(CeilDiv(size_t{9}, 8u), size_t{2});
1865 BOOST_CHECK_EQUAL(CeilDiv(size_t{10}, 3u), size_t{4});
1866 BOOST_CHECK_EQUAL(CeilDiv(size_t{11}, 5u), size_t{3});
1867 BOOST_CHECK_EQUAL(CeilDiv(size_t{41} * 8, 5u), size_t{66});
1868
1869 // `flatfile.cpp` mixed unsigned/size_t pattern.
1870 BOOST_CHECK_EQUAL(CeilDiv(unsigned{10}, size_t{4}), size_t{3});
1871
1872 // `util/feefrac.h` fast-path rounding-up pattern.
1873 constexpr int64_t fee{12345};
1874 constexpr int32_t at_size{67};
1875 constexpr int32_t size{10};
1877 (uint64_t(fee) * at_size + uint32_t(size) - 1) / uint32_t(size));
1878
1879 // `bitset.h` template parameter pattern.
1880 constexpr unsigned bits{129};
1881 constexpr size_t digits{std::numeric_limits<size_t>::digits};
1882 BOOST_CHECK_EQUAL(CeilDiv(bits, digits), (bits + digits - 1) / digits);
1883
1884 // `serialize.h` varint scratch-buffer pattern.
1885 BOOST_CHECK_EQUAL(CeilDiv(sizeof(uint64_t) * 8, 7u), (sizeof(uint64_t) * 8 + 6) / 7);
1886}
1887
1889{
1890 // Basic equivalences and simple arithmetic operations
1892 BOOST_CHECK_EQUAL(1_GiB, 1 << 30);
1893 BOOST_CHECK_EQUAL(1_GiB, 1024 * 1024 * 1024);
1894 BOOST_CHECK_EQUAL(1_GiB, 0x40000000U);
1895 BOOST_CHECK_EQUAL(1_GiB, 1073741824U);
1896 BOOST_CHECK_EQUAL(1_GiB, 1_MiB * 1024);
1898 BOOST_CHECK_EQUAL((1_GiB + 123) / double(1_GiB), (1_GiB + 123) / 1024.0 / 1024.0 / 1024.0);
1899 BOOST_CHECK_EQUAL(2ULL * 1_GiB, 2ULL << 30);
1900 BOOST_CHECK_EQUAL(4 * uint64_t{1_GiB}, uint64_t{4} << 30);
1902 BOOST_CHECK_EQUAL(3_GiB / 1_GiB, 3U);
1903 BOOST_CHECK_EQUAL(3_GiB, 3U << 30);
1904
1905 // 3 GiB fits in uint32_t bytes. 4 GiB requires the uint64_t return type.
1909 BOOST_CHECK_EQUAL(3_GiB, uint32_t{3} << 30);
1910 BOOST_CHECK_EQUAL(4_GiB, uint64_t{4} << 30);
1911
1912 // Specific codebase values
1915 BOOST_CHECK_EQUAL(16_GiB, 16384_MiB);
1916 BOOST_CHECK_EQUAL(32_GiB, 32768_MiB);
1917}
1918
1920{
1921 // Initial value is clamped to cap
1922 util::TokenBucket<NodeClock> b1(/*rate=*/1, /*value=*/100, /*cap=*/10);
1923 BOOST_CHECK_EQUAL(b1.value(), 10);
1924
1925 // Initial value below cap is kept as-is
1926 util::TokenBucket<NodeClock> b2(/*rate=*/1, /*value=*/5, /*cap=*/10);
1927 BOOST_CHECK_EQUAL(b2.value(), 5);
1928}
1929
1931{
1932 // First increment establishes the time baseline but does not refill
1933 util::TokenBucket<NodeClock> b(/*rate=*/100, /*value=*/0, /*cap=*/1000);
1935 BOOST_CHECK_EQUAL(b.value(), 0);
1936
1937 // Second increment refills based on elapsed time
1939 BOOST_CHECK_EQUAL(b.value(), 500); // 100/s * 5s
1940}
1941
1943{
1944 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/90, /*cap=*/100);
1946 b.increment(NodeClock::time_point{100s}); // would add 990, but cap is 100
1947 BOOST_CHECK_EQUAL(b.value(), 100);
1948}
1949
1951{
1952 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/50, /*cap=*/200);
1954 b.increment(NodeClock::time_point{5s}); // backwards, no change
1955 BOOST_CHECK_EQUAL(b.value(), 50);
1956 b.increment(NodeClock::time_point{15s}); // forwards takes backwards into account
1957 BOOST_CHECK_EQUAL(b.value(), 150);
1958}
1959
1961{
1962 // Default debt=0: returns false at exactly 0
1963 util::TokenBucket<NodeClock> b(/*rate=*/1, /*value=*/3, /*cap=*/10);
1964 BOOST_CHECK(b.decrement(1)); // 3 -> 2
1965 BOOST_CHECK(b.decrement(1)); // 2 -> 1
1966 BOOST_CHECK(!b.decrement(1)); // 1 -> 0, at floor
1967 BOOST_CHECK_EQUAL(b.value(), 0);
1968 BOOST_CHECK(!b.decrement(1)); // 0 -> -1, despite being at floor
1969 BOOST_CHECK_EQUAL(b.value(), -1);
1970}
1971
1973{
1974 util::TokenBucket<NodeClock> b(/*rate=*/1, /*value=*/2, /*cap=*/10);
1975 BOOST_CHECK(b.decrement(1, -3)); // 2 -> 1
1976 BOOST_CHECK(b.decrement(1, -3)); // 1 -> 0
1977 BOOST_CHECK(b.decrement(1, -3)); // 0 -> -1, still above -3
1978 BOOST_CHECK(b.decrement(1, -3)); // -1 -> -2, still above -3
1979 BOOST_CHECK(!b.decrement(1, -3)); // -2 -> -3, at floor
1980 BOOST_CHECK_EQUAL(b.value(), -3);
1981}
1982
1984{
1985 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/20, /*cap=*/100);
1986 b.decrement(20); // drain to 0
1987 BOOST_CHECK_EQUAL(b.value(), 0);
1988
1990 b.increment(NodeClock::time_point{4s}); // +30
1991 BOOST_CHECK_EQUAL(b.value(), 30);
1992}
1993
1994
1996{
1997 // The first increment establishes the baseline (no refill) even when it
1998 // lands exactly on the clock epoch; later increments then refill normally.
1999 util::TokenBucket<NodeClock> b(/*rate=*/100, /*value=*/0, /*cap=*/1000);
2001 BOOST_CHECK_EQUAL(b.value(), 0);
2003 BOOST_CHECK_EQUAL(b.value(), 500); // 100/s * 5s
2004}
2005
2007{
2008 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/100, /*cap=*/100);
2009 BOOST_CHECK_EQUAL(b.value(), 100); // already at cap
2010 b.increment(NodeClock::time_point{1s}); // baseline established at 1s
2011 b.increment(NodeClock::time_point{100s}); // 99s spent at the cap; baseline -> 100s
2012 BOOST_CHECK_EQUAL(b.value(), 100);
2013
2014 b.decrement(100); // drain to 0
2015 BOOST_CHECK_EQUAL(b.value(), 0);
2016
2017 // refill doesn't "bank" the extra 99s we were at cap
2019 BOOST_CHECK_EQUAL(b.value(), 10);
2020
2021 // And when real time genuinely elapses, a single increment refills straight
2022 // back to the cap immediately.
2023 b.increment(NodeClock::time_point{200s}); // 99s elapsed -> +990, clamped to cap
2024 BOOST_CHECK_EQUAL(b.value(), 100);
2025}
2026
2028{
2029 // Sub-second elapsed time accumulates fractional tokens via double math.
2030 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/0, /*cap=*/100);
2032 b.increment(NodeClock::time_point{1250ms}); // 10/s * 0.25s = 2.5
2033 BOOST_CHECK_EQUAL(b.value(), 2.5);
2034}
2035
2037{
2038 // Refilling from a negative (debt) balance accrues normally and still
2039 // clamps to the cap rather than to debt + increment.
2040 util::TokenBucket<NodeClock> b(/*rate=*/10, /*value=*/0, /*cap=*/100);
2041 BOOST_CHECK(!b.decrement(50)); // -> -50, below floor 0
2042 BOOST_CHECK_EQUAL(b.value(), -50);
2043 b.increment(NodeClock::time_point{1s}); // baseline
2044 b.increment(NodeClock::time_point{4s}); // +30 -> -20
2045 BOOST_CHECK_EQUAL(b.value(), -20);
2046 b.increment(NodeClock::time_point{100s}); // +960 but clamped to cap
2047 BOOST_CHECK_EQUAL(b.value(), 100);
2048}
2049
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition amount.h:15
static void pool cs
#define Assert(val)
Identity function.
Definition check.h:119
#define Assume(val)
Assume is the identity function.
Definition check.h:131
An encapsulated private key.
Definition key.h:46
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Definition time.h:54
256-bit opaque blob.
Definition uint256.h:196
A token bucket rate limiter.
Definition tokenbucket.h:24
bool decrement(double n=1.0, double floor=0.0)
Consume n tokens.
Definition tokenbucket.h:52
void increment(const time_point &now)
Refill tokens based on elapsed time since last call.
Definition tokenbucket.h:40
double value() const
Current token balance.
Definition tokenbucket.h:59
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...
bool MessageSign(const CKey &privkey, const std::string &message, std::string &signature)
Sign a message.
const std::string MESSAGE_MAGIC
Text used to signify that a signed message follows and to prevent inadvertently signing a transaction...
MessageVerificationResult MessageVerify(const std::string &address, const std::string &signature, const std::string &message)
Verify a signed message.
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
void ReleaseDirectoryLocks()
Release all directory locks.
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition hash.h:83
#define T(expected, seed, data)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition hex_base.cpp:30
uint64_t fee
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
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition string.h:153
consteval uint8_t ConstevalHexDigit(const char c)
consteval version of HexDigit() without the lookup table.
std::vector< T > Split(std::span< const char > sp LIFETIMEBOUND, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
Definition string.h:120
LockResult
Definition fs_helpers.h:99
std::string_view TrimStringView(std::string_view str LIFETIMEBOUND, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:163
void ReplaceAll(std::string &in_out, std::string_view search, std::string_view substitute)
Replace every non-overlapping occurrence of search with substitute, treating both literally; the repl...
Definition string.cpp:14
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition string.h:173
std::string RemovePrefix(std::string_view str, std::string_view prefix)
Definition string.h:194
auto Join(const C &container, const S &separator, UnaryOp unary_op)
Join all container items.
Definition string.h:209
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
std::string_view RemovePrefixView(std::string_view str LIFETIMEBOUND, std::string_view prefix)
Definition string.h:186
#define BOOST_CHECK_EQUAL(v1, v2)
Definition object.cpp:17
#define BOOST_CHECK(expr)
Definition object.cpp:16
std::optional< T > CheckedAdd(const T i, const T j) noexcept
Definition overflow.h:27
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
Definition overflow.h:70
T SaturatingAdd(const T i, const T j) noexcept
Definition overflow.h:44
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.
auto MakeByteSpan(const V &v) noexcept
Definition span.h:84
constexpr auto MakeUCharSpan(const V &v) -> decltype(UCharSpanCast(std::span{v}))
Like the std::span constructor, but for (const) unsigned char member types only.
Definition span.h:111
auto MakeWritableByteSpan(V &&v) noexcept
Definition span.h:89
constexpr bool IsDigit(char c)
Tests if the given character is a decimal digit.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
@ SAFE_CHARS_UA_COMMENT
BIP-0014 subset.
Basic testing setup.
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition time.cpp:38
std::chrono::time_point< NodeClock > time_point
Definition time.h:28
#define LOCK(cs)
Definition sync.h:268
#define TRY_LOCK(cs, name)
Definition sync.h:273
@ ZEROS
Seed with a compile time constant of zeros.
static int count
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
BOOST_CHECK_NE(OneL.ToString(), ArrayToString(ZeroArray, 32))
BOOST_CHECK_EQUAL_COLLECTIONS(R1L.begin(), R1L.end(), R1Array, R1Array+uint256::size())
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
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 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.
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.
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition time.cpp:30
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition time.cpp:88
std::string FormatISO8601Date(int64_t nTime)
Definition time.cpp:99
std::optional< int64_t > ParseISO8601DateTime(std::string_view str)
Definition time.cpp:107
std::string FormatRFC1123DateTime(int64_t time)
RFC1123 formatting https://www.rfc-editor.org/rfc/rfc1123#section-5.2.14 Used in HTTP/1....
Definition time.cpp:131
std::string FormatISO8601DateTime(int64_t nTime)
ISO 8601 formatting is preferred.
Definition time.cpp:90
constexpr int64_t TicksSeconds(Duration d)
Definition time.h:88
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82
int64_t atoi64_legacy(const std::string &str)
#define E
constexpr uint8_t HEX_PARSE_OUTPUT[]
constexpr char HEX_PARSE_INPUT[]
static void TestOtherProcess(fs::path dirname, fs::path lockname, int fd)
#define B
static constexpr char ExitCommand
static constexpr char UnlockCommand
static std::string SpanToStr(const std::span< const char > &span)
@ ResErrorWrite
@ ResUnlockSuccess
@ ResSuccess
@ ResErrorLock
static void TestAddMatrixOverflow()
static void TestAddMatrix()
BOOST_AUTO_TEST_CASE(util_check)
static void RunToIntegralTests()
static const std::string STRING_WITH_EMBEDDED_NULL_CHAR
static constexpr char LockCommand
void TestCheckedLeftShift()
void TestSaturatingLeftShift()
assert(!tx.IsCoinBase())
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition vector.h:34
std::vector< std::common_type_t< Args... > > 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
FakeNodeClock clock