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