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/obfuscation.h>
15 : : #include <util/overflow.h>
16 : : #include <util/syserror.h>
17 : :
18 : : #include <algorithm>
19 : : #include <cassert>
20 : : #include <cstddef>
21 : : #include <cstdint>
22 : : #include <cstdio>
23 : : #include <cstring>
24 : : #include <ios>
25 : : #include <limits>
26 : : #include <optional>
27 : : #include <string>
28 : : #include <vector>
29 : :
30 : : /* Minimal stream for overwriting and/or appending to an existing byte vector
31 : : *
32 : : * The referenced vector will grow as necessary
33 : : */
34 : : class VectorWriter
35 : : {
36 : : public:
37 : : /*
38 : : * @param[in] vchDataIn Referenced byte vector to overwrite/append
39 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
40 : : * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
41 : : */
42 : 870462 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
43 : : {
44 [ - + ]: 870462 : if(nPos > vchData.size())
45 : 0 : vchData.resize(nPos);
46 : 870462 : }
47 : : /*
48 : : * (other params same as above)
49 : : * @param[in] args A list of items to serialize starting at nPosIn.
50 : : */
51 : : template <typename... Args>
52 [ + - ][ + - : 768422 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - + - ]
[ + - - -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
- - + - +
- + - -
- ]
53 : : {
54 [ + - ][ + - : 768422 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - + - ]
[ + - - -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
- - + - +
- + - -
- ]
55 : 278481 : }
56 : 7610499 : void write(std::span<const std::byte> src)
57 : : {
58 [ - + ]: 7610499 : assert(nPos <= vchData.size());
59 [ + + ]: 7610499 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
60 [ - + ]: 7610499 : if (nOverwrite) {
61 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
62 : : }
63 [ + + ]: 7610499 : if (nOverwrite < src.size()) {
64 : 7521163 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
65 : : }
66 : 7610499 : nPos += src.size();
67 : 7610499 : }
68 : : template <typename T>
69 : 1334469 : VectorWriter& operator<<(const T& obj)
70 : : {
71 [ + - + - : 1334469 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - +
- ]
72 : 140545 : return (*this);
73 : : }
74 : :
75 : : private:
76 : : std::vector<unsigned char>& vchData;
77 : : size_t nPos;
78 : : };
79 : :
80 : : /** Minimal stream for reading from an existing byte array by std::span.
81 : : */
82 : : class SpanReader
83 : : {
84 : : private:
85 : : std::span<const std::byte> m_data;
86 : :
87 : : public:
88 : : /**
89 : : * @param[in] data Referenced byte vector to overwrite/append
90 : : */
91 : 919324 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
92 [ + - ]: 7724 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
93 : :
94 : : template<typename T>
95 : 4030064 : SpanReader& operator>>(T&& obj)
96 : : {
97 [ + + + + : 4001356 : ::Unserialize(*this, obj);
+ + + + +
+ + + + -
+ - + - +
+ + - + -
+ + + - +
+ + - + -
+ + + - +
+ + + + +
+ + + - +
- + - + +
+ - + + +
- + - + -
+ - + - +
+ + + + -
+ + + + ]
[ + - + -
+ + + + +
+ + - + -
+ - + + +
+ ][ + + +
+ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - ]
98 : 1238216 : return (*this);
99 : : }
100 : :
101 [ + + ]: 128610 : size_t size() const { return m_data.size(); }
102 [ - + - + : 263816 : bool empty() const { return m_data.empty(); }
# # # # ]
[ + + + +
+ + + + ]
[ + + ]
103 : :
104 : 5352973 : void read(std::span<std::byte> dst)
105 : : {
106 [ + - ]: 5352973 : if (dst.size() == 0) {
107 : : return;
108 : : }
109 : :
110 : : // Read from the beginning of the buffer
111 [ + + ]: 5352973 : if (dst.size() > m_data.size()) {
112 [ + - ]: 81904 : throw std::ios_base::failure("SpanReader::read(): end of data");
113 : : }
114 : 5271069 : memcpy(dst.data(), m_data.data(), dst.size());
115 : 5271069 : m_data = m_data.subspan(dst.size());
116 : : }
117 : :
118 : : void ignore(size_t n)
119 : : {
120 : : m_data = m_data.subspan(n);
121 : : }
122 : : };
123 : :
124 : : /** Double ended buffer combining vector and stream-like interfaces.
125 : : *
126 : : * >> and << read and write unformatted data using the above serialization templates.
127 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
128 : : */
129 [ + - + - : 47617849 : class DataStream
+ + ][ + - ]
[ + + + + ]
130 : : {
131 : : protected:
132 : : using vector_type = SerializeData;
133 : : vector_type vch;
134 : : vector_type::size_type m_read_pos{0};
135 : :
136 : : public:
137 : : typedef vector_type::allocator_type allocator_type;
138 : : typedef vector_type::size_type size_type;
139 : : typedef vector_type::difference_type difference_type;
140 : : typedef vector_type::reference reference;
141 : : typedef vector_type::const_reference const_reference;
142 : : typedef vector_type::value_type value_type;
143 : : typedef vector_type::iterator iterator;
144 : : typedef vector_type::const_iterator const_iterator;
145 : : typedef vector_type::reverse_iterator reverse_iterator;
146 : :
147 [ + - ]: 2906659 : explicit DataStream() = default;
148 : 1738151 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
149 : 19644360 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
150 : :
151 : 362 : std::string str() const
152 : : {
153 : 724 : return std::string{UCharCast(data()), UCharCast(data() + size())};
154 : : }
155 : :
156 : :
157 : : //
158 : : // Vector subset
159 : : //
160 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
161 : 1599705 : iterator begin() { return vch.begin() + m_read_pos; }
162 : : const_iterator end() const { return vch.end(); }
163 [ + - ]: 836599 : iterator end() { return vch.end(); }
[ # # # # ]
164 [ + + + + : 43827372 : size_type size() const { return vch.size() - m_read_pos; }
# # # # #
# # # # #
# # # # #
# # # #
# ][ + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - + - +
- ][ + - -
+ + - ][ #
# # # # #
# # ][ + + ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - -
- # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # ]
165 [ - + - + : 1915781 : bool empty() const { return vch.size() == m_read_pos; }
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + ][ + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # ][ +
+ + + + +
+ + + + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + ]
[ # # ][ + +
+ + + + +
+ ][ - - -
- - - - -
- - + + ]
166 : 737324 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
167 [ # # # # ]: 20433055 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
[ + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - ][ + -
+ - + - +
- + - ][ +
- + - + -
+ - + - +
- + - -
- ][ # # #
# # # # #
# # # # ]
[ + - # #
# # # # #
# # # # #
# # ]
168 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
169 [ + + ]: 5845353 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
170 [ # # # # : 22064474 : void clear() { vch.clear(); m_read_pos = 0; }
# # # # ]
[ + + + +
# # # # ]
[ # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- - - ][ #
# # # # #
# # # # #
# # # #
# ]
171 [ + - + - : 37758869 : value_type* data() { return vch.data() + m_read_pos; }
+ - + - ]
[ + - ]
[ + - + - ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - -
- # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
172 : 108898 : const value_type* data() const { return vch.data() + m_read_pos; }
173 : :
174 : : inline void Compact()
175 : : {
176 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
177 : : m_read_pos = 0;
178 : : }
179 : :
180 : : bool Rewind(std::optional<size_type> n = std::nullopt)
181 : : {
182 : : // Total rewind if no size is passed
183 : : if (!n) {
184 : : m_read_pos = 0;
185 : : return true;
186 : : }
187 : : // Rewind by n characters if the buffer hasn't been compacted yet
188 : : if (*n > m_read_pos)
189 : : return false;
190 : : m_read_pos -= *n;
191 : : return true;
192 : : }
193 : :
194 : :
195 : : //
196 : : // Stream subset
197 : : //
198 [ # # ]: 0 : bool eof() const { return size() == 0; }
199 [ + + ]: 438 : int in_avail() const { return size(); }
200 : :
201 : 544462497 : void read(std::span<value_type> dst)
202 : : {
203 [ + + ]: 544462497 : if (dst.size() == 0) return;
204 : :
205 : : // Read from the beginning of the buffer
206 [ + - ]: 538484391 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
207 [ + - + + ]: 538484391 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
208 [ + - ]: 335892 : throw std::ios_base::failure("DataStream::read(): end of data");
209 : : }
210 [ + + ]: 538148499 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
211 [ + + ]: 538148499 : if (next_read_pos.value() == vch.size()) {
212 : 35384513 : m_read_pos = 0;
213 [ + - ]: 35384513 : vch.clear();
214 : 35384513 : return;
215 : : }
216 : 502763986 : m_read_pos = next_read_pos.value();
217 : : }
218 : :
219 : 1491363 : void ignore(size_t num_ignore)
220 : : {
221 : : // Ignore from the beginning of the buffer
222 : 1491363 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
223 [ + - + + ]: 1491363 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
224 [ + - ]: 3362 : throw std::ios_base::failure("DataStream::ignore(): end of data");
225 : : }
226 [ + + ]: 1488001 : if (next_read_pos.value() == vch.size()) {
227 : 1528 : m_read_pos = 0;
228 [ + + ]: 1528 : vch.clear();
229 : 1528 : return;
230 : : }
231 : 1486473 : m_read_pos = next_read_pos.value();
232 : : }
233 : :
234 : 309805815 : void write(std::span<const value_type> src)
235 : : {
236 : : // Write to the end of the buffer
237 : 309805815 : vch.insert(vch.end(), src.begin(), src.end());
238 : 309805815 : }
239 : :
240 : : template<typename T>
241 : 98004110 : DataStream& operator<<(const T& obj)
242 : : {
243 [ + - + - : 89629723 : ::Serialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # ][ - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - ]
[ + - + -
+ - + - +
- ][ + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
244 : 16747868 : return (*this);
245 : : }
246 : :
247 : : template <typename T>
248 : 88100690 : DataStream& operator>>(T&& obj)
249 : : {
250 [ + + ][ + + : 88041995 : ::Unserialize(*this, obj);
+ + + + ]
[ + - + +
+ - + - +
- ][ + + +
+ + + + +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
- + + + +
+ + + + ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - +
+ ][ + + +
+ # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ -
- + - + +
- - + + +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
+ + + + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
+ - - - -
- - ][ - -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - - -
- - - + -
+ - + - +
- + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
251 : 41166746 : return (*this);
252 : : }
253 : :
254 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
255 : : size_t GetMemoryUsage() const noexcept;
256 : : };
257 : :
258 : : template <typename IStream>
259 : : class BitStreamReader
260 : : {
261 : : private:
262 : : IStream& m_istream;
263 : :
264 : : /// Buffered byte read in from the input stream. A new byte is read into the
265 : : /// buffer when m_offset reaches 8.
266 : : uint8_t m_buffer{0};
267 : :
268 : : /// Number of high order bits in m_buffer already returned by previous
269 : : /// Read() calls. The next bit to be returned is at this offset from the
270 : : /// most significant bit position.
271 : : int m_offset{8};
272 : :
273 : : public:
274 [ + - ]: 1952 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
275 : :
276 : : /** Read the specified number of bits from the stream. The data is returned
277 : : * in the nbits least significant bits of a 64-bit uint.
278 : : */
279 : 2354778 : uint64_t Read(int nbits) {
280 [ + - ]: 2354778 : if (nbits < 0 || nbits > 64) {
281 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
282 : : }
283 : :
284 : : uint64_t data = 0;
285 [ + + ]: 6902275 : while (nbits > 0) {
286 [ + + ]: 4567486 : if (m_offset == 8) {
287 : 2659644 : m_istream >> m_buffer;
288 : 2639655 : m_offset = 0;
289 : : }
290 : :
291 [ + + ]: 4547497 : int bits = std::min(8 - m_offset, nbits);
292 : 4547497 : data <<= bits;
293 : 4547497 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
294 : 4547497 : m_offset += bits;
295 : 4547497 : nbits -= bits;
296 : : }
297 : 2334789 : return data;
298 : : }
299 : : };
300 : :
301 : : template <typename OStream>
302 : : class BitStreamWriter
303 : : {
304 : : private:
305 : : OStream& m_ostream;
306 : :
307 : : /// Buffered byte waiting to be written to the output stream. The byte is
308 : : /// written buffer when m_offset reaches 8 or Flush() is called.
309 : : uint8_t m_buffer{0};
310 : :
311 : : /// Number of high order bits in m_buffer already written by previous
312 : : /// Write() calls and not yet flushed to the stream. The next bit to be
313 : : /// written to is at this offset from the most significant bit position.
314 : : int m_offset{0};
315 : :
316 : : public:
317 [ + + ]: 281 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
318 : :
319 : 281 : ~BitStreamWriter()
320 : : {
321 : 281 : Flush();
322 : 281 : }
323 : :
324 : : /** Write the nbits least significant bits of a 64-bit int to the output
325 : : * stream. Data is buffered until it completes an octet.
326 : : */
327 : 85094 : void Write(uint64_t data, int nbits) {
328 [ + - ]: 85094 : if (nbits < 0 || nbits > 64) {
329 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
330 : : }
331 : :
332 [ + + ]: 248645 : while (nbits > 0) {
333 [ + + ]: 163551 : int bits = std::min(8 - m_offset, nbits);
334 : 163551 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
335 : 163551 : m_offset += bits;
336 : 163551 : nbits -= bits;
337 : :
338 [ + + ]: 163551 : if (m_offset == 8) {
339 : 89197 : Flush();
340 : : }
341 : : }
342 : 85094 : }
343 : :
344 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
345 : : * next byte boundary.
346 : : */
347 : 89759 : void Flush() {
348 [ + + ]: 89759 : if (m_offset == 0) {
349 : : return;
350 : : }
351 : :
352 : 89405 : m_ostream << m_buffer;
353 : 89405 : m_buffer = 0;
354 : 89405 : m_offset = 0;
355 : : }
356 : : };
357 : :
358 : : /** Non-refcounted RAII wrapper for FILE*
359 : : *
360 : : * Will automatically close the file when it goes out of scope if not null.
361 : : * If you're returning the file pointer, return file.release().
362 : : * If you need to close the file early, use autofile.fclose() instead of fclose(underlying_FILE).
363 : : *
364 : : * @note If the file has been written to, then the caller must close it
365 : : * explicitly with the `fclose()` method, check if it returns an error and treat
366 : : * such an error as if the `write()` method failed. The OS's `fclose(3)` may
367 : : * fail to flush to disk data that has been previously written, rendering the
368 : : * file corrupt.
369 : : */
370 : : class AutoFile
371 : : {
372 : : protected:
373 : : std::FILE* m_file;
374 : : Obfuscation m_obfuscation;
375 : : std::optional<int64_t> m_position;
376 : : bool m_was_written{false};
377 : :
378 : : public:
379 : : explicit AutoFile(std::FILE* file, const Obfuscation& obfuscation = {});
380 : :
381 : 340207 : ~AutoFile()
382 : : {
383 [ + + ]: 340207 : if (m_was_written) {
384 : : // Callers that wrote to the file must have closed it explicitly
385 : : // with the fclose() method and checked that the close succeeded.
386 : : // This is because here in the destructor we have no way to signal
387 : : // errors from fclose() which, after write, could mean the file is
388 : : // corrupted and must be handled properly at the call site.
389 : : // Destructors in C++ cannot signal an error to the callers because
390 : : // they do not return a value and are not allowed to throw exceptions.
391 : 293161 : Assume(IsNull());
392 : : }
393 : :
394 [ + + ]: 14145 : if (fclose() != 0) {
395 : 2578 : LogError("Failed to close file: %s", SysErrorString(errno));
396 : : }
397 : 340207 : }
398 : :
399 : : // Disallow copies
400 : : AutoFile(const AutoFile&) = delete;
401 : : AutoFile& operator=(const AutoFile&) = delete;
402 : :
403 : 14072 : bool feof() const { return std::feof(m_file); }
404 : :
405 : 637128 : [[nodiscard]] int fclose()
406 : : {
407 [ + - ]: 309923 : if (auto rel{release()}) return std::fclose(rel);
[ + - + - ]
[ + - + -
+ - ]
408 : : return 0;
409 : : }
410 : :
411 : : /** Get wrapped FILE* with transfer of ownership.
412 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
413 : : * of this function to clean up the returned FILE*.
414 : : */
415 : 637246 : std::FILE* release()
416 : : {
417 : 637246 : std::FILE* ret{m_file};
418 : 637246 : m_file = nullptr;
419 [ + - - - ]: 637246 : return ret;
[ # # # #
# # ][ + +
+ + + + ]
[ + - + -
+ - - - ]
[ # # # #
# # # # #
# ]
420 : : }
421 : :
422 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
423 : : */
424 [ + + ]: 965354 : bool IsNull() const { return m_file == nullptr; }
[ + + + + ]
[ # # # #
# # # # #
# # # ][ -
- - - - +
+ + - + -
- ]
425 : :
426 : : /** Continue with a different XOR key */
427 : 1515 : void SetObfuscation(const Obfuscation& obfuscation) { m_obfuscation = obfuscation; }
428 : :
429 : : /** Implementation detail, only used internally. */
430 : : std::size_t detail_fread(std::span<std::byte> dst);
431 : :
432 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
433 : : void seek(int64_t offset, int origin);
434 : :
435 : : /** Find position within the file. Will throw if unknown. */
436 : : int64_t tell();
437 : :
438 : : /** Wrapper around FileCommit(). */
439 : : bool Commit();
440 : :
441 : : /** Wrapper around TruncateFile(). */
442 : : bool Truncate(unsigned size);
443 : :
444 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
445 : : void write_buffer(std::span<std::byte> src);
446 : :
447 : : //
448 : : // Stream subset
449 : : //
450 : : void read(std::span<std::byte> dst);
451 : : void ignore(size_t nSize);
452 : : void write(std::span<const std::byte> src);
453 : :
454 : : template <typename T>
455 : 1642163 : AutoFile& operator<<(const T& obj)
456 : : {
457 [ + - ][ - - : 1635545 : ::Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ + + + + ]
[ + - + +
+ - + + -
- - - - -
+ + + - ]
[ # # # #
# # # # ]
[ + + + -
+ - + - +
- + - + -
+ - ][ # #
# # # # #
# # # # #
# # # # ]
458 : 414134 : return *this;
459 : : }
460 : :
461 : : template <typename T>
462 : 4147258 : AutoFile& operator>>(T&& obj)
463 : : {
464 [ + + + + ]: 4132755 : ::Unserialize(*this, obj);
[ # # ][ - -
+ + + + +
+ + - + +
+ + + - +
- - - + -
- - - - ]
[ + - + -
+ - ][ + +
+ + + + +
+ + + + +
+ + + + +
+ ][ + + +
+ + + +
+ ][ + + +
+ + + + +
+ + + + ]
465 : 1893224 : return *this;
466 : : }
467 : : };
468 : :
469 : : using DataBuffer = std::vector<std::byte>;
470 : :
471 : : /** Wrapper around an AutoFile& that implements a ring buffer to
472 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
473 : : *
474 : : * Will automatically close the file when it goes out of scope if not null.
475 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
476 : : */
477 : 1113 : class BufferedFile
478 : : {
479 : : private:
480 : : AutoFile& m_src;
481 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
482 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
483 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
484 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
485 : : DataBuffer vchBuf;
486 : :
487 : : //! read data from the source to fill the buffer
488 : 494181 : bool Fill() {
489 [ + + ]: 494181 : unsigned int pos = nSrcPos % vchBuf.size();
490 : 494181 : unsigned int readNow = vchBuf.size() - pos;
491 : 494181 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
492 [ + + ]: 494181 : if (nAvail < readNow)
493 : 476428 : readNow = nAvail;
494 [ + - ]: 494181 : if (readNow == 0)
495 : : return false;
496 : 494181 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
497 [ + + ]: 492812 : if (nBytes == 0) {
498 [ + + + - ]: 8499 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
499 : : }
500 : 487216 : nSrcPos += nBytes;
501 : 487216 : return true;
502 : : }
503 : :
504 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
505 : : //! filling the buffer from the file so that at least one byte is available.
506 : : //! Return a pointer to the available buffer data and the number of bytes
507 : : //! (which may be less than the requested length) that may be accessed
508 : : //! beginning at that pointer.
509 : 8515270 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
510 : : {
511 [ - + ]: 8515270 : assert(m_read_pos <= nSrcPos);
512 [ + + ]: 8515270 : if (m_read_pos + length > nReadLimit) {
513 [ + - ]: 33426 : throw std::ios_base::failure("Attempt to position past buffer limit");
514 : : }
515 : : // If there are no bytes available, read from the file.
516 [ + + + - ]: 8481844 : if (m_read_pos == nSrcPos && length > 0) Fill();
517 : :
518 : 8475895 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
519 : 8475895 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
520 : 8475895 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
521 : 8475895 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
522 : 8475895 : m_read_pos += advance;
523 : 8475895 : return std::make_pair(&vchBuf[buffer_offset], advance);
524 : : }
525 : :
526 : : public:
527 : 1147 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
528 : 1147 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
529 : : {
530 [ + + ]: 1147 : if (nRewindIn >= nBufSize)
531 [ + - ]: 34 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
532 : 1147 : }
533 : :
534 : : //! check whether we're at the end of the source file
535 : 1981384 : bool eof() const {
536 [ + + + + ]: 1981384 : return m_read_pos == nSrcPos && m_src.feof();
537 : : }
538 : :
539 : : //! read a number of bytes
540 : 7807077 : void read(std::span<std::byte> dst)
541 : : {
542 [ + + ]: 15892158 : while (dst.size() > 0) {
543 : 8122744 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
544 : 8085081 : memcpy(dst.data(), buffer_pointer, length);
545 : 8085081 : dst = dst.subspan(length);
546 : : }
547 : 7769414 : }
548 : :
549 : : //! Move the read position ahead in the stream to the given position.
550 : : //! Use SetPos() to back up in the stream, not SkipTo().
551 : 393939 : void SkipTo(const uint64_t file_pos)
552 : : {
553 [ + - ]: 393939 : assert(file_pos >= m_read_pos);
554 [ + + ]: 784753 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
555 : 392227 : }
556 : :
557 : : //! return the current reading position
558 : 2470350 : uint64_t GetPos() const {
559 [ + + + + : 2470350 : return m_read_pos;
+ - ]
560 : : }
561 : :
562 : : //! rewind to a given reading position
563 : 2125489 : bool SetPos(uint64_t nPos) {
564 [ + + ]: 2125489 : size_t bufsize = vchBuf.size();
565 [ + + ]: 2125489 : if (nPos + bufsize < nSrcPos) {
566 : : // rewinding too far, rewind as far as possible
567 : 769 : m_read_pos = nSrcPos - bufsize;
568 : 769 : return false;
569 : : }
570 [ + + ]: 2124720 : if (nPos > nSrcPos) {
571 : : // can't go this far forward, go as far as possible
572 : 2055 : m_read_pos = nSrcPos;
573 : 2055 : return false;
574 : : }
575 : 2122665 : m_read_pos = nPos;
576 : 2122665 : return true;
577 : : }
578 : :
579 : : //! prevent reading beyond a certain position
580 : : //! no argument removes the limit
581 : 2377719 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
582 [ + + ]: 396637 : if (nPos < m_read_pos)
583 : : return false;
584 : 2376962 : nReadLimit = nPos;
585 [ + + ]: 2376962 : return true;
586 : : }
587 : :
588 : : template<typename T>
589 : 3004523 : BufferedFile& operator>>(T&& obj) {
590 [ + + + + ]: 3004523 : ::Unserialize(*this, obj);
[ + + + +
+ + + + ]
591 : 2934692 : return (*this);
592 : : }
593 : :
594 : : //! search for a given byte in the stream, and remain positioned on it
595 : 1983114 : void FindByte(std::byte byte)
596 : : {
597 : : // For best performance, avoid mod operation within the loop.
598 : 1983114 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
599 : 2147846 : while (true) {
600 [ + + ]: 2147846 : if (m_read_pos == nSrcPos) {
601 : : // No more bytes available; read from the file into the buffer,
602 : : // setting nSrcPos to one beyond the end of the new data.
603 : : // Throws exception if end-of-file reached.
604 : 167635 : Fill();
605 : : }
606 [ + + ]: 2146830 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
607 [ + + ]: 2146830 : const auto it_start{vchBuf.begin() + buf_offset};
608 : 2146830 : const auto it_find{std::find(it_start, it_start + len, byte)};
609 [ + + ]: 2146830 : const size_t inc{size_t(std::distance(it_start, it_find))};
610 : 2146830 : m_read_pos += inc;
611 [ + + ]: 2146830 : if (inc < len) break;
612 : 164732 : buf_offset += inc;
613 [ + + ]: 164732 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
614 : : }
615 : 1982098 : }
616 : : };
617 : :
618 : : /**
619 : : * Wrapper that buffers reads from an underlying stream.
620 : : * Requires underlying stream to support read() and detail_fread() calls
621 : : * to support fixed-size and variable-sized reads, respectively.
622 : : */
623 : : template <typename S>
624 : 0 : class BufferedReader
625 : : {
626 : : S& m_src;
627 : : DataBuffer m_buf;
628 : : size_t m_buf_pos;
629 : :
630 : : public:
631 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
632 : 0 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
633 : : requires std::is_rvalue_reference_v<S&&>
634 [ # # # # ]: 0 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
635 : :
636 : 0 : void read(std::span<std::byte> dst)
637 : : {
638 [ # # # # ]: 0 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
639 : 0 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
640 : 0 : m_buf_pos += available;
641 : 0 : dst = dst.subspan(available);
642 : : }
643 [ # # ]: 0 : if (dst.size()) {
644 [ # # ]: 0 : assert(m_buf_pos == m_buf.size());
645 : 0 : m_src.read(dst);
646 : :
647 : 0 : m_buf_pos = 0;
648 : 0 : m_buf.resize(m_src.detail_fread(m_buf));
649 : : }
650 : 0 : }
651 : :
652 : : template <typename T>
653 : 0 : BufferedReader& operator>>(T&& obj)
654 : : {
655 [ # # ]: 0 : Unserialize(*this, obj);
656 : 0 : return *this;
657 : : }
658 : : };
659 : :
660 : : /**
661 : : * Wrapper that buffers writes to an underlying stream.
662 : : * Requires underlying stream to support write_buffer() method
663 : : * for efficient buffer flushing and obfuscation.
664 : : */
665 : : template <typename S>
666 : : class BufferedWriter
667 : : {
668 : : S& m_dst;
669 : : DataBuffer m_buf;
670 : : size_t m_buf_pos{0};
671 : :
672 : : public:
673 [ + - + - : 289484 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
674 : :
675 [ + - + - ]: 289484 : ~BufferedWriter() { flush(); }
676 : :
677 : 289484 : void flush()
678 : : {
679 [ + - ]: 289484 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
680 : 289484 : m_buf_pos = 0;
681 : 289484 : }
682 : :
683 : 5187308 : void write(std::span<const std::byte> src)
684 : : {
685 [ + - + + ]: 20749232 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
686 : 5187308 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
687 : 5187308 : m_buf_pos += available;
688 [ - + ]: 5187308 : if (m_buf_pos == m_buf.size()) flush();
689 : 5187308 : src = src.subspan(available);
690 : : }
691 : 5187308 : }
692 : :
693 : : template <typename T>
694 : 1145068 : BufferedWriter& operator<<(const T& obj)
695 : : {
696 [ - - + - : 855584 : Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- ]
697 : 580792 : return *this;
698 : : }
699 : : };
700 : :
701 : : #endif // BITCOIN_STREAMS_H
|