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 <serialize.h>
10 : : #include <span.h>
11 : : #include <support/allocators/zeroafterfree.h>
12 : : #include <util/overflow.h>
13 : :
14 : : #include <algorithm>
15 : : #include <cassert>
16 : : #include <cstddef>
17 : : #include <cstdint>
18 : : #include <cstdio>
19 : : #include <cstring>
20 : : #include <ios>
21 : : #include <limits>
22 : : #include <optional>
23 : : #include <string>
24 : : #include <utility>
25 : : #include <vector>
26 : :
27 : : namespace util {
28 : 137031 : inline void Xor(std::span<std::byte> write, std::span<const std::byte> key, size_t key_offset = 0)
29 : : {
30 [ + - ]: 137031 : if (key.size() == 0) {
31 : : return;
32 : : }
33 : 137031 : key_offset %= key.size();
34 : :
35 [ + + ]: 68103175 : for (size_t i = 0, j = key_offset; i != write.size(); i++) {
36 [ + + ]: 67966144 : write[i] ^= key[j++];
37 : :
38 : : // This potentially acts on very many bytes of data, so it's
39 : : // important that we calculate `j`, i.e. the `key` index in this
40 : : // way instead of doing a %, which would effectively be a division
41 : : // for each byte Xor'd -- much slower than need be.
42 [ + + ]: 67966144 : if (j == key.size())
43 : 8447235 : j = 0;
44 : : }
45 : : }
46 : : } // namespace util
47 : :
48 : : /* Minimal stream for overwriting and/or appending to an existing byte vector
49 : : *
50 : : * The referenced vector will grow as necessary
51 : : */
52 : : class VectorWriter
53 : : {
54 : : public:
55 : : /*
56 : : * @param[in] vchDataIn Referenced byte vector to overwrite/append
57 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
58 : : * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
59 : : */
60 : 298 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
61 : : {
62 [ + + ]: 298 : if(nPos > vchData.size())
63 : 1 : vchData.resize(nPos);
64 : 298 : }
65 : : /*
66 : : * (other params same as above)
67 : : * @param[in] args A list of items to serialize starting at nPosIn.
68 : : */
69 : : template <typename... Args>
70 [ + - ][ + - : 38 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - - -
- - - - -
- - - - -
- - - - +
- - - - -
- - - - -
- - - - -
+ - + - -
- ]
71 : : {
72 [ + - ][ + - : 38 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - - -
- - - - -
- - - - -
- - - - +
- - - - -
- - - - -
- - - - -
+ - + - -
- ]
73 : 30 : }
74 : 1420 : void write(std::span<const std::byte> src)
75 : : {
76 [ - + ]: 1420 : assert(nPos <= vchData.size());
77 [ + + ]: 1420 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
78 [ + + ]: 1420 : if (nOverwrite) {
79 : 19 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
80 : : }
81 [ + + ]: 1420 : if (nOverwrite < src.size()) {
82 : 1402 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
83 : : }
84 : 1420 : nPos += src.size();
85 : 1420 : }
86 : : template <typename T>
87 : 1072 : VectorWriter& operator<<(const T& obj)
88 : : {
89 [ + - + - : 1072 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - ][ + -
+ - + - +
- ]
90 : 117 : return (*this);
91 : : }
92 : :
93 : : private:
94 : : std::vector<unsigned char>& vchData;
95 : : size_t nPos;
96 : : };
97 : :
98 : : /** Minimal stream for reading from an existing byte array by std::span.
99 : : */
100 : : class SpanReader
101 : : {
102 : : private:
103 : : std::span<const std::byte> m_data;
104 : :
105 : : public:
106 : : /**
107 : : * @param[in] data Referenced byte vector to overwrite/append
108 : : */
109 : 562 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
110 [ + - ]: 2170 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
111 : :
112 : : template<typename T>
113 : 16114 : SpanReader& operator>>(T&& obj)
114 : : {
115 [ # # # # : 16114 : ::Unserialize(*this, obj);
# # # # #
# # # # #
# # # # #
# ][ + + #
# # # # #
# # ][ + -
- - - - ]
[ + - + -
+ - + - -
+ + - - +
# # # # #
# ][ + - +
- + - + -
+ - # # #
# ]
[ + - + + ]
116 : 2274 : return (*this);
117 : : }
118 : :
119 [ # # ][ + - : 5 : size_t size() const { return m_data.size(); }
+ - + - +
- + - ]
120 [ # # # # : 11 : bool empty() const { return m_data.empty(); }
# # # # ]
[ + - + -
+ - + - +
- + - ]
[ + + ]
121 : :
122 : 74362 : void read(std::span<std::byte> dst)
123 : : {
124 [ + - ]: 74362 : if (dst.size() == 0) {
125 : : return;
126 : : }
127 : :
128 : : // Read from the beginning of the buffer
129 [ + + ]: 74362 : if (dst.size() > m_data.size()) {
130 [ + - ]: 4 : throw std::ios_base::failure("SpanReader::read(): end of data");
131 : : }
132 : 74358 : memcpy(dst.data(), m_data.data(), dst.size());
133 : 74358 : m_data = m_data.subspan(dst.size());
134 : : }
135 : :
136 : : void ignore(size_t n)
137 : : {
138 : : m_data = m_data.subspan(n);
139 : : }
140 : : };
141 : :
142 : : /** Double ended buffer combining vector and stream-like interfaces.
143 : : *
144 : : * >> and << read and write unformatted data using the above serialization templates.
145 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
146 : : */
147 [ + + + + ]: 6033979 : class DataStream
[ + - + -
+ - + - ]
[ + - # #
# # # # ]
[ + - + -
+ - ]
148 : : {
149 : : protected:
150 : : using vector_type = SerializeData;
151 : : vector_type vch;
152 : : vector_type::size_type m_read_pos{0};
153 : :
154 : : public:
155 : : typedef vector_type::allocator_type allocator_type;
156 : : typedef vector_type::size_type size_type;
157 : : typedef vector_type::difference_type difference_type;
158 : : typedef vector_type::reference reference;
159 : : typedef vector_type::const_reference const_reference;
160 : : typedef vector_type::value_type value_type;
161 : : typedef vector_type::iterator iterator;
162 : : typedef vector_type::const_iterator const_iterator;
163 : : typedef vector_type::reverse_iterator reverse_iterator;
164 : :
165 [ + - ]: 1732 : explicit DataStream() = default;
166 : 759 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
167 : 97388 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
168 : :
169 : 19 : std::string str() const
170 : : {
171 : 38 : return std::string{UCharCast(data()), UCharCast(data() + size())};
172 : : }
173 : :
174 : :
175 : : //
176 : : // Vector subset
177 : : //
178 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
179 : 58532 : iterator begin() { return vch.begin() + m_read_pos; }
180 : : const_iterator end() const { return vch.end(); }
181 [ + - ]: 29409 : iterator end() { return vch.end(); }
[ + - + - ]
[ + - + -
+ - + - ]
182 [ + + # # ]: 14837650 : size_type size() const { return vch.size() - m_read_pos; }
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- - + +
- ][ + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - ][ + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ - - +
- - - - -
- - + - #
# # # ]
183 [ - + + - : 1143 : bool empty() const { return vch.size() == m_read_pos; }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - + -
+ - + + ]
[ + - + - ]
[ + + + +
+ + + + ]
[ # # # #
# # # # #
# # # ]
184 : 309 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
185 [ + - + - : 5732045 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - + -
+ - + - +
- + - ]
[ # # # # ]
[ + - + -
+ - + - +
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
+ - + - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - + - -
- - - - -
+ - + - +
- + - + -
- - ][ + -
+ - + - +
- + - ][ -
- + - + -
+ - - - +
- + - -
- ][ - - +
- - - - -
- - + - ]
[ + - # #
# # # # #
# # # # #
# # ]
186 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
187 [ + + ]: 8767304 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
188 [ - + + - : 67139 : void clear() { vch.clear(); m_read_pos = 0; }
- + - + ]
[ + + + +
# # # # ]
[ - + + -
- + + - -
+ + - + +
+ - + + +
- + + ][ -
+ + - - +
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ - +
- + - + ]
[ - - - -
+ - + - +
- + - + -
- - ][ + -
+ - + - +
- + - + -
# # # # ]
189 [ + - + - : 5700905 : value_type* data() { return vch.data() + m_read_pos; }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
# # # # #
# # # #
# ][ + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - ]
[ + - + -
+ - + - +
- ][ # # #
# # # # #
# # # # #
# # # ][ -
- + - - -
- - - - +
- ]
190 : 318 : const value_type* data() const { return vch.data() + m_read_pos; }
191 : :
192 : : inline void Compact()
193 : : {
194 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
195 : : m_read_pos = 0;
196 : : }
197 : :
198 : : bool Rewind(std::optional<size_type> n = std::nullopt)
199 : : {
200 : : // Total rewind if no size is passed
201 : : if (!n) {
202 : : m_read_pos = 0;
203 : : return true;
204 : : }
205 : : // Rewind by n characters if the buffer hasn't been compacted yet
206 : : if (*n > m_read_pos)
207 : : return false;
208 : : m_read_pos -= *n;
209 : : return true;
210 : : }
211 : :
212 : :
213 : : //
214 : : // Stream subset
215 : : //
216 [ + + ]: 15495 : bool eof() const { return size() == 0; }
217 [ # # ]: 0 : int in_avail() const { return size(); }
218 : :
219 : 1315209 : void read(std::span<value_type> dst)
220 : : {
221 [ + + ]: 1315209 : if (dst.size() == 0) return;
222 : :
223 : : // Read from the beginning of the buffer
224 [ + - ]: 1314137 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
225 [ + - + + ]: 1314137 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
226 [ + - ]: 30 : throw std::ios_base::failure("DataStream::read(): end of data");
227 : : }
228 [ + + ]: 1314107 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
229 [ + + ]: 1314107 : if (next_read_pos.value() == vch.size()) {
230 : 98168 : m_read_pos = 0;
231 [ + - ]: 98168 : vch.clear();
232 : 98168 : return;
233 : : }
234 : 1215939 : m_read_pos = next_read_pos.value();
235 : : }
236 : :
237 : 7 : void ignore(size_t num_ignore)
238 : : {
239 : : // Ignore from the beginning of the buffer
240 : 7 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
241 [ + - + + ]: 7 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
242 [ + - ]: 1 : throw std::ios_base::failure("DataStream::ignore(): end of data");
243 : : }
244 [ + + ]: 6 : if (next_read_pos.value() == vch.size()) {
245 : 3 : m_read_pos = 0;
246 [ + + ]: 3 : vch.clear();
247 : 3 : return;
248 : : }
249 : 3 : m_read_pos = next_read_pos.value();
250 : : }
251 : :
252 : 32559455 : void write(std::span<const value_type> src)
253 : : {
254 : : // Write to the end of the buffer
255 : 32559455 : vch.insert(vch.end(), src.begin(), src.end());
256 : 32559455 : }
257 : :
258 : : template<typename T>
259 : 12207614 : DataStream& operator<<(const T& obj)
260 : : {
261 [ + - ][ + - : 12177320 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
- - - - +
- + - + -
+ - + - +
- - - - -
- - + - +
- - - + -
+ - + - +
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + - +
- - - - -
- - + - +
- + - + -
+ - - - -
- + - + -
+ - + - -
- ][ + - +
- + - + -
+ - ][ + -
+ - + - -
- + - + -
+ - - - +
- + - - -
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
# # # # #
# # # # #
# # ][ + -
+ - # # #
# ][ + - +
- + - + -
# # # # #
# ]
262 : 6375235 : return (*this);
263 : : }
264 : :
265 : : template<typename T>
266 : 468459 : DataStream& operator>>(T&& obj)
267 : : {
268 [ + + ][ + - : 468229 : ::Unserialize(*this, obj);
+ - + - +
- + + +
+ ][ + - +
+ + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - -
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + + +
+ + - + -
+ - + - +
- + - +
- ][ + - +
- - + - +
- + + - +
- - + + -
+ - + - +
- - + + -
- + + - +
- - + - +
+ - + - ]
[ - - + -
- - - - -
- - - - -
- - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
- - - - +
- + - + -
+ - + - ]
[ + - + +
+ + + + #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
# # # # ]
[ + - + -
+ - # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
+ - - - -
- - - + -
+ - + - +
- + - + -
+ - + + -
- + - + -
+ - - + +
- - - - -
- - - - -
- - - - -
+ - - - -
- - - - -
- - - - -
- - - -
- ]
269 : 281990 : return (*this);
270 : : }
271 : :
272 : : /**
273 : : * XOR the contents of this stream with a certain key.
274 : : *
275 : : * @param[in] key The key used to XOR the data in this stream.
276 : : */
277 : 111180 : void Xor(const std::vector<unsigned char>& key)
278 : : {
279 : 111180 : util::Xor(MakeWritableByteSpan(*this), MakeByteSpan(key));
280 : 111180 : }
281 : :
282 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
283 : : size_t GetMemoryUsage() const noexcept;
284 : : };
285 : :
286 : : template <typename IStream>
287 : : class BitStreamReader
288 : : {
289 : : private:
290 : : IStream& m_istream;
291 : :
292 : : /// Buffered byte read in from the input stream. A new byte is read into the
293 : : /// buffer when m_offset reaches 8.
294 : : uint8_t m_buffer{0};
295 : :
296 : : /// Number of high order bits in m_buffer already returned by previous
297 : : /// Read() calls. The next bit to be returned is at this offset from the
298 : : /// most significant bit position.
299 : : int m_offset{8};
300 : :
301 : : public:
302 [ + - ]: 211 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
303 : :
304 : : /** Read the specified number of bits from the stream. The data is returned
305 : : * in the nbits least significant bits of a 64-bit uint.
306 : : */
307 : 23862 : uint64_t Read(int nbits) {
308 [ + - ]: 23862 : if (nbits < 0 || nbits > 64) {
309 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
310 : : }
311 : :
312 : : uint64_t data = 0;
313 [ + + ]: 58889 : while (nbits > 0) {
314 [ + + ]: 35028 : if (m_offset == 8) {
315 : 13842 : m_istream >> m_buffer;
316 : 13841 : m_offset = 0;
317 : : }
318 : :
319 [ + + ]: 35027 : int bits = std::min(8 - m_offset, nbits);
320 : 35027 : data <<= bits;
321 : 35027 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
322 : 35027 : m_offset += bits;
323 : 35027 : nbits -= bits;
324 : : }
325 : 23861 : return data;
326 : : }
327 : : };
328 : :
329 : : template <typename OStream>
330 : : class BitStreamWriter
331 : : {
332 : : private:
333 : : OStream& m_ostream;
334 : :
335 : : /// Buffered byte waiting to be written to the output stream. The byte is
336 : : /// written buffer when m_offset reaches 8 or Flush() is called.
337 : : uint8_t m_buffer{0};
338 : :
339 : : /// Number of high order bits in m_buffer already written by previous
340 : : /// Write() calls and not yet flushed to the stream. The next bit to be
341 : : /// written to is at this offset from the most significant bit position.
342 : : int m_offset{0};
343 : :
344 : : public:
345 [ + - ]: 236 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
346 : :
347 : 236 : ~BitStreamWriter()
348 : : {
349 : 236 : Flush();
350 : 236 : }
351 : :
352 : : /** Write the nbits least significant bits of a 64-bit int to the output
353 : : * stream. Data is buffered until it completes an octet.
354 : : */
355 : 873 : void Write(uint64_t data, int nbits) {
356 [ + - ]: 873 : if (nbits < 0 || nbits > 64) {
357 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
358 : : }
359 : :
360 [ + + ]: 2417 : while (nbits > 0) {
361 [ + + ]: 1544 : int bits = std::min(8 - m_offset, nbits);
362 : 1544 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
363 : 1544 : m_offset += bits;
364 : 1544 : nbits -= bits;
365 : :
366 [ + + ]: 1544 : if (m_offset == 8) {
367 : 709 : Flush();
368 : : }
369 : : }
370 : 873 : }
371 : :
372 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
373 : : * next byte boundary.
374 : : */
375 : 1181 : void Flush() {
376 [ + + ]: 1181 : if (m_offset == 0) {
377 : : return;
378 : : }
379 : :
380 : 944 : m_ostream << m_buffer;
381 : 944 : m_buffer = 0;
382 : 944 : m_offset = 0;
383 : : }
384 : : };
385 : :
386 : : /** Non-refcounted RAII wrapper for FILE*
387 : : *
388 : : * Will automatically close the file when it goes out of scope if not null.
389 : : * If you're returning the file pointer, return file.release().
390 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
391 : : */
392 : : class AutoFile
393 : : {
394 : : protected:
395 : : std::FILE* m_file;
396 : : std::vector<std::byte> m_xor;
397 : : std::optional<int64_t> m_position;
398 : :
399 : : public:
400 : : explicit AutoFile(std::FILE* file, std::vector<std::byte> data_xor={});
401 : :
402 [ + - + - : 18559 : ~AutoFile() { fclose(); }
+ - # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - ]
[ - + + - ]
[ # # ]
403 : :
404 : : // Disallow copies
405 : : AutoFile(const AutoFile&) = delete;
406 : : AutoFile& operator=(const AutoFile&) = delete;
407 : :
408 : 192 : bool feof() const { return std::feof(m_file); }
409 : :
410 : 18634 : int fclose()
411 : : {
412 [ + - ]: 18591 : if (auto rel{release()}) return std::fclose(rel);
413 : : return 0;
414 : : }
415 : :
416 : : /** Get wrapped FILE* with transfer of ownership.
417 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
418 : : * of this function to clean up the returned FILE*.
419 : : */
420 : 18634 : std::FILE* release()
421 : : {
422 : 18634 : std::FILE* ret{m_file};
423 : 18634 : m_file = nullptr;
424 [ + + ]: 18634 : return ret;
[ + - - - ]
425 : : }
426 : :
427 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
428 : : */
429 [ + - + - : 37031 : bool IsNull() const { return m_file == nullptr; }
+ - ]
[ - + + + ]
[ - + ][ - -
- + + - -
+ # # #
# ][ - - -
- - + - +
- + - + ]
430 : :
431 : : /** Continue with a different XOR key */
432 [ # # # # ]: 0 : void SetXor(std::vector<std::byte> data_xor) { m_xor = data_xor; }
433 : :
434 : : /** Implementation detail, only used internally. */
435 : : std::size_t detail_fread(std::span<std::byte> dst);
436 : :
437 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
438 : : void seek(int64_t offset, int origin);
439 : :
440 : : /** Find position within the file. Will throw if unknown. */
441 : : int64_t tell();
442 : :
443 : : /** Wrapper around FileCommit(). */
444 : : bool Commit();
445 : :
446 : : /** Wrapper around TruncateFile(). */
447 : : bool Truncate(unsigned size);
448 : :
449 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
450 : : void write_buffer(std::span<std::byte> src);
451 : :
452 : : //
453 : : // Stream subset
454 : : //
455 : : void read(std::span<std::byte> dst);
456 : : void ignore(size_t nSize);
457 : : void write(std::span<const std::byte> src);
458 : :
459 : : template <typename T>
460 : 27130 : AutoFile& operator<<(const T& obj)
461 : : {
462 [ + - + + : 26887 : ::Serialize(*this, obj);
+ - # # #
# # # ][ +
- + - + -
- + + - +
- ]
[ + - + - ]
[ + - # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # ]
[ + - - -
- - + - ]
463 : 10741 : return *this;
464 : : }
465 : :
466 : : template <typename T>
467 : 14791 : AutoFile& operator>>(T&& obj)
468 : : {
469 [ + - + + : 12254 : ::Unserialize(*this, obj);
+ - + + ]
[ + - # #
# # # # #
# # # #
# ][ - + +
- + - + -
- + + - -
+ # # ][ +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - +
- ]
[ + - + - ]
[ # # # #
# # # # #
# # # ]
470 : 8369 : return *this;
471 : : }
472 : : };
473 : :
474 : : using DataBuffer = std::vector<std::byte>;
475 : :
476 : : /** Wrapper around an AutoFile& that implements a ring buffer to
477 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
478 : : *
479 : : * Will automatically close the file when it goes out of scope if not null.
480 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
481 : : */
482 : 52 : class BufferedFile
483 : : {
484 : : private:
485 : : AutoFile& m_src;
486 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
487 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
488 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
489 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
490 : : DataBuffer vchBuf;
491 : :
492 : : //! read data from the source to fill the buffer
493 : 284 : bool Fill() {
494 [ + + ]: 284 : unsigned int pos = nSrcPos % vchBuf.size();
495 : 284 : unsigned int readNow = vchBuf.size() - pos;
496 : 284 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
497 [ + + ]: 284 : if (nAvail < readNow)
498 : 247 : readNow = nAvail;
499 [ + - ]: 284 : if (readNow == 0)
500 : : return false;
501 : 284 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
502 [ + + ]: 284 : if (nBytes == 0) {
503 [ - + + - ]: 1 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
504 : : }
505 : 283 : nSrcPos += nBytes;
506 : 283 : return true;
507 : : }
508 : :
509 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
510 : : //! filling the buffer from the file so that at least one byte is available.
511 : : //! Return a pointer to the available buffer data and the number of bytes
512 : : //! (which may be less than the requested length) that may be accessed
513 : : //! beginning at that pointer.
514 : 3210 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
515 : : {
516 [ - + ]: 3210 : assert(m_read_pos <= nSrcPos);
517 [ + + ]: 3210 : if (m_read_pos + length > nReadLimit) {
518 [ + - ]: 2 : throw std::ios_base::failure("Attempt to position past buffer limit");
519 : : }
520 : : // If there are no bytes available, read from the file.
521 [ + + + - ]: 3208 : if (m_read_pos == nSrcPos && length > 0) Fill();
522 : :
523 : 3207 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
524 : 3207 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
525 : 3207 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
526 : 3207 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
527 : 3207 : m_read_pos += advance;
528 : 3207 : return std::make_pair(&vchBuf[buffer_offset], advance);
529 : : }
530 : :
531 : : public:
532 : 53 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
533 : 53 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
534 : : {
535 [ + + ]: 53 : if (nRewindIn >= nBufSize)
536 [ + - ]: 1 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
537 : 53 : }
538 : :
539 : : //! check whether we're at the end of the source file
540 : 3882 : bool eof() const {
541 [ + + + + ]: 3882 : return m_read_pos == nSrcPos && m_src.feof();
542 : : }
543 : :
544 : : //! read a number of bytes
545 : 2598 : void read(std::span<std::byte> dst)
546 : : {
547 [ + + ]: 5293 : while (dst.size() > 0) {
548 : 2697 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
549 : 2695 : memcpy(dst.data(), buffer_pointer, length);
550 : 2695 : dst = dst.subspan(length);
551 : : }
552 : 2596 : }
553 : :
554 : : //! Move the read position ahead in the stream to the given position.
555 : : //! Use SetPos() to back up in the stream, not SkipTo().
556 : 620 : void SkipTo(const uint64_t file_pos)
557 : : {
558 [ + - ]: 620 : assert(file_pos >= m_read_pos);
559 [ + + ]: 1132 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
560 : 619 : }
561 : :
562 : : //! return the current reading position
563 : 5201 : uint64_t GetPos() const {
564 [ + - + - : 5201 : return m_read_pos;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ # # #
# # # ]
565 : : }
566 : :
567 : : //! rewind to a given reading position
568 : 668 : bool SetPos(uint64_t nPos) {
569 [ + + - + : 668 : size_t bufsize = vchBuf.size();
- + - + -
+ - + - +
- + - + +
- ][ # # ]
570 [ + + - + : 668 : if (nPos + bufsize < nSrcPos) {
- + - + -
+ - + - +
- + - + +
- ][ # # ]
571 : : // rewinding too far, rewind as far as possible
572 : 67 : m_read_pos = nSrcPos - bufsize;
573 : 67 : return false;
574 : : }
575 [ + + - + : 598 : if (nPos > nSrcPos) {
- + - + -
+ - + ]
[ # # ]
576 : : // can't go this far forward, go as far as possible
577 : 17 : m_read_pos = nSrcPos;
578 : 17 : return false;
579 : : }
580 : 584 : m_read_pos = nPos;
581 : 584 : return true;
582 : : }
583 : :
584 : : //! prevent reading beyond a certain position
585 : : //! no argument removes the limit
586 : 3195 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
587 [ + - + - : 3194 : if (nPos < m_read_pos)
+ - + - +
- + - +
- ][ # # ]
588 : : return false;
589 : 3195 : nReadLimit = nPos;
590 [ + - ]: 3195 : return true;
591 : : }
592 : :
593 : : template<typename T>
594 : 2598 : BufferedFile& operator>>(T&& obj) {
595 [ + - + - : 2598 : ::Unserialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- + - + -
- + + - +
- + - + -
+ - - + +
- ][ # # #
# # # #
# ]
596 : 2596 : return (*this);
597 : : }
598 : :
599 : : //! search for a given byte in the stream, and remain positioned on it
600 : 650 : void FindByte(std::byte byte)
601 : : {
602 : : // For best performance, avoid mod operation within the loop.
603 : 650 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
604 : 718 : while (true) {
605 [ + + ]: 718 : if (m_read_pos == nSrcPos) {
606 : : // No more bytes available; read from the file into the buffer,
607 : : // setting nSrcPos to one beyond the end of the new data.
608 : : // Throws exception if end-of-file reached.
609 : 81 : Fill();
610 : : }
611 [ + + ]: 718 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
612 [ + + ]: 718 : const auto it_start{vchBuf.begin() + buf_offset};
613 : 718 : const auto it_find{std::find(it_start, it_start + len, byte)};
614 [ + + ]: 718 : const size_t inc{size_t(std::distance(it_start, it_find))};
615 : 718 : m_read_pos += inc;
616 [ + + ]: 718 : if (inc < len) break;
617 : 68 : buf_offset += inc;
618 [ + + ]: 68 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
619 : : }
620 : 650 : }
621 : : };
622 : :
623 : : /**
624 : : * Wrapper that buffers reads from an underlying stream.
625 : : * Requires underlying stream to support read() and detail_fread() calls
626 : : * to support fixed-size and variable-sized reads, respectively.
627 : : */
628 : : template <typename S>
629 : 917 : class BufferedReader
630 : : {
631 : : S& m_src;
632 : : DataBuffer m_buf;
633 : : size_t m_buf_pos;
634 : :
635 : : public:
636 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
637 : 917 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
638 : : requires std::is_rvalue_reference_v<S&&>
639 [ + - + - : 917 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
+ - ]
[ + - + - ]
640 : :
641 : 1836 : void read(std::span<std::byte> dst)
642 : : {
643 [ + + + + ]: 2753 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
644 : 917 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
645 : 917 : m_buf_pos += available;
646 : 917 : dst = dst.subspan(available);
647 : : }
648 [ + + ]: 1836 : if (dst.size()) {
649 [ - + ]: 919 : assert(m_buf_pos == m_buf.size());
650 : 919 : m_src.read(dst);
651 : :
652 : 917 : m_buf_pos = 0;
653 : 917 : m_buf.resize(m_src.detail_fread(m_buf));
654 : : }
655 : 1834 : }
656 : :
657 : : template <typename T>
658 : 917 : BufferedReader& operator>>(T&& obj)
659 : : {
660 [ + - + - ]: 916 : Unserialize(*this, obj);
[ + - ]
661 : 916 : return *this;
662 : : }
663 : : };
664 : :
665 : : /**
666 : : * Wrapper that buffers writes to an underlying stream.
667 : : * Requires underlying stream to support write_buffer() method
668 : : * for efficient buffer flushing and obfuscation.
669 : : */
670 : : template <typename S>
671 : : class BufferedWriter
672 : : {
673 : : S& m_dst;
674 : : DataBuffer m_buf;
675 : : size_t m_buf_pos{0};
676 : :
677 : : public:
678 [ + - + - : 14604 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - ][ + -
+ - + - +
- ]
679 : :
680 : 14604 : ~BufferedWriter() { flush(); }
681 : :
682 : 21770 : void flush()
683 : : {
684 [ + + ]: 21770 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
685 : 21770 : m_buf_pos = 0;
686 : 21770 : }
687 : :
688 : 245156 : void write(std::span<const std::byte> src)
689 : : {
690 [ + + + + ]: 980625 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
691 : 245157 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
692 : 245157 : m_buf_pos += available;
693 [ + + ]: 245157 : if (m_buf_pos == m_buf.size()) flush();
694 : 245157 : src = src.subspan(available);
695 : : }
696 : 245156 : }
697 : :
698 : : template <typename T>
699 : 58156 : BufferedWriter& operator<<(const T& obj)
700 : : {
701 [ + - + - ]: 43553 : Serialize(*this, obj);
[ + - - -
- - + - +
- + - + -
+ - + - +
- ]
702 : 29215 : return *this;
703 : : }
704 : : };
705 : :
706 : : #endif // BITCOIN_STREAMS_H
|