Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #ifndef BITCOIN_STREAMS_H
7 : : #define BITCOIN_STREAMS_H
8 : :
9 : : #include <logging.h>
10 : : #include <serialize.h>
11 : : #include <span.h>
12 : : #include <support/allocators/zeroafterfree.h>
13 : : #include <util/check.h>
14 : : #include <util/overflow.h>
15 : : #include <util/syserror.h>
16 : :
17 : : #include <algorithm>
18 : : #include <cassert>
19 : : #include <cstddef>
20 : : #include <cstdint>
21 : : #include <cstdio>
22 : : #include <cstring>
23 : : #include <ios>
24 : : #include <limits>
25 : : #include <optional>
26 : : #include <string>
27 : : #include <utility>
28 : : #include <vector>
29 : :
30 : : namespace util {
31 : 18150359 : inline void Xor(std::span<std::byte> write, std::span<const std::byte> key, size_t key_offset = 0)
32 : : {
33 [ + - ]: 18150359 : if (key.size() == 0) {
34 : : return;
35 : : }
36 : 18150359 : key_offset %= key.size();
37 : :
38 [ + + ]: 2324696429 : for (size_t i = 0, j = key_offset; i != write.size(); i++) {
39 [ + + ]: 2306546070 : write[i] ^= key[j++];
40 : :
41 : : // This potentially acts on very many bytes of data, so it's
42 : : // important that we calculate `j`, i.e. the `key` index in this
43 : : // way instead of doing a %, which would effectively be a division
44 : : // for each byte Xor'd -- much slower than need be.
45 [ + + ]: 2306546070 : if (j == key.size())
46 : 282744547 : j = 0;
47 : : }
48 : : }
49 : : } // namespace util
50 : :
51 : : /* Minimal stream for overwriting and/or appending to an existing byte vector
52 : : *
53 : : * The referenced vector will grow as necessary
54 : : */
55 : : class VectorWriter
56 : : {
57 : : public:
58 : : /*
59 : : * @param[in] vchDataIn Referenced byte vector to overwrite/append
60 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
61 : : * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
62 : : */
63 : 747700 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
64 : : {
65 [ - + ]: 747700 : if(nPos > vchData.size())
66 : 0 : vchData.resize(nPos);
67 : 747700 : }
68 : : /*
69 : : * (other params same as above)
70 : : * @param[in] args A list of items to serialize starting at nPosIn.
71 : : */
72 : : template <typename... Args>
73 [ + - ][ + - : 655881 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - + - ]
[ + - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
- - + - +
- + - -
- ]
74 : : {
75 [ + - ][ + - : 655881 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - + - ]
[ + - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
- - + - +
- + - -
- ]
76 : 230382 : }
77 : 8396721 : void write(std::span<const std::byte> src)
78 : : {
79 [ - + ]: 8396721 : assert(nPos <= vchData.size());
80 [ + + ]: 8396721 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
81 [ - + ]: 8396721 : if (nOverwrite) {
82 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
83 : : }
84 [ + + ]: 8396721 : if (nOverwrite < src.size()) {
85 : 8356975 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
86 : : }
87 : 8396721 : nPos += src.size();
88 : 8396721 : }
89 : : template <typename T>
90 : 1513807 : VectorWriter& operator<<(const T& obj)
91 : : {
92 [ + - + - : 1513807 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - +
- ]
93 : 120131 : return (*this);
94 : : }
95 : :
96 : : private:
97 : : std::vector<unsigned char>& vchData;
98 : : size_t nPos;
99 : : };
100 : :
101 : : /** Minimal stream for reading from an existing byte array by std::span.
102 : : */
103 : : class SpanReader
104 : : {
105 : : private:
106 : : std::span<const std::byte> m_data;
107 : :
108 : : public:
109 : : /**
110 : : * @param[in] data Referenced byte vector to overwrite/append
111 : : */
112 : 790283 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
113 [ + - ]: 6691 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
114 : :
115 : : template<typename T>
116 : 3547330 : SpanReader& operator>>(T&& obj)
117 : : {
118 [ + + + + : 3524524 : ::Unserialize(*this, obj);
+ + + + +
+ + + + -
+ - + - +
+ + - + -
+ + + - +
+ + - + -
+ + + - +
+ + + + +
+ - + - +
+ + - + +
+ - + - +
- + - + +
+ + + - +
+ + + ][ +
- + - + +
+ + + + +
- + - + -
+ + + + ]
[ + + + +
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
[ + - ]
119 : 982805 : return (*this);
120 : : }
121 : :
122 [ + + ]: 89662 : size_t size() const { return m_data.size(); }
123 [ - + - + : 206865 : bool empty() const { return m_data.empty(); }
# # # # ]
[ + + + +
+ + + + ]
[ + + ]
124 : :
125 : 4687041 : void read(std::span<std::byte> dst)
126 : : {
127 [ + - ]: 4687041 : if (dst.size() == 0) {
128 : : return;
129 : : }
130 : :
131 : : // Read from the beginning of the buffer
132 [ + + ]: 4687041 : if (dst.size() > m_data.size()) {
133 [ + - ]: 57347 : throw std::ios_base::failure("SpanReader::read(): end of data");
134 : : }
135 : 4629694 : memcpy(dst.data(), m_data.data(), dst.size());
136 : 4629694 : m_data = m_data.subspan(dst.size());
137 : : }
138 : :
139 : : void ignore(size_t n)
140 : : {
141 : : m_data = m_data.subspan(n);
142 : : }
143 : : };
144 : :
145 : : /** Double ended buffer combining vector and stream-like interfaces.
146 : : *
147 : : * >> and << read and write unformatted data using the above serialization templates.
148 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
149 : : */
150 [ + - + - : 41971393 : class DataStream
+ + ][ + - ]
[ + + + + ]
151 : : {
152 : : protected:
153 : : using vector_type = SerializeData;
154 : : vector_type vch;
155 : : vector_type::size_type m_read_pos{0};
156 : :
157 : : public:
158 : : typedef vector_type::allocator_type allocator_type;
159 : : typedef vector_type::size_type size_type;
160 : : typedef vector_type::difference_type difference_type;
161 : : typedef vector_type::reference reference;
162 : : typedef vector_type::const_reference const_reference;
163 : : typedef vector_type::value_type value_type;
164 : : typedef vector_type::iterator iterator;
165 : : typedef vector_type::const_iterator const_iterator;
166 : : typedef vector_type::reverse_iterator reverse_iterator;
167 : :
168 [ + - ]: 2860969 : explicit DataStream() = default;
169 : 1430922 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
170 : 17098192 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
171 : :
172 : 329 : std::string str() const
173 : : {
174 : 658 : return std::string{UCharCast(data()), UCharCast(data() + size())};
175 : : }
176 : :
177 : :
178 : : //
179 : : // Vector subset
180 : : //
181 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
182 : 1462187 : iterator begin() { return vch.begin() + m_read_pos; }
183 : : const_iterator end() const { return vch.end(); }
184 [ + - ]: 765713 : iterator end() { return vch.end(); }
[ # # # # ]
185 [ + + + + : 30879694 : size_type size() const { return vch.size() - m_read_pos; }
# # # # #
# # # # #
# # # # #
# # # #
# ][ + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - + - +
- ][ + - -
+ + - ][ #
# # # # #
# # ][ + + ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - -
- # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # ]
186 [ - + - + : 1680743 : bool empty() const { return vch.size() == m_read_pos; }
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + ][ + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # ][ +
+ + + + +
+ + + + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + ]
[ # # ][ + +
+ + + + +
+ ][ - - -
- - - - -
- - + + ]
187 : 590214 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
188 [ # # # # ]: 19499077 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
[ + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - ][ + -
+ - + - +
- + - ][ +
- + - + -
+ - + - +
- + - -
- ][ # # #
# # # # #
# # # # ]
[ + - # #
# # # # #
# # # # #
# # ]
189 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
190 [ + + ]: 4505949 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
191 [ # # # # : 21306118 : void clear() { vch.clear(); m_read_pos = 0; }
# # # # ]
[ + + + +
# # # # ]
[ # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- - - ][ #
# # # # #
# # # # #
# # # #
# ]
192 [ + - + - : 26105183 : value_type* data() { return vch.data() + m_read_pos; }
+ - + - ]
[ + - ]
[ + - + - ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - -
- # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
193 : 90971 : const value_type* data() const { return vch.data() + m_read_pos; }
194 : :
195 : : inline void Compact()
196 : : {
197 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
198 : : m_read_pos = 0;
199 : : }
200 : :
201 : : bool Rewind(std::optional<size_type> n = std::nullopt)
202 : : {
203 : : // Total rewind if no size is passed
204 : : if (!n) {
205 : : m_read_pos = 0;
206 : : return true;
207 : : }
208 : : // Rewind by n characters if the buffer hasn't been compacted yet
209 : : if (*n > m_read_pos)
210 : : return false;
211 : : m_read_pos -= *n;
212 : : return true;
213 : : }
214 : :
215 : :
216 : : //
217 : : // Stream subset
218 : : //
219 [ # # ]: 0 : bool eof() const { return size() == 0; }
220 [ + + ]: 425 : int in_avail() const { return size(); }
221 : :
222 : 483196388 : void read(std::span<value_type> dst)
223 : : {
224 [ + + ]: 483196388 : if (dst.size() == 0) return;
225 : :
226 : : // Read from the beginning of the buffer
227 [ + - ]: 478830653 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
228 [ + - + + ]: 478830653 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
229 [ + - ]: 259905 : throw std::ios_base::failure("DataStream::read(): end of data");
230 : : }
231 [ + + ]: 478570748 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
232 [ + + ]: 478570748 : if (next_read_pos.value() == vch.size()) {
233 : 30814107 : m_read_pos = 0;
234 [ + - ]: 30814107 : vch.clear();
235 : 30814107 : return;
236 : : }
237 : 447756641 : m_read_pos = next_read_pos.value();
238 : : }
239 : :
240 : 1456161 : void ignore(size_t num_ignore)
241 : : {
242 : : // Ignore from the beginning of the buffer
243 : 1456161 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
244 [ + - + + ]: 1456161 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
245 [ + - ]: 2990 : throw std::ios_base::failure("DataStream::ignore(): end of data");
246 : : }
247 [ + + ]: 1453171 : if (next_read_pos.value() == vch.size()) {
248 : 1295 : m_read_pos = 0;
249 [ + + ]: 1295 : vch.clear();
250 : 1295 : return;
251 : : }
252 : 1451876 : m_read_pos = next_read_pos.value();
253 : : }
254 : :
255 : 273955812 : void write(std::span<const value_type> src)
256 : : {
257 : : // Write to the end of the buffer
258 : 273955812 : vch.insert(vch.end(), src.begin(), src.end());
259 : 273955812 : }
260 : :
261 : : template<typename T>
262 : 87721180 : DataStream& operator<<(const T& obj)
263 : : {
264 [ + - + - : 79671963 : ::Serialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # ][ - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - ]
[ + - + -
+ - + - +
- ][ + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
265 : 13993905 : return (*this);
266 : : }
267 : :
268 : : template<typename T>
269 : 73583335 : DataStream& operator>>(T&& obj)
270 : : {
271 [ + + ][ + + : 73531658 : ::Unserialize(*this, obj);
+ + + + ]
[ + - + +
+ - + - +
- ][ + + +
+ + + + +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
- + + + +
+ + + + ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - +
+ ][ + + +
+ # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ -
- + - + +
- - + + +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
+ + + + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
+ - - - -
- - ][ - -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - - -
- - - + -
+ - + - +
- + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
272 : 34802914 : return (*this);
273 : : }
274 : :
275 : : /**
276 : : * XOR the contents of this stream with a certain key.
277 : : *
278 : : * @param[in] key The key used to XOR the data in this stream.
279 : : */
280 : 17156486 : void Xor(const std::vector<unsigned char>& key)
281 : : {
282 : 17156486 : util::Xor(MakeWritableByteSpan(*this), MakeByteSpan(key));
283 : 17156486 : }
284 : :
285 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
286 : : size_t GetMemoryUsage() const noexcept;
287 : : };
288 : :
289 : : template <typename IStream>
290 : : class BitStreamReader
291 : : {
292 : : private:
293 : : IStream& m_istream;
294 : :
295 : : /// Buffered byte read in from the input stream. A new byte is read into the
296 : : /// buffer when m_offset reaches 8.
297 : : uint8_t m_buffer{0};
298 : :
299 : : /// Number of high order bits in m_buffer already returned by previous
300 : : /// Read() calls. The next bit to be returned is at this offset from the
301 : : /// most significant bit position.
302 : : int m_offset{8};
303 : :
304 : : public:
305 [ + - ]: 1766 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
306 : :
307 : : /** Read the specified number of bits from the stream. The data is returned
308 : : * in the nbits least significant bits of a 64-bit uint.
309 : : */
310 : 2182082 : uint64_t Read(int nbits) {
311 [ + - ]: 2182082 : if (nbits < 0 || nbits > 64) {
312 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
313 : : }
314 : :
315 : : uint64_t data = 0;
316 [ + + ]: 6402824 : while (nbits > 0) {
317 [ + + ]: 4240726 : if (m_offset == 8) {
318 : 2472299 : m_istream >> m_buffer;
319 : 2452315 : m_offset = 0;
320 : : }
321 : :
322 [ + + ]: 4220742 : int bits = std::min(8 - m_offset, nbits);
323 : 4220742 : data <<= bits;
324 : 4220742 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
325 : 4220742 : m_offset += bits;
326 : 4220742 : nbits -= bits;
327 : : }
328 : 2162098 : return data;
329 : : }
330 : : };
331 : :
332 : : template <typename OStream>
333 : : class BitStreamWriter
334 : : {
335 : : private:
336 : : OStream& m_ostream;
337 : :
338 : : /// Buffered byte waiting to be written to the output stream. The byte is
339 : : /// written buffer when m_offset reaches 8 or Flush() is called.
340 : : uint8_t m_buffer{0};
341 : :
342 : : /// Number of high order bits in m_buffer already written by previous
343 : : /// Write() calls and not yet flushed to the stream. The next bit to be
344 : : /// written to is at this offset from the most significant bit position.
345 : : int m_offset{0};
346 : :
347 : : public:
348 [ + + ]: 281 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
349 : :
350 : 281 : ~BitStreamWriter()
351 : : {
352 : 281 : Flush();
353 : 281 : }
354 : :
355 : : /** Write the nbits least significant bits of a 64-bit int to the output
356 : : * stream. Data is buffered until it completes an octet.
357 : : */
358 : 85094 : void Write(uint64_t data, int nbits) {
359 [ + - ]: 85094 : if (nbits < 0 || nbits > 64) {
360 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
361 : : }
362 : :
363 [ + + ]: 248645 : while (nbits > 0) {
364 [ + + ]: 163551 : int bits = std::min(8 - m_offset, nbits);
365 : 163551 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
366 : 163551 : m_offset += bits;
367 : 163551 : nbits -= bits;
368 : :
369 [ + + ]: 163551 : if (m_offset == 8) {
370 : 89197 : Flush();
371 : : }
372 : : }
373 : 85094 : }
374 : :
375 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
376 : : * next byte boundary.
377 : : */
378 : 89759 : void Flush() {
379 [ + + ]: 89759 : if (m_offset == 0) {
380 : : return;
381 : : }
382 : :
383 : 89405 : m_ostream << m_buffer;
384 : 89405 : m_buffer = 0;
385 : 89405 : m_offset = 0;
386 : : }
387 : : };
388 : :
389 : : /** Non-refcounted RAII wrapper for FILE*
390 : : *
391 : : * Will automatically close the file when it goes out of scope if not null.
392 : : * If you're returning the file pointer, return file.release().
393 : : * If you need to close the file early, use autofile.fclose() instead of fclose(underlying_FILE).
394 : : *
395 : : * @note If the file has been written to, then the caller must close it
396 : : * explicitly with the `fclose()` method, check if it returns an error and treat
397 : : * such an error as if the `write()` method failed. The OS's `fclose(3)` may
398 : : * fail to flush to disk data that has been previously written, rendering the
399 : : * file corrupt.
400 : : */
401 : : class AutoFile
402 : : {
403 : : protected:
404 : : std::FILE* m_file;
405 : : std::vector<std::byte> m_xor;
406 : : std::optional<int64_t> m_position;
407 : : bool m_was_written{false};
408 : :
409 : : public:
410 : : explicit AutoFile(std::FILE* file, std::vector<std::byte> data_xor={});
411 : :
412 : 233085 : ~AutoFile()
413 : : {
414 [ + + ]: 233085 : if (m_was_written) {
415 : : // Callers that wrote to the file must have closed it explicitly
416 : : // with the fclose() method and checked that the close succeeded.
417 : : // This is because here in the destructor we have no way to signal
418 : : // errors from fclose() which, after write, could mean the file is
419 : : // corrupted and must be handled properly at the call site.
420 : : // Destructors in C++ cannot signal an error to the callers because
421 : : // they do not return a value and are not allowed to throw exceptions.
422 : 195898 : Assume(IsNull());
423 : : }
424 : :
425 [ + + ]: 12060 : if (fclose() != 0) {
426 : 2312 : LogError("Failed to close file: %s", SysErrorString(errno));
427 : : }
428 : 233085 : }
429 : :
430 : : // Disallow copies
431 : : AutoFile(const AutoFile&) = delete;
432 : : AutoFile& operator=(const AutoFile&) = delete;
433 : :
434 : 12349 : bool feof() const { return std::feof(m_file); }
435 : :
436 : 432095 : [[nodiscard]] int fclose()
437 : : {
438 [ + - ]: 210337 : if (auto rel{release()}) return std::fclose(rel);
[ + - + - ]
[ + - + -
+ - ]
439 : : return 0;
440 : : }
441 : :
442 : : /** Get wrapped FILE* with transfer of ownership.
443 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
444 : : * of this function to clean up the returned FILE*.
445 : : */
446 : 432149 : std::FILE* release()
447 : : {
448 : 432149 : std::FILE* ret{m_file};
449 : 432149 : m_file = nullptr;
450 [ + - - - ]: 432149 : return ret;
[ # # # #
# # ][ + +
+ + + + ]
[ + - + -
+ - - - ]
[ # # # #
# # # # #
# ]
451 : : }
452 : :
453 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
454 : : */
455 [ + + ]: 655208 : bool IsNull() const { return m_file == nullptr; }
[ + + + + ]
[ # # # #
# # # # #
# # # ][ -
- - - - +
+ + - + -
- ]
456 : :
457 : : /** Continue with a different XOR key */
458 [ + - + - ]: 1625 : void SetXor(std::vector<std::byte> data_xor) { m_xor = data_xor; }
459 : :
460 : : /** Implementation detail, only used internally. */
461 : : std::size_t detail_fread(std::span<std::byte> dst);
462 : :
463 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
464 : : void seek(int64_t offset, int origin);
465 : :
466 : : /** Find position within the file. Will throw if unknown. */
467 : : int64_t tell();
468 : :
469 : : /** Wrapper around FileCommit(). */
470 : : bool Commit();
471 : :
472 : : /** Wrapper around TruncateFile(). */
473 : : bool Truncate(unsigned size);
474 : :
475 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
476 : : void write_buffer(std::span<std::byte> src);
477 : :
478 : : //
479 : : // Stream subset
480 : : //
481 : : void read(std::span<std::byte> dst);
482 : : void ignore(size_t nSize);
483 : : void write(std::span<const std::byte> src);
484 : :
485 : : template <typename T>
486 : 1391913 : AutoFile& operator<<(const T& obj)
487 : : {
488 [ + - ][ - - : 1386326 : ::Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ + + + + ]
[ + + + -
+ + + - +
- + - + +
+ - ][ # #
# # # # #
# ][ # # #
# # # #
# ]
489 : 334428 : return *this;
490 : : }
491 : :
492 : : template <typename T>
493 : 3369420 : AutoFile& operator>>(T&& obj)
494 : : {
495 [ + + + + ]: 3356973 : ::Unserialize(*this, obj);
[ # # ][ - -
+ + + + +
+ + - + +
+ + + - +
- - - + -
- - - - ]
[ + - + -
+ - ][ + +
+ + + + +
+ + + + +
+ + + + ]
[ + + + +
+ + + + ]
[ + + + +
+ + + + +
+ + + ]
496 : 1685069 : return *this;
497 : : }
498 : : };
499 : :
500 : : using DataBuffer = std::vector<std::byte>;
501 : :
502 : : /** Wrapper around an AutoFile& that implements a ring buffer to
503 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
504 : : *
505 : : * Will automatically close the file when it goes out of scope if not null.
506 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
507 : : */
508 : 914 : class BufferedFile
509 : : {
510 : : private:
511 : : AutoFile& m_src;
512 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
513 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
514 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
515 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
516 : : DataBuffer vchBuf;
517 : :
518 : : //! read data from the source to fill the buffer
519 : 400947 : bool Fill() {
520 [ + + ]: 400947 : unsigned int pos = nSrcPos % vchBuf.size();
521 : 400947 : unsigned int readNow = vchBuf.size() - pos;
522 : 400947 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
523 [ + + ]: 400947 : if (nAvail < readNow)
524 : 360955 : readNow = nAvail;
525 [ + - ]: 400947 : if (readNow == 0)
526 : : return false;
527 : 400947 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
528 [ + + ]: 400719 : if (nBytes == 0) {
529 [ + + + - ]: 7258 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
530 : : }
531 : 396181 : nSrcPos += nBytes;
532 : 396181 : return true;
533 : : }
534 : :
535 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
536 : : //! filling the buffer from the file so that at least one byte is available.
537 : : //! Return a pointer to the available buffer data and the number of bytes
538 : : //! (which may be less than the requested length) that may be accessed
539 : : //! beginning at that pointer.
540 : 6710958 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
541 : : {
542 [ - + ]: 6710958 : assert(m_read_pos <= nSrcPos);
543 [ + + ]: 6710958 : if (m_read_pos + length > nReadLimit) {
544 [ + - ]: 26897 : throw std::ios_base::failure("Attempt to position past buffer limit");
545 : : }
546 : : // If there are no bytes available, read from the file.
547 [ + + + - ]: 6684061 : if (m_read_pos == nSrcPos && length > 0) Fill();
548 : :
549 : 6680098 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
550 : 6680098 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
551 : 6680098 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
552 : 6680098 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
553 : 6680098 : m_read_pos += advance;
554 : 6680098 : return std::make_pair(&vchBuf[buffer_offset], advance);
555 : : }
556 : :
557 : : public:
558 : 940 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
559 : 940 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
560 : : {
561 [ + + ]: 940 : if (nRewindIn >= nBufSize)
562 [ + - ]: 26 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
563 : 940 : }
564 : :
565 : : //! check whether we're at the end of the source file
566 : 1499638 : bool eof() const {
567 [ + + + + ]: 1499638 : return m_read_pos == nSrcPos && m_src.feof();
568 : : }
569 : :
570 : : //! read a number of bytes
571 : 6220205 : void read(std::span<std::byte> dst)
572 : : {
573 [ + + ]: 12583266 : while (dst.size() > 0) {
574 : 6392317 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
575 : 6363061 : memcpy(dst.data(), buffer_pointer, length);
576 : 6363061 : dst = dst.subspan(length);
577 : : }
578 : 6190949 : }
579 : :
580 : : //! Move the read position ahead in the stream to the given position.
581 : : //! Use SetPos() to back up in the stream, not SkipTo().
582 : 319663 : void SkipTo(const uint64_t file_pos)
583 : : {
584 [ + - ]: 319663 : assert(file_pos >= m_read_pos);
585 [ + + ]: 636700 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
586 : 318059 : }
587 : :
588 : : //! return the current reading position
589 : 1892536 : uint64_t GetPos() const {
590 [ + + + + : 1892536 : return m_read_pos;
+ - ]
591 : : }
592 : :
593 : : //! rewind to a given reading position
594 : 1612842 : bool SetPos(uint64_t nPos) {
595 [ + + ]: 1612842 : size_t bufsize = vchBuf.size();
596 [ + + ]: 1612842 : if (nPos + bufsize < nSrcPos) {
597 : : // rewinding too far, rewind as far as possible
598 : 466 : m_read_pos = nSrcPos - bufsize;
599 : 466 : return false;
600 : : }
601 [ + + ]: 1612376 : if (nPos > nSrcPos) {
602 : : // can't go this far forward, go as far as possible
603 : 1680 : m_read_pos = nSrcPos;
604 : 1680 : return false;
605 : : }
606 : 1610696 : m_read_pos = nPos;
607 : 1610696 : return true;
608 : : }
609 : :
610 : : //! prevent reading beyond a certain position
611 : : //! no argument removes the limit
612 : 1821070 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
613 [ + + ]: 321691 : if (nPos < m_read_pos)
614 : : return false;
615 : 1820559 : nReadLimit = nPos;
616 [ + + ]: 1820559 : return true;
617 : : }
618 : :
619 : : template<typename T>
620 : 2330645 : BufferedFile& operator>>(T&& obj) {
621 [ + + + + ]: 2330645 : ::Unserialize(*this, obj);
[ + + + +
+ + + + ]
622 : 2268640 : return (*this);
623 : : }
624 : :
625 : : //! search for a given byte in the stream, and remain positioned on it
626 : 1501101 : void FindByte(std::byte byte)
627 : : {
628 : : // For best performance, avoid mod operation within the loop.
629 : 1501101 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
630 : 1717370 : while (true) {
631 [ + + ]: 1717370 : if (m_read_pos == nSrcPos) {
632 : : // No more bytes available; read from the file into the buffer,
633 : : // setting nSrcPos to one beyond the end of the new data.
634 : : // Throws exception if end-of-file reached.
635 : 218832 : Fill();
636 : : }
637 [ + + ]: 1716567 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
638 [ + + ]: 1716567 : const auto it_start{vchBuf.begin() + buf_offset};
639 : 1716567 : const auto it_find{std::find(it_start, it_start + len, byte)};
640 [ + + ]: 1716567 : const size_t inc{size_t(std::distance(it_start, it_find))};
641 : 1716567 : m_read_pos += inc;
642 [ + + ]: 1716567 : if (inc < len) break;
643 : 216269 : buf_offset += inc;
644 [ + + ]: 216269 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
645 : : }
646 : 1500298 : }
647 : : };
648 : :
649 : : /**
650 : : * Wrapper that buffers reads from an underlying stream.
651 : : * Requires underlying stream to support read() and detail_fread() calls
652 : : * to support fixed-size and variable-sized reads, respectively.
653 : : */
654 : : template <typename S>
655 : 0 : class BufferedReader
656 : : {
657 : : S& m_src;
658 : : DataBuffer m_buf;
659 : : size_t m_buf_pos;
660 : :
661 : : public:
662 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
663 : 0 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
664 : : requires std::is_rvalue_reference_v<S&&>
665 [ # # # # ]: 0 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
666 : :
667 : 0 : void read(std::span<std::byte> dst)
668 : : {
669 [ # # # # ]: 0 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
670 : 0 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
671 : 0 : m_buf_pos += available;
672 : 0 : dst = dst.subspan(available);
673 : : }
674 [ # # ]: 0 : if (dst.size()) {
675 [ # # ]: 0 : assert(m_buf_pos == m_buf.size());
676 : 0 : m_src.read(dst);
677 : :
678 : 0 : m_buf_pos = 0;
679 : 0 : m_buf.resize(m_src.detail_fread(m_buf));
680 : : }
681 : 0 : }
682 : :
683 : : template <typename T>
684 : 0 : BufferedReader& operator>>(T&& obj)
685 : : {
686 [ # # ]: 0 : Unserialize(*this, obj);
687 : 0 : return *this;
688 : : }
689 : : };
690 : :
691 : : /**
692 : : * Wrapper that buffers writes to an underlying stream.
693 : : * Requires underlying stream to support write_buffer() method
694 : : * for efficient buffer flushing and obfuscation.
695 : : */
696 : : template <typename S>
697 : : class BufferedWriter
698 : : {
699 : : S& m_dst;
700 : : DataBuffer m_buf;
701 : : size_t m_buf_pos{0};
702 : :
703 : : public:
704 [ + - + - : 192739 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
705 : :
706 [ + - + - ]: 192739 : ~BufferedWriter() { flush(); }
707 : :
708 : 192739 : void flush()
709 : : {
710 [ + - ]: 192739 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
711 : 192739 : m_buf_pos = 0;
712 : 192739 : }
713 : :
714 : 3515621 : void write(std::span<const std::byte> src)
715 : : {
716 [ + - + + ]: 14062484 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
717 : 3515621 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
718 : 3515621 : m_buf_pos += available;
719 [ - + ]: 3515621 : if (m_buf_pos == m_buf.size()) flush();
720 : 3515621 : src = src.subspan(available);
721 : : }
722 : 3515621 : }
723 : :
724 : : template <typename T>
725 : 760067 : BufferedWriter& operator<<(const T& obj)
726 : : {
727 [ - - + - : 567328 : Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- ]
728 : 386766 : return *this;
729 : : }
730 : : };
731 : :
732 : : #endif // BITCOIN_STREAMS_H
|