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