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 : 139425 : inline void Xor(std::span<std::byte> write, std::span<const std::byte> key, size_t key_offset = 0)
32 : : {
33 [ + - ]: 139425 : if (key.size() == 0) {
34 : : return;
35 : : }
36 : 139425 : key_offset %= key.size();
37 : :
38 [ + + ]: 66771344 : for (size_t i = 0, j = key_offset; i != write.size(); i++) {
39 [ + + ]: 66631919 : 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 [ + + ]: 66631919 : if (j == key.size())
46 : 8278990 : 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 : 298 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
64 : : {
65 [ + + ]: 298 : if(nPos > vchData.size())
66 : 1 : vchData.resize(nPos);
67 : 298 : }
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 [ + - ][ + - : 38 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - - -
- - - - -
- - - - -
- - - - +
- - - - -
- - - - -
- - - - -
+ - + - -
- ]
74 : : {
75 [ + - ][ + - : 38 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - - -
- - - - -
- - - - -
- - - - +
- - - - -
- - - - -
- - - - -
+ - + - -
- ]
76 : 30 : }
77 : 1420 : void write(std::span<const std::byte> src)
78 : : {
79 [ - + ]: 1420 : assert(nPos <= vchData.size());
80 [ + + ]: 1420 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
81 [ + + ]: 1420 : if (nOverwrite) {
82 : 19 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
83 : : }
84 [ + + ]: 1420 : if (nOverwrite < src.size()) {
85 : 1402 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
86 : : }
87 : 1420 : nPos += src.size();
88 : 1420 : }
89 : : template <typename T>
90 : 1072 : VectorWriter& operator<<(const T& obj)
91 : : {
92 [ + - + - : 1072 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - ][ + -
+ - + - +
- ]
93 : 117 : 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 : 562 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
113 [ + - ]: 2119 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
114 : :
115 : : template<typename T>
116 : 15744 : SpanReader& operator>>(T&& obj)
117 : : {
118 [ # # # # : 15744 : ::Unserialize(*this, obj);
# # # # #
# # # # #
# # # # #
# ][ + + #
# # # # #
# # ][ + -
- - - - ]
[ + - + -
+ - + - -
+ + - - +
# # # # #
# ][ + - +
- + - + -
+ - # # #
# ]
[ + - + + ]
119 : 2223 : return (*this);
120 : : }
121 : :
122 [ # # ][ + - : 5 : size_t size() const { return m_data.size(); }
+ - + - +
- + - ]
123 [ # # # # : 11 : bool empty() const { return m_data.empty(); }
# # # # ]
[ + - + -
+ - + - +
- + - ]
[ + + ]
124 : :
125 : 72513 : void read(std::span<std::byte> dst)
126 : : {
127 [ + - ]: 72513 : if (dst.size() == 0) {
128 : : return;
129 : : }
130 : :
131 : : // Read from the beginning of the buffer
132 [ + + ]: 72513 : if (dst.size() > m_data.size()) {
133 [ + - ]: 4 : throw std::ios_base::failure("SpanReader::read(): end of data");
134 : : }
135 : 72509 : memcpy(dst.data(), m_data.data(), dst.size());
136 : 72509 : 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 [ + + + + ]: 4105742 : 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 [ + - ]: 1710 : explicit DataStream() = default;
169 : 740 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
170 : 100188 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
171 : :
172 : 19 : std::string str() const
173 : : {
174 : 38 : 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 : 58264 : iterator begin() { return vch.begin() + m_read_pos; }
183 : : const_iterator end() const { return vch.end(); }
184 [ + - ]: 29275 : iterator end() { return vch.end(); }
[ + - + - ]
[ + - + -
+ - + - ]
185 [ + + # # ]: 12525323 : size_type size() const { return vch.size() - m_read_pos; }
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - # # #
# # # # #
# # # # #
# # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - # # ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - +
+ - ][ + -
+ - + - +
- + - + -
+ - # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - ]
[ + - + -
+ - + - +
- ][ # # #
# # # # #
# # # # #
# # # ][ -
- + - - -
- - - - +
- ]
186 [ - + + - : 1127 : bool empty() const { return vch.size() == m_read_pos; }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - + -
+ - + + ]
[ + - ][ + +
+ + + + +
+ ][ # # #
# # # # #
# # # # ]
[ + - + - ]
187 : 309 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
188 [ + - + - : 3803410 : 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 [ + + ]: 8386102 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
191 [ - + + - : 66893 : void clear() { vch.clear(); m_read_pos = 0; }
- + - + ]
[ + + + +
# # # # ]
[ - + + -
+ - - + +
- - + + -
- + + - -
+ ][ - + +
- - + + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ - + -
+ - + ][ -
- - - - -
- - - - +
- + - + -
+ - + - +
- ][ - - -
- + - + -
+ - + - +
- - - ][ +
- + - + -
+ - + - +
- # # #
# ]
192 [ + - + - : 3772420 : value_type* data() { return vch.data() + m_read_pos; }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
# # # # #
# # # #
# ][ + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - ]
[ + - + -
+ - + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- + - - -
- - - - +
- # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
193 : 318 : 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 [ + + ]: 15495 : bool eof() const { return size() == 0; }
220 [ # # ]: 0 : int in_avail() const { return size(); }
221 : :
222 : 1345405 : void read(std::span<value_type> dst)
223 : : {
224 [ + + ]: 1345405 : if (dst.size() == 0) return;
225 : :
226 : : // Read from the beginning of the buffer
227 [ + - ]: 1344217 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
228 [ + - + + ]: 1344217 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
229 [ + - ]: 29 : throw std::ios_base::failure("DataStream::read(): end of data");
230 : : }
231 [ + + ]: 1344188 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
232 [ + + ]: 1344188 : if (next_read_pos.value() == vch.size()) {
233 : 100971 : m_read_pos = 0;
234 [ + - ]: 100971 : vch.clear();
235 : 100971 : return;
236 : : }
237 : 1243217 : m_read_pos = next_read_pos.value();
238 : : }
239 : :
240 : 7 : void ignore(size_t num_ignore)
241 : : {
242 : : // Ignore from the beginning of the buffer
243 : 7 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
244 [ + - + + ]: 7 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
245 [ + - ]: 1 : throw std::ios_base::failure("DataStream::ignore(): end of data");
246 : : }
247 [ + + ]: 6 : if (next_read_pos.value() == vch.size()) {
248 : 3 : m_read_pos = 0;
249 [ + + ]: 3 : vch.clear();
250 : 3 : return;
251 : : }
252 : 3 : m_read_pos = next_read_pos.value();
253 : : }
254 : :
255 : 23082918 : void write(std::span<const value_type> src)
256 : : {
257 : : // Write to the end of the buffer
258 : 23082918 : vch.insert(vch.end(), src.begin(), src.end());
259 : 23082918 : }
260 : :
261 : : template<typename T>
262 : 8345373 : DataStream& operator<<(const T& obj)
263 : : {
264 [ + - ][ + - : 8314944 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
- - - - +
- + - + -
+ - + - +
- - - - -
- - + - +
- - - + -
+ - + - +
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + - +
- - - - -
- - + - +
- + - + -
+ - - - -
- + - + -
+ - + - -
- ][ + - +
- + - + -
+ - ][ + -
+ - + - -
- + - + -
+ - - - +
- + - - -
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
# # # # #
# # # # #
# # ][ + -
+ - # # #
# ][ + - +
- + - + -
# # # # #
# ]
265 : 4441399 : return (*this);
266 : : }
267 : :
268 : : template<typename T>
269 : 479776 : DataStream& operator>>(T&& obj)
270 : : {
271 [ + + ][ + - : 479546 : ::Unserialize(*this, obj);
+ - + - +
- + + +
+ ][ + - +
+ + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - -
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + + +
+ + - + -
+ - + - +
- + - +
- ][ + - +
- - + - +
- + + - +
- - + + -
+ - + - +
- - + + -
- + + - +
- - + - +
+ - + - ]
[ - - + -
- - - - -
- - - - -
- - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
- - - - +
- + - + -
+ - + - ]
[ + - + -
+ + + + #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
# # # # ]
[ + - + -
+ - # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - + -
+ - + - +
- + + - -
+ - + - +
- - + + -
- - - - -
- - - - -
- - - - +
- - - - -
- - - - -
- - - - -
- - - - ]
272 : 287632 : 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 : 113937 : void Xor(const std::vector<unsigned char>& key)
281 : : {
282 : 113937 : util::Xor(MakeWritableByteSpan(*this), MakeByteSpan(key));
283 : 113937 : }
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 [ + - ]: 211 : 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 : 23248 : uint64_t Read(int nbits) {
311 [ + - ]: 23248 : 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 [ + + ]: 57412 : while (nbits > 0) {
317 [ + + ]: 34165 : if (m_offset == 8) {
318 : 13523 : m_istream >> m_buffer;
319 : 13522 : m_offset = 0;
320 : : }
321 : :
322 [ + + ]: 34164 : int bits = std::min(8 - m_offset, nbits);
323 : 34164 : data <<= bits;
324 : 34164 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
325 : 34164 : m_offset += bits;
326 : 34164 : nbits -= bits;
327 : : }
328 : 23247 : 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 [ + - ]: 236 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
349 : :
350 : 236 : ~BitStreamWriter()
351 : : {
352 : 236 : Flush();
353 : 236 : }
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 : 875 : void Write(uint64_t data, int nbits) {
359 [ + - ]: 875 : if (nbits < 0 || nbits > 64) {
360 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
361 : : }
362 : :
363 [ + + ]: 2421 : while (nbits > 0) {
364 [ + + ]: 1546 : int bits = std::min(8 - m_offset, nbits);
365 : 1546 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
366 : 1546 : m_offset += bits;
367 : 1546 : nbits -= bits;
368 : :
369 [ + + ]: 1546 : if (m_offset == 8) {
370 : 709 : Flush();
371 : : }
372 : : }
373 : 875 : }
374 : :
375 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
376 : : * next byte boundary.
377 : : */
378 : 1181 : void Flush() {
379 [ + + ]: 1181 : if (m_offset == 0) {
380 : : return;
381 : : }
382 : :
383 : 944 : m_ostream << m_buffer;
384 : 944 : m_buffer = 0;
385 : 944 : 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 : 18331 : ~AutoFile()
413 : : {
414 : 18331 : 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 : 18331 : Assume(IsNull());
423 : : }
424 : :
425 [ - + ]: 3523 : if (fclose() != 0) {
426 : 0 : LogError("Failed to close file: %s", SysErrorString(errno));
427 : : }
428 : 18331 : }
429 : :
430 : : // Disallow copies
431 : : AutoFile(const AutoFile&) = delete;
432 : : AutoFile& operator=(const AutoFile&) = delete;
433 : :
434 : 192 : bool feof() const { return std::feof(m_file); }
435 : :
436 : 33136 : [[nodiscard]] int fclose()
437 : : {
438 [ + - + - : 18328 : 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 : 33136 : std::FILE* release()
447 : : {
448 : 33136 : std::FILE* ret{m_file};
449 : 33136 : m_file = nullptr;
450 [ + - + - : 33136 : return ret;
+ - + - -
- ][ + + #
# # # # #
# # # # #
# # # #
# ][ + - +
- + - + -
+ - + - +
- + - -
- ][ + - +
- + - -
- ][ + - -
- # # ][ #
# # # #
# ]
451 : : }
452 : :
453 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
454 : : */
455 [ # # ][ + - : 54838 : bool IsNull() const { return m_file == nullptr; }
+ - + - +
+ ]
[ - + + + ]
[ - - - +
+ - - + -
- # # #
# ][ - - -
- - + - +
- + - + -
- ][ - + +
+ - - # #
# # ]
456 : :
457 : : /** Continue with a different XOR key */
458 [ # # # # ]: 0 : 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 : 27128 : AutoFile& operator<<(const T& obj)
487 : : {
488 [ + - + + : 26885 : ::Serialize(*this, obj);
+ - # # #
# # # ][ +
- + - + -
- + + - +
- ]
[ + - + - ]
[ + - # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # ]
[ + - - -
- - + - ]
489 : 10739 : return *this;
490 : : }
491 : :
492 : : template <typename T>
493 : 14689 : AutoFile& operator>>(T&& obj)
494 : : {
495 [ + - + + : 12203 : ::Unserialize(*this, obj);
+ - + + ]
[ + - # #
# # # # #
# # # #
# ][ - + +
- + - + -
- + + - -
+ # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - +
- ]
[ + - + - ]
[ # # # #
# # # # #
# # # ]
496 : 8318 : 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 : 52 : 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 : 284 : bool Fill() {
520 [ + + ]: 284 : unsigned int pos = nSrcPos % vchBuf.size();
521 : 284 : unsigned int readNow = vchBuf.size() - pos;
522 : 284 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
523 [ + + ]: 284 : if (nAvail < readNow)
524 : 247 : readNow = nAvail;
525 [ + - ]: 284 : if (readNow == 0)
526 : : return false;
527 : 284 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
528 [ + + ]: 284 : if (nBytes == 0) {
529 [ - + + - ]: 1 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
530 : : }
531 : 283 : nSrcPos += nBytes;
532 : 283 : 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 : 3210 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
541 : : {
542 [ - + ]: 3210 : assert(m_read_pos <= nSrcPos);
543 [ + + ]: 3210 : if (m_read_pos + length > nReadLimit) {
544 [ + - ]: 2 : throw std::ios_base::failure("Attempt to position past buffer limit");
545 : : }
546 : : // If there are no bytes available, read from the file.
547 [ + + + - ]: 3208 : if (m_read_pos == nSrcPos && length > 0) Fill();
548 : :
549 : 3207 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
550 : 3207 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
551 : 3207 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
552 : 3207 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
553 : 3207 : m_read_pos += advance;
554 : 3207 : return std::make_pair(&vchBuf[buffer_offset], advance);
555 : : }
556 : :
557 : : public:
558 : 53 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
559 : 53 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
560 : : {
561 [ + + ]: 53 : if (nRewindIn >= nBufSize)
562 [ + - ]: 1 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
563 : 53 : }
564 : :
565 : : //! check whether we're at the end of the source file
566 : 3882 : bool eof() const {
567 [ + + + + ]: 3882 : return m_read_pos == nSrcPos && m_src.feof();
568 : : }
569 : :
570 : : //! read a number of bytes
571 : 2598 : void read(std::span<std::byte> dst)
572 : : {
573 [ + + ]: 5293 : while (dst.size() > 0) {
574 : 2697 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
575 : 2695 : memcpy(dst.data(), buffer_pointer, length);
576 : 2695 : dst = dst.subspan(length);
577 : : }
578 : 2596 : }
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 : 620 : void SkipTo(const uint64_t file_pos)
583 : : {
584 [ + - ]: 620 : assert(file_pos >= m_read_pos);
585 [ + + ]: 1132 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
586 : 619 : }
587 : :
588 : : //! return the current reading position
589 : 5201 : uint64_t GetPos() const {
590 [ + - + - : 5201 : return m_read_pos;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ # # #
# # # ]
591 : : }
592 : :
593 : : //! rewind to a given reading position
594 : 668 : bool SetPos(uint64_t nPos) {
595 [ + + - + : 668 : size_t bufsize = vchBuf.size();
- + - + -
+ - + - +
- + - + +
- ][ # # ]
596 [ + + - + : 668 : if (nPos + bufsize < nSrcPos) {
- + - + -
+ - + - +
- + - + +
- ][ # # ]
597 : : // rewinding too far, rewind as far as possible
598 : 67 : m_read_pos = nSrcPos - bufsize;
599 : 67 : return false;
600 : : }
601 [ + + - + : 598 : if (nPos > nSrcPos) {
- + - + -
+ - + ]
[ # # ]
602 : : // can't go this far forward, go as far as possible
603 : 17 : m_read_pos = nSrcPos;
604 : 17 : return false;
605 : : }
606 : 584 : m_read_pos = nPos;
607 : 584 : return true;
608 : : }
609 : :
610 : : //! prevent reading beyond a certain position
611 : : //! no argument removes the limit
612 : 3195 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
613 [ + - + - : 3194 : if (nPos < m_read_pos)
+ - + - +
- + - +
- ][ # # ]
614 : : return false;
615 : 3195 : nReadLimit = nPos;
616 [ + - ]: 3195 : return true;
617 : : }
618 : :
619 : : template<typename T>
620 : 2598 : BufferedFile& operator>>(T&& obj) {
621 [ + - + - : 2598 : ::Unserialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- + - + -
- + + - +
- + - + -
+ - - + +
- ][ # # #
# # # #
# ]
622 : 2596 : return (*this);
623 : : }
624 : :
625 : : //! search for a given byte in the stream, and remain positioned on it
626 : 650 : void FindByte(std::byte byte)
627 : : {
628 : : // For best performance, avoid mod operation within the loop.
629 : 650 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
630 : 718 : while (true) {
631 [ + + ]: 718 : 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 : 81 : Fill();
636 : : }
637 [ + + ]: 718 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
638 [ + + ]: 718 : const auto it_start{vchBuf.begin() + buf_offset};
639 : 718 : const auto it_find{std::find(it_start, it_start + len, byte)};
640 [ + + ]: 718 : const size_t inc{size_t(std::distance(it_start, it_find))};
641 : 718 : m_read_pos += inc;
642 [ + + ]: 718 : if (inc < len) break;
643 : 68 : buf_offset += inc;
644 [ + + ]: 68 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
645 : : }
646 : 650 : }
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 : 899 : 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 : 899 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
664 : : requires std::is_rvalue_reference_v<S&&>
665 [ + - + - : 899 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
+ - ]
[ + - + - ]
666 : :
667 : 1811 : void read(std::span<std::byte> dst)
668 : : {
669 [ + + + + ]: 2716 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
670 : 910 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
671 : 910 : m_buf_pos += available;
672 : 910 : dst = dst.subspan(available);
673 : : }
674 [ + + ]: 1811 : if (dst.size()) {
675 [ - + ]: 906 : assert(m_buf_pos == m_buf.size());
676 : 906 : m_src.read(dst);
677 : :
678 : 904 : m_buf_pos = 0;
679 : 904 : m_buf.resize(m_src.detail_fread(m_buf));
680 : : }
681 : 1809 : }
682 : :
683 : : template <typename T>
684 : 899 : BufferedReader& operator>>(T&& obj)
685 : : {
686 [ + - + - ]: 898 : Unserialize(*this, obj);
[ + - ]
687 : 898 : 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 [ + - + - : 14412 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - ][ + -
+ - + - +
- ]
705 : :
706 [ + - + - ]: 14412 : ~BufferedWriter() { flush(); }
707 : :
708 : 14421 : void flush()
709 : : {
710 [ + + ]: 14421 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
711 : 14421 : m_buf_pos = 0;
712 : 14421 : }
713 : :
714 : 242715 : void write(std::span<const std::byte> src)
715 : : {
716 [ + + + + ]: 970868 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
717 : 242723 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
718 : 242723 : m_buf_pos += available;
719 [ + + ]: 242723 : if (m_buf_pos == m_buf.size()) flush();
720 : 242723 : src = src.subspan(available);
721 : : }
722 : 242715 : }
723 : :
724 : : template <typename T>
725 : 57344 : BufferedWriter& operator<<(const T& obj)
726 : : {
727 [ + - + - ]: 42933 : Serialize(*this, obj);
[ + - - -
- - + - +
- + - + -
+ - + - +
- ]
728 : 28831 : return *this;
729 : : }
730 : : };
731 : :
732 : : #endif // BITCOIN_STREAMS_H
|