Bitcoin Core 29.99.0
P2P Digital Currency
streams_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-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 <flatfile.h>
6#include <node/blockstorage.h>
7#include <streams.h>
8#include <test/util/random.h>
10#include <util/fs.h>
11#include <util/obfuscation.h>
12#include <util/strencodings.h>
13
14#include <boost/test/unit_test.hpp>
15
16using namespace std::string_literals;
17using namespace util::hex_literals;
18
20
21// Check optimized obfuscation with random offsets and sizes to ensure proper
22// handling of key wrapping. Also verify it roundtrips.
23BOOST_AUTO_TEST_CASE(xor_random_chunks)
24{
25 auto apply_random_xor_chunks{[&](std::span<std::byte> target, const Obfuscation& obfuscation) {
26 for (size_t offset{0}; offset < target.size();) {
27 const size_t chunk_size{1 + m_rng.randrange(target.size() - offset)};
28 obfuscation(target.subspan(offset, chunk_size), offset);
29 offset += chunk_size;
30 }
31 }};
32
33 for (size_t test{0}; test < 100; ++test) {
34 const size_t write_size{1 + m_rng.randrange(100U)};
35 const std::vector original{m_rng.randbytes<std::byte>(write_size)};
36 std::vector roundtrip{original};
37
38 const auto key_bytes{m_rng.randbool() ? m_rng.randbytes<Obfuscation::KEY_SIZE>() : std::array<std::byte, Obfuscation::KEY_SIZE>{}};
39 const Obfuscation obfuscation{key_bytes};
40 apply_random_xor_chunks(roundtrip, obfuscation);
41 BOOST_CHECK_EQUAL(roundtrip.size(), original.size());
42 for (size_t i{0}; i < original.size(); ++i) {
43 BOOST_CHECK_EQUAL(roundtrip[i], original[i] ^ key_bytes[i % Obfuscation::KEY_SIZE]);
44 }
45
46 apply_random_xor_chunks(roundtrip, obfuscation);
47 BOOST_CHECK_EQUAL_COLLECTIONS(roundtrip.begin(), roundtrip.end(), original.begin(), original.end());
48 }
49}
50
51BOOST_AUTO_TEST_CASE(obfuscation_hexkey)
52{
53 const auto key_bytes{m_rng.randbytes<Obfuscation::KEY_SIZE>()};
54
55 const Obfuscation obfuscation{key_bytes};
56 BOOST_CHECK_EQUAL(obfuscation.HexKey(), HexStr(key_bytes));
57}
58
59BOOST_AUTO_TEST_CASE(obfuscation_serialize)
60{
61 Obfuscation obfuscation{};
62 BOOST_CHECK(!obfuscation);
63
64 // Test loading a key.
65 std::vector key_in{m_rng.randbytes<std::byte>(Obfuscation::KEY_SIZE)};
66 DataStream ds_in;
67 ds_in << key_in;
68 BOOST_CHECK_EQUAL(ds_in.size(), 1 + Obfuscation::KEY_SIZE); // serialized as a vector
69 ds_in >> obfuscation;
70
71 // Test saving the key.
72 std::vector<std::byte> key_out;
73 DataStream ds_out;
74 ds_out << obfuscation;
75 ds_out >> key_out;
76
77 // Make sure saved key is the same.
78 BOOST_CHECK_EQUAL_COLLECTIONS(key_in.begin(), key_in.end(), key_out.begin(), key_out.end());
79}
80
81BOOST_AUTO_TEST_CASE(obfuscation_empty)
82{
83 const Obfuscation null_obf{};
84 BOOST_CHECK(!null_obf);
85
86 const Obfuscation non_null_obf{"ff00ff00ff00ff00"_hex};
87 BOOST_CHECK(non_null_obf);
88}
89
91{
92 fs::path xor_path{m_args.GetDataDirBase() / "test_xor.bin"};
93 auto raw_file{[&](const auto& mode) { return fsbridge::fopen(xor_path, mode); }};
94 const std::vector<uint8_t> test1{1, 2, 3};
95 const std::vector<uint8_t> test2{4, 5};
96 const Obfuscation obfuscation{"ff00ff00ff00ff00"_hex};
97
98 {
99 // Check errors for missing file
100 AutoFile xor_file{raw_file("rb"), obfuscation};
101 BOOST_CHECK_EXCEPTION(xor_file << std::byte{}, std::ios_base::failure, HasReason{"AutoFile::write: file handle is nullptr"});
102 BOOST_CHECK_EXCEPTION(xor_file >> std::byte{}, std::ios_base::failure, HasReason{"AutoFile::read: file handle is nullptr"});
103 BOOST_CHECK_EXCEPTION(xor_file.ignore(1), std::ios_base::failure, HasReason{"AutoFile::ignore: file handle is nullptr"});
104 }
105 {
106#ifdef __MINGW64__
107 // Temporary workaround for https://github.com/bitcoin/bitcoin/issues/30210
108 const char* mode = "wb";
109#else
110 const char* mode = "wbx";
111#endif
112 AutoFile xor_file{raw_file(mode), obfuscation};
113 xor_file << test1 << test2;
114 BOOST_REQUIRE_EQUAL(xor_file.fclose(), 0);
115 }
116 {
117 // Read raw from disk
118 AutoFile non_xor_file{raw_file("rb")};
119 std::vector<std::byte> raw(7);
120 non_xor_file >> std::span{raw};
121 BOOST_CHECK_EQUAL(HexStr(raw), "fc01fd03fd04fa");
122 // Check that no padding exists
123 BOOST_CHECK_EXCEPTION(non_xor_file.ignore(1), std::ios_base::failure, HasReason{"AutoFile::ignore: end of file"});
124 }
125 {
126 AutoFile xor_file{raw_file("rb"), obfuscation};
127 std::vector<std::byte> read1, read2;
128 xor_file >> read1 >> read2;
130 BOOST_CHECK_EQUAL(HexStr(read2), HexStr(test2));
131 // Check that eof was reached
132 BOOST_CHECK_EXCEPTION(xor_file >> std::byte{}, std::ios_base::failure, HasReason{"AutoFile::read: end of file"});
133 }
134 {
135 AutoFile xor_file{raw_file("rb"), obfuscation};
136 std::vector<std::byte> read2;
137 // Check that ignore works
138 xor_file.ignore(4);
139 xor_file >> read2;
140 BOOST_CHECK_EQUAL(HexStr(read2), HexStr(test2));
141 // Check that ignore and read fail now
142 BOOST_CHECK_EXCEPTION(xor_file.ignore(1), std::ios_base::failure, HasReason{"AutoFile::ignore: end of file"});
143 BOOST_CHECK_EXCEPTION(xor_file >> std::byte{}, std::ios_base::failure, HasReason{"AutoFile::read: end of file"});
144 }
145}
146
147BOOST_AUTO_TEST_CASE(streams_vector_writer)
148{
149 unsigned char a(1);
150 unsigned char b(2);
151 unsigned char bytes[] = {3, 4, 5, 6};
152 std::vector<unsigned char> vch;
153
154 // Each test runs twice. Serializing a second time at the same starting
155 // point should yield the same results, even if the first test grew the
156 // vector.
157
158 VectorWriter{vch, 0, a, b};
159 BOOST_CHECK((vch == std::vector<unsigned char>{{1, 2}}));
160 VectorWriter{vch, 0, a, b};
161 BOOST_CHECK((vch == std::vector<unsigned char>{{1, 2}}));
162 vch.clear();
163
164 VectorWriter{vch, 2, a, b};
165 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2}}));
166 VectorWriter{vch, 2, a, b};
167 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2}}));
168 vch.clear();
169
170 vch.resize(5, 0);
171 VectorWriter{vch, 2, a, b};
172 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2, 0}}));
173 VectorWriter{vch, 2, a, b};
174 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 1, 2, 0}}));
175 vch.clear();
176
177 vch.resize(4, 0);
178 VectorWriter{vch, 3, a, b};
179 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 1, 2}}));
180 VectorWriter{vch, 3, a, b};
181 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 1, 2}}));
182 vch.clear();
183
184 vch.resize(4, 0);
185 VectorWriter{vch, 4, a, b};
186 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 0, 1, 2}}));
187 VectorWriter{vch, 4, a, b};
188 BOOST_CHECK((vch == std::vector<unsigned char>{{0, 0, 0, 0, 1, 2}}));
189 vch.clear();
190
191 VectorWriter{vch, 0, bytes};
192 BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
193 VectorWriter{vch, 0, bytes};
194 BOOST_CHECK((vch == std::vector<unsigned char>{{3, 4, 5, 6}}));
195 vch.clear();
196
197 vch.resize(4, 8);
198 VectorWriter{vch, 2, a, bytes, b};
199 BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
200 VectorWriter{vch, 2, a, bytes, b};
201 BOOST_CHECK((vch == std::vector<unsigned char>{{8, 8, 1, 3, 4, 5, 6, 2}}));
202 vch.clear();
203}
204
205BOOST_AUTO_TEST_CASE(streams_vector_reader)
206{
207 std::vector<unsigned char> vch = {1, 255, 3, 4, 5, 6};
208
209 SpanReader reader{vch};
210 BOOST_CHECK_EQUAL(reader.size(), 6U);
211 BOOST_CHECK(!reader.empty());
212
213 // Read a single byte as an unsigned char.
214 unsigned char a;
215 reader >> a;
216 BOOST_CHECK_EQUAL(a, 1);
217 BOOST_CHECK_EQUAL(reader.size(), 5U);
218 BOOST_CHECK(!reader.empty());
219
220 // Read a single byte as a int8_t.
221 int8_t b;
222 reader >> b;
223 BOOST_CHECK_EQUAL(b, -1);
224 BOOST_CHECK_EQUAL(reader.size(), 4U);
225 BOOST_CHECK(!reader.empty());
226
227 // Read a 4 bytes as an unsigned int.
228 unsigned int c;
229 reader >> c;
230 BOOST_CHECK_EQUAL(c, 100992003U); // 3,4,5,6 in little-endian base-256
231 BOOST_CHECK_EQUAL(reader.size(), 0U);
232 BOOST_CHECK(reader.empty());
233
234 // Reading after end of byte vector throws an error.
235 signed int d;
236 BOOST_CHECK_THROW(reader >> d, std::ios_base::failure);
237
238 // Read a 4 bytes as a signed int from the beginning of the buffer.
239 SpanReader new_reader{vch};
240 new_reader >> d;
241 BOOST_CHECK_EQUAL(d, 67370753); // 1,255,3,4 in little-endian base-256
242 BOOST_CHECK_EQUAL(new_reader.size(), 2U);
243 BOOST_CHECK(!new_reader.empty());
244
245 // Reading after end of byte vector throws an error even if the reader is
246 // not totally empty.
247 BOOST_CHECK_THROW(new_reader >> d, std::ios_base::failure);
248}
249
250BOOST_AUTO_TEST_CASE(streams_vector_reader_rvalue)
251{
252 std::vector<uint8_t> data{0x82, 0xa7, 0x31};
253 SpanReader reader{data};
254 uint32_t varint = 0;
255 // Deserialize into r-value
256 reader >> VARINT(varint);
257 BOOST_CHECK_EQUAL(varint, 54321U);
258 BOOST_CHECK(reader.empty());
259}
260
261BOOST_AUTO_TEST_CASE(bitstream_reader_writer)
262{
264
265 BitStreamWriter bit_writer{data};
266 bit_writer.Write(0, 1);
267 bit_writer.Write(2, 2);
268 bit_writer.Write(6, 3);
269 bit_writer.Write(11, 4);
270 bit_writer.Write(1, 5);
271 bit_writer.Write(32, 6);
272 bit_writer.Write(7, 7);
273 bit_writer.Write(30497, 16);
274 bit_writer.Flush();
275
276 DataStream data_copy{data};
277 uint32_t serialized_int1;
278 data >> serialized_int1;
279 BOOST_CHECK_EQUAL(serialized_int1, uint32_t{0x7700C35A}); // NOTE: Serialized as LE
280 uint16_t serialized_int2;
281 data >> serialized_int2;
282 BOOST_CHECK_EQUAL(serialized_int2, uint16_t{0x1072}); // NOTE: Serialized as LE
283
284 BitStreamReader bit_reader{data_copy};
285 BOOST_CHECK_EQUAL(bit_reader.Read(1), 0U);
286 BOOST_CHECK_EQUAL(bit_reader.Read(2), 2U);
287 BOOST_CHECK_EQUAL(bit_reader.Read(3), 6U);
288 BOOST_CHECK_EQUAL(bit_reader.Read(4), 11U);
289 BOOST_CHECK_EQUAL(bit_reader.Read(5), 1U);
290 BOOST_CHECK_EQUAL(bit_reader.Read(6), 32U);
291 BOOST_CHECK_EQUAL(bit_reader.Read(7), 7U);
292 BOOST_CHECK_EQUAL(bit_reader.Read(16), 30497U);
293 BOOST_CHECK_THROW(bit_reader.Read(8), std::ios_base::failure);
294}
295
296BOOST_AUTO_TEST_CASE(streams_serializedata_xor)
297{
298 // Degenerate case
299 {
300 DataStream ds{};
301 Obfuscation{}(ds);
302 BOOST_CHECK_EQUAL(""s, ds.str());
303 }
304
305 {
306 const Obfuscation obfuscation{"ffffffffffffffff"_hex};
307
308 DataStream ds{"0ff0"_hex};
309 obfuscation(ds);
310 BOOST_CHECK_EQUAL("\xf0\x0f"s, ds.str());
311 }
312
313 {
314 const Obfuscation obfuscation{"ff0fff0fff0fff0f"_hex};
315
316 DataStream ds{"f00f"_hex};
317 obfuscation(ds);
318 BOOST_CHECK_EQUAL("\x0f\x00"s, ds.str());
319 }
320}
321
322BOOST_AUTO_TEST_CASE(streams_buffered_file)
323{
324 fs::path streams_test_filename = m_args.GetDataDirBase() / "streams_test_tmp";
325 AutoFile file{fsbridge::fopen(streams_test_filename, "w+b")};
326
327 // The value at each offset is the offset.
328 for (uint8_t j = 0; j < 40; ++j) {
329 file << j;
330 }
331 file.seek(0, SEEK_SET);
332
333 // The buffer size (second arg) must be greater than the rewind
334 // amount (third arg).
335 try {
336 BufferedFile bfbad{file, 25, 25};
337 BOOST_CHECK(false);
338 } catch (const std::exception& e) {
339 BOOST_CHECK(strstr(e.what(),
340 "Rewind limit must be less than buffer size") != nullptr);
341 }
342
343 // The buffer is 25 bytes, allow rewinding 10 bytes.
344 BufferedFile bf{file, 25, 10};
345 BOOST_CHECK(!bf.eof());
346
347 uint8_t i;
348 bf >> i;
349 BOOST_CHECK_EQUAL(i, 0);
350 bf >> i;
351 BOOST_CHECK_EQUAL(i, 1);
352
353 // After reading bytes 0 and 1, we're positioned at 2.
354 BOOST_CHECK_EQUAL(bf.GetPos(), 2U);
355
356 // Rewind to offset 0, ok (within the 10 byte window).
357 BOOST_CHECK(bf.SetPos(0));
358 bf >> i;
359 BOOST_CHECK_EQUAL(i, 0);
360
361 // We can go forward to where we've been, but beyond may fail.
362 BOOST_CHECK(bf.SetPos(2));
363 bf >> i;
364 BOOST_CHECK_EQUAL(i, 2);
365
366 // If you know the maximum number of bytes that should be
367 // read to deserialize the variable, you can limit the read
368 // extent. The current file offset is 3, so the following
369 // SetLimit() allows zero bytes to be read.
370 BOOST_CHECK(bf.SetLimit(3));
371 try {
372 bf >> i;
373 BOOST_CHECK(false);
374 } catch (const std::exception& e) {
375 BOOST_CHECK(strstr(e.what(),
376 "Attempt to position past buffer limit") != nullptr);
377 }
378 // The default argument removes the limit completely.
379 BOOST_CHECK(bf.SetLimit());
380 // The read position should still be at 3 (no change).
381 BOOST_CHECK_EQUAL(bf.GetPos(), 3U);
382
383 // Read from current offset, 3, forward until position 10.
384 for (uint8_t j = 3; j < 10; ++j) {
385 bf >> i;
386 BOOST_CHECK_EQUAL(i, j);
387 }
388 BOOST_CHECK_EQUAL(bf.GetPos(), 10U);
389
390 // We're guaranteed (just barely) to be able to rewind to zero.
391 BOOST_CHECK(bf.SetPos(0));
392 BOOST_CHECK_EQUAL(bf.GetPos(), 0U);
393 bf >> i;
394 BOOST_CHECK_EQUAL(i, 0);
395
396 // We can set the position forward again up to the farthest
397 // into the stream we've been, but no farther. (Attempting
398 // to go farther may succeed, but it's not guaranteed.)
399 BOOST_CHECK(bf.SetPos(10));
400 bf >> i;
401 BOOST_CHECK_EQUAL(i, 10);
402 BOOST_CHECK_EQUAL(bf.GetPos(), 11U);
403
404 // Now it's only guaranteed that we can rewind to offset 1
405 // (current read position, 11, minus rewind amount, 10).
406 BOOST_CHECK(bf.SetPos(1));
407 BOOST_CHECK_EQUAL(bf.GetPos(), 1U);
408 bf >> i;
409 BOOST_CHECK_EQUAL(i, 1);
410
411 // We can stream into large variables, even larger than
412 // the buffer size.
413 BOOST_CHECK(bf.SetPos(11));
414 {
415 uint8_t a[40 - 11];
416 bf >> a;
417 for (uint8_t j = 0; j < sizeof(a); ++j) {
418 BOOST_CHECK_EQUAL(a[j], 11 + j);
419 }
420 }
421 BOOST_CHECK_EQUAL(bf.GetPos(), 40U);
422
423 // We've read the entire file, the next read should throw.
424 try {
425 bf >> i;
426 BOOST_CHECK(false);
427 } catch (const std::exception& e) {
428 BOOST_CHECK(strstr(e.what(),
429 "BufferedFile::Fill: end of file") != nullptr);
430 }
431 // Attempting to read beyond the end sets the EOF indicator.
432 BOOST_CHECK(bf.eof());
433
434 // Still at offset 40, we can go back 10, to 30.
435 BOOST_CHECK_EQUAL(bf.GetPos(), 40U);
436 BOOST_CHECK(bf.SetPos(30));
437 bf >> i;
438 BOOST_CHECK_EQUAL(i, 30);
439 BOOST_CHECK_EQUAL(bf.GetPos(), 31U);
440
441 // We're too far to rewind to position zero.
442 BOOST_CHECK(!bf.SetPos(0));
443 // But we should now be positioned at least as far back as allowed
444 // by the rewind window (relative to our farthest read position, 40).
445 BOOST_CHECK(bf.GetPos() <= 30U);
446
447 BOOST_REQUIRE_EQUAL(file.fclose(), 0);
448
449 fs::remove(streams_test_filename);
450}
451
452BOOST_AUTO_TEST_CASE(streams_buffered_file_skip)
453{
454 fs::path streams_test_filename = m_args.GetDataDirBase() / "streams_test_tmp";
455 AutoFile file{fsbridge::fopen(streams_test_filename, "w+b")};
456 // The value at each offset is the byte offset (e.g. byte 1 in the file has the value 0x01).
457 for (uint8_t j = 0; j < 40; ++j) {
458 file << j;
459 }
460 file.seek(0, SEEK_SET);
461
462 // The buffer is 25 bytes, allow rewinding 10 bytes.
463 BufferedFile bf{file, 25, 10};
464
465 uint8_t i;
466 // This is like bf >> (7-byte-variable), in that it will cause data
467 // to be read from the file into memory, but it's not copied to us.
468 bf.SkipTo(7);
469 BOOST_CHECK_EQUAL(bf.GetPos(), 7U);
470 bf >> i;
471 BOOST_CHECK_EQUAL(i, 7);
472
473 // The bytes in the buffer up to offset 7 are valid and can be read.
474 BOOST_CHECK(bf.SetPos(0));
475 bf >> i;
476 BOOST_CHECK_EQUAL(i, 0);
477 bf >> i;
478 BOOST_CHECK_EQUAL(i, 1);
479
480 bf.SkipTo(11);
481 bf >> i;
482 BOOST_CHECK_EQUAL(i, 11);
483
484 // SkipTo() honors the transfer limit; we can't position beyond the limit.
485 bf.SetLimit(13);
486 try {
487 bf.SkipTo(14);
488 BOOST_CHECK(false);
489 } catch (const std::exception& e) {
490 BOOST_CHECK(strstr(e.what(), "Attempt to position past buffer limit") != nullptr);
491 }
492
493 // We can position exactly to the transfer limit.
494 bf.SkipTo(13);
495 BOOST_CHECK_EQUAL(bf.GetPos(), 13U);
496
497 BOOST_REQUIRE_EQUAL(file.fclose(), 0);
498 fs::remove(streams_test_filename);
499}
500
501BOOST_AUTO_TEST_CASE(streams_buffered_file_rand)
502{
503 // Make this test deterministic.
504 SeedRandomForTest(SeedRand::ZEROS);
505
506 fs::path streams_test_filename = m_args.GetDataDirBase() / "streams_test_tmp";
507 for (int rep = 0; rep < 50; ++rep) {
508 AutoFile file{fsbridge::fopen(streams_test_filename, "w+b")};
509 size_t fileSize = m_rng.randrange(256);
510 for (uint8_t i = 0; i < fileSize; ++i) {
511 file << i;
512 }
513 file.seek(0, SEEK_SET);
514
515 size_t bufSize = m_rng.randrange(300) + 1;
516 size_t rewindSize = m_rng.randrange(bufSize);
517 BufferedFile bf{file, bufSize, rewindSize};
518 size_t currentPos = 0;
519 size_t maxPos = 0;
520 for (int step = 0; step < 100; ++step) {
521 if (currentPos >= fileSize)
522 break;
523
524 // We haven't read to the end of the file yet.
525 BOOST_CHECK(!bf.eof());
526 BOOST_CHECK_EQUAL(bf.GetPos(), currentPos);
527
528 // Pretend the file consists of a series of objects of varying
529 // sizes; the boundaries of the objects can interact arbitrarily
530 // with the CBufferFile's internal buffer. These first three
531 // cases simulate objects of various sizes (1, 2, 5 bytes).
532 switch (m_rng.randrange(6)) {
533 case 0: {
534 uint8_t a[1];
535 if (currentPos + 1 > fileSize)
536 continue;
537 bf.SetLimit(currentPos + 1);
538 bf >> a;
539 for (uint8_t i = 0; i < 1; ++i) {
540 BOOST_CHECK_EQUAL(a[i], currentPos);
541 currentPos++;
542 }
543 break;
544 }
545 case 1: {
546 uint8_t a[2];
547 if (currentPos + 2 > fileSize)
548 continue;
549 bf.SetLimit(currentPos + 2);
550 bf >> a;
551 for (uint8_t i = 0; i < 2; ++i) {
552 BOOST_CHECK_EQUAL(a[i], currentPos);
553 currentPos++;
554 }
555 break;
556 }
557 case 2: {
558 uint8_t a[5];
559 if (currentPos + 5 > fileSize)
560 continue;
561 bf.SetLimit(currentPos + 5);
562 bf >> a;
563 for (uint8_t i = 0; i < 5; ++i) {
564 BOOST_CHECK_EQUAL(a[i], currentPos);
565 currentPos++;
566 }
567 break;
568 }
569 case 3: {
570 // SkipTo is similar to the "read" cases above, except
571 // we don't receive the data.
572 size_t skip_length{static_cast<size_t>(m_rng.randrange(5))};
573 if (currentPos + skip_length > fileSize) continue;
574 bf.SetLimit(currentPos + skip_length);
575 bf.SkipTo(currentPos + skip_length);
576 currentPos += skip_length;
577 break;
578 }
579 case 4: {
580 // Find a byte value (that is at or ahead of the current position).
581 size_t find = currentPos + m_rng.randrange(8);
582 if (find >= fileSize)
583 find = fileSize - 1;
584 bf.FindByte(std::byte(find));
585 // The value at each offset is the offset.
586 BOOST_CHECK_EQUAL(bf.GetPos(), find);
587 currentPos = find;
588
589 bf.SetLimit(currentPos + 1);
590 uint8_t i;
591 bf >> i;
592 BOOST_CHECK_EQUAL(i, currentPos);
593 currentPos++;
594 break;
595 }
596 case 5: {
597 size_t requestPos = m_rng.randrange(maxPos + 4);
598 bool okay = bf.SetPos(requestPos);
599 // The new position may differ from the requested position
600 // because we may not be able to rewind beyond the rewind
601 // window, and we may not be able to move forward beyond the
602 // farthest position we've reached so far.
603 currentPos = bf.GetPos();
604 BOOST_CHECK_EQUAL(okay, currentPos == requestPos);
605 // Check that we can position within the rewind window.
606 if (requestPos <= maxPos &&
607 maxPos > rewindSize &&
608 requestPos >= maxPos - rewindSize) {
609 // We requested a position within the rewind window.
610 BOOST_CHECK(okay);
611 }
612 break;
613 }
614 }
615 if (maxPos < currentPos)
616 maxPos = currentPos;
617 }
618 BOOST_REQUIRE_EQUAL(file.fclose(), 0);
619 }
620 fs::remove(streams_test_filename);
621}
622
623BOOST_AUTO_TEST_CASE(buffered_reader_matches_autofile_random_content)
624{
625 const size_t file_size{1 + m_rng.randrange<size_t>(1 << 17)};
626 const size_t buf_size{1 + m_rng.randrange(file_size)};
627 const FlatFilePos pos{0, 0};
628
629 const FlatFileSeq test_file{m_args.GetDataDirBase(), "buffered_file_test_random", node::BLOCKFILE_CHUNK_SIZE};
630 const Obfuscation obfuscation{m_rng.randbytes<Obfuscation::KEY_SIZE>()};
631
632 // Write out the file with random content
633 {
634 AutoFile f{test_file.Open(pos, /*read_only=*/false), obfuscation};
635 f.write(m_rng.randbytes<std::byte>(file_size));
636 BOOST_REQUIRE_EQUAL(f.fclose(), 0);
637 }
638 BOOST_CHECK_EQUAL(fs::file_size(test_file.FileName(pos)), file_size);
639
640 {
641 AutoFile direct_file{test_file.Open(pos, /*read_only=*/true), obfuscation};
642
643 AutoFile buffered_file{test_file.Open(pos, /*read_only=*/true), obfuscation};
644 BufferedReader buffered_reader{std::move(buffered_file), buf_size};
645
646 for (size_t total_read{0}; total_read < file_size;) {
647 const size_t read{Assert(std::min(1 + m_rng.randrange(m_rng.randbool() ? buf_size : 2 * buf_size), file_size - total_read))};
648
649 DataBuffer direct_file_buffer{read};
650 direct_file.read(direct_file_buffer);
651
652 DataBuffer buffered_buffer{read};
653 buffered_reader.read(buffered_buffer);
654
655 BOOST_CHECK_EQUAL_COLLECTIONS(
656 direct_file_buffer.begin(), direct_file_buffer.end(),
657 buffered_buffer.begin(), buffered_buffer.end()
658 );
659
660 total_read += read;
661 }
662
663 {
664 DataBuffer excess_byte{1};
665 BOOST_CHECK_EXCEPTION(direct_file.read(excess_byte), std::ios_base::failure, HasReason{"end of file"});
666 }
667
668 {
669 DataBuffer excess_byte{1};
670 BOOST_CHECK_EXCEPTION(buffered_reader.read(excess_byte), std::ios_base::failure, HasReason{"end of file"});
671 }
672 }
673
674 fs::remove(test_file.FileName(pos));
675}
676
677BOOST_AUTO_TEST_CASE(buffered_writer_matches_autofile_random_content)
678{
679 const size_t file_size{1 + m_rng.randrange<size_t>(1 << 17)};
680 const size_t buf_size{1 + m_rng.randrange(file_size)};
681 const FlatFilePos pos{0, 0};
682
683 const FlatFileSeq test_buffered{m_args.GetDataDirBase(), "buffered_write_test", node::BLOCKFILE_CHUNK_SIZE};
684 const FlatFileSeq test_direct{m_args.GetDataDirBase(), "direct_write_test", node::BLOCKFILE_CHUNK_SIZE};
685 const Obfuscation obfuscation{m_rng.randbytes<Obfuscation::KEY_SIZE>()};
686
687 {
688 DataBuffer test_data{m_rng.randbytes<std::byte>(file_size)};
689
690 AutoFile direct_file{test_direct.Open(pos, /*read_only=*/false), obfuscation};
691
692 AutoFile buffered_file{test_buffered.Open(pos, /*read_only=*/false), obfuscation};
693 {
694 BufferedWriter buffered{buffered_file, buf_size};
695
696 for (size_t total_written{0}; total_written < file_size;) {
697 const size_t write_size{Assert(std::min(1 + m_rng.randrange(m_rng.randbool() ? buf_size : 2 * buf_size), file_size - total_written))};
698
699 auto current_span = std::span{test_data}.subspan(total_written, write_size);
700 direct_file.write(current_span);
701 buffered.write(current_span);
702
703 total_written += write_size;
704 }
705 }
706 BOOST_REQUIRE_EQUAL(buffered_file.fclose(), 0);
707 BOOST_REQUIRE_EQUAL(direct_file.fclose(), 0);
708 }
709
710 // Compare the resulting files
711 DataBuffer direct_result{file_size};
712 {
713 AutoFile verify_direct{test_direct.Open(pos, /*read_only=*/true), obfuscation};
714 verify_direct.read(direct_result);
715
716 DataBuffer excess_byte{1};
717 BOOST_CHECK_EXCEPTION(verify_direct.read(excess_byte), std::ios_base::failure, HasReason{"end of file"});
718 }
719
720 DataBuffer buffered_result{file_size};
721 {
722 AutoFile verify_buffered{test_buffered.Open(pos, /*read_only=*/true), obfuscation};
723 verify_buffered.read(buffered_result);
724
725 DataBuffer excess_byte{1};
726 BOOST_CHECK_EXCEPTION(verify_buffered.read(excess_byte), std::ios_base::failure, HasReason{"end of file"});
727 }
728
729 BOOST_CHECK_EQUAL_COLLECTIONS(
730 direct_result.begin(), direct_result.end(),
731 buffered_result.begin(), buffered_result.end()
732 );
733
734 fs::remove(test_direct.FileName(pos));
735 fs::remove(test_buffered.FileName(pos));
736}
737
738BOOST_AUTO_TEST_CASE(buffered_writer_reader)
739{
740 const uint32_t v1{m_rng.rand32()}, v2{m_rng.rand32()}, v3{m_rng.rand32()};
741 const fs::path test_file{m_args.GetDataDirBase() / "test_buffered_write_read.bin"};
742
743 // Write out the values through a precisely sized BufferedWriter
744 AutoFile file{fsbridge::fopen(test_file, "w+b")};
745 {
746 BufferedWriter f(file, sizeof(v1) + sizeof(v2) + sizeof(v3));
747 f << v1 << v2;
748 f.write(std::as_bytes(std::span{&v3, 1}));
749 }
750 BOOST_REQUIRE_EQUAL(file.fclose(), 0);
751
752 // Read back and verify using BufferedReader
753 {
754 uint32_t _v1{0}, _v2{0}, _v3{0};
755 AutoFile file{fsbridge::fopen(test_file, "rb")};
756 BufferedReader f(std::move(file), sizeof(v1) + sizeof(v2) + sizeof(v3));
757 f >> _v1 >> _v2;
758 f.read(std::as_writable_bytes(std::span{&_v3, 1}));
759 BOOST_CHECK_EQUAL(_v1, v1);
760 BOOST_CHECK_EQUAL(_v2, v2);
761 BOOST_CHECK_EQUAL(_v3, v3);
762
763 DataBuffer excess_byte{1};
764 BOOST_CHECK_EXCEPTION(f.read(excess_byte), std::ios_base::failure, HasReason{"end of file"});
765 }
766
767 fs::remove(test_file);
768}
769
770BOOST_AUTO_TEST_CASE(streams_hashed)
771{
772 DataStream stream{};
773 HashedSourceWriter hash_writer{stream};
774 const std::string data{"bitcoin"};
775 hash_writer << data;
776
777 HashVerifier hash_verifier{stream};
778 std::string result;
779 hash_verifier >> result;
780 BOOST_CHECK_EQUAL(data, result);
781 BOOST_CHECK_EQUAL(hash_writer.GetHash(), hash_verifier.GetHash());
782}
783
#define Assert(val)
Identity function.
Definition: check.h:106
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:371
void ignore(size_t nSize)
Definition: streams.cpp:67
void write(std::span< const std::byte > src)
Definition: streams.cpp:81
void read(std::span< std::byte > dst)
Definition: streams.cpp:60
Wrapper around an AutoFile& that implements a ring buffer to deserialize from.
Definition: streams.h:478
void SkipTo(const uint64_t file_pos)
Move the read position ahead in the stream to the given position.
Definition: streams.h:551
Wrapper that buffers reads from an underlying stream.
Definition: streams.h:625
void read(std::span< std::byte > dst)
Definition: streams.h:636
Wrapper that buffers writes to an underlying stream.
Definition: streams.h:667
void write(std::span< const std::byte > src)
Definition: streams.h:683
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:130
size_type size() const
Definition: streams.h:164
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:46
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: setup_common.h:304
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:151
Writes data to an underlying source stream, while hashing the written data.
Definition: hash.h:185
static constexpr size_t KEY_SIZE
Definition: obfuscation.h:23
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
const std::string test1
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
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:29
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:26
static const unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:71
""_hex is a compile-time user-defined literal returning a std::array<std::byte>, equivalent to ParseH...
Definition: strencodings.h:384
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition: object.cpp:19
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
#define VARINT(obj)
Definition: serialize.h:491
std::vector< std::byte > DataBuffer
Definition: streams.h:469
BOOST_AUTO_TEST_CASE(xor_random_chunks)
Basic testing setup.
Definition: setup_common.h:64
@ ZEROS
Seed with a compile time constant of zeros.