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