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 <assert.h>
16 : : #include <cstddef>
17 : : #include <cstdio>
18 : : #include <ios>
19 : : #include <limits>
20 : : #include <optional>
21 : : #include <stdint.h>
22 : : #include <string.h>
23 : : #include <string>
24 : : #include <utility>
25 : : #include <vector>
26 : :
27 : : namespace util {
28 : 8184627 : inline void Xor(std::span<std::byte> write, std::span<const std::byte> key, size_t key_offset = 0)
29 : : {
30 [ + - ]: 8184627 : if (key.size() == 0) {
31 : : return;
32 : : }
33 : 8184627 : key_offset %= key.size();
34 : :
35 [ + + ]: 208830504 : for (size_t i = 0, j = key_offset; i != write.size(); i++) {
36 [ + + ]: 200645877 : 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 [ + + ]: 200645877 : if (j == key.size())
43 : 21140047 : 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 : 523544 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
61 : : {
62 [ - + ]: 523544 : if(nPos > vchData.size())
63 : 0 : vchData.resize(nPos);
64 : 523544 : }
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 [ + - ][ + - : 461019 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - + - ]
[ + - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
- - - - +
- + - + -
+ - + - +
- + - -
- ]
71 : : {
72 [ + - ][ + - : 461019 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - + - ]
[ + - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
- - - - +
- + - + -
+ - + - +
- + - -
- ]
73 : 158534 : }
74 : 5789824 : void write(std::span<const std::byte> src)
75 : : {
76 [ - + ]: 5789824 : assert(nPos <= vchData.size());
77 [ + + ]: 5789824 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
78 [ - + ]: 5789824 : if (nOverwrite) {
79 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
80 : : }
81 [ + + ]: 5789824 : if (nOverwrite < src.size()) {
82 : 5775136 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
83 : : }
84 : 5789824 : nPos += src.size();
85 : 5789824 : }
86 : : template <typename T>
87 : 996971 : VectorWriter& operator<<(const T& obj)
88 : : {
89 [ + - + - : 996971 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - +
- ]
90 : 86166 : 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 unsigned char> m_data;
104 : :
105 : : public:
106 : : /**
107 : : * @param[in] data Referenced byte vector to overwrite/append
108 : : */
109 [ + - + + ]: 615932 : explicit SpanReader(std::span<const unsigned char> data) : m_data{data} {}
[ + - + -
+ - + - +
- + - + +
+ - + - +
- + - + -
+ - + - ]
[ + + + +
+ - + - +
+ # # # #
# # # # #
# # # # #
# # # # ]
[ + + # # ]
110 : :
111 : : template<typename T>
112 : 3021032 : SpanReader& operator>>(T&& obj)
113 : : {
114 [ + + + + : 3018777 : ::Unserialize(*this, obj);
+ + + + +
+ + + + -
+ - + - +
+ + - + -
+ + + - +
+ + - + -
+ + + - +
+ + + + +
+ - + - +
+ + - + +
+ - + - +
- + - + +
+ + + - +
+ + + ][ +
- + - + +
+ + + + +
- + - + -
+ + + + ]
[ + + + +
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
[ + - ]
115 : 730729 : return (*this);
116 : : }
117 : :
118 [ + + ]: 3096 : size_t size() const { return m_data.size(); }
119 [ - + - + : 155217 : bool empty() const { return m_data.empty(); }
# # # # ]
[ + + + +
+ + + + ]
[ + + ]
120 : :
121 : 3890097 : void read(std::span<std::byte> dst)
122 : : {
123 [ + - ]: 3890097 : if (dst.size() == 0) {
124 : : return;
125 : : }
126 : :
127 : : // Read from the beginning of the buffer
128 [ + + ]: 3890097 : if (dst.size() > m_data.size()) {
129 [ + - ]: 43808 : throw std::ios_base::failure("SpanReader::read(): end of data");
130 : : }
131 : 3846289 : memcpy(dst.data(), m_data.data(), dst.size());
132 : 3846289 : m_data = m_data.subspan(dst.size());
133 : : }
134 : :
135 : : void ignore(size_t n)
136 : : {
137 : : m_data = m_data.subspan(n);
138 : : }
139 : : };
140 : :
141 : : /** Double ended buffer combining vector and stream-like interfaces.
142 : : *
143 : : * >> and << read and write unformatted data using the above serialization templates.
144 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
145 : : */
146 [ + - + - : 27682421 : class DataStream
+ + ][ + - ]
[ + + + + ]
147 : : {
148 : : protected:
149 : : using vector_type = SerializeData;
150 : : vector_type vch;
151 : : vector_type::size_type m_read_pos{0};
152 : :
153 : : public:
154 : : typedef vector_type::allocator_type allocator_type;
155 : : typedef vector_type::size_type size_type;
156 : : typedef vector_type::difference_type difference_type;
157 : : typedef vector_type::reference reference;
158 : : typedef vector_type::const_reference const_reference;
159 : : typedef vector_type::value_type value_type;
160 : : typedef vector_type::iterator iterator;
161 : : typedef vector_type::const_iterator const_iterator;
162 : : typedef vector_type::reverse_iterator reverse_iterator;
163 : :
164 [ + - ]: 273067 : explicit DataStream() = default;
165 : 1065824 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
166 : 11728098 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
167 : :
168 : 259 : std::string str() const
169 : : {
170 : 518 : return std::string{UCharCast(data()), UCharCast(data() + size())};
171 : : }
172 : :
173 : :
174 : : //
175 : : // Vector subset
176 : : //
177 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
178 : 1101221 : iterator begin() { return vch.begin() + m_read_pos; }
179 : : const_iterator end() const { return vch.end(); }
180 [ + - ]: 579381 : iterator end() { return vch.end(); }
[ # # # # ]
181 [ + + + + : 9377478 : size_type size() const { return vch.size() - m_read_pos; }
# # # # #
# # # # #
# # # # #
# # # #
# ][ + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + - +
- + - ][ +
- - + +
- ][ # # #
# # # #
# ][ + + ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
- - + - -
- # # # #
# # # # ]
[ - - - -
+ - + - +
- + - + -
+ - ][ # #
# # # # #
# # # #
# ]
182 [ - + - + : 1308754 : bool empty() const { return vch.size() == m_read_pos; }
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + ][ + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # ][ +
+ + + + +
+ + + + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + ][ +
+ + + + +
+ + ][ - -
- - - - -
- - - +
+ ]
183 : 423314 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
184 [ # # # # ]: 4709443 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
[ + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - ][ + -
+ - + - +
- + - ][ +
- + - + -
+ - + - -
- + - -
- ][ # # #
# # # # #
# # # # ]
[ + - # #
# # # # #
# # # # #
# # ]
185 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
186 [ + + ]: 3531902 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
187 [ # # # # : 4110461 : void clear() { vch.clear(); m_read_pos = 0; }
# # # # ]
[ + + + +
# # # # ]
[ # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- - - ][ #
# # # # #
# # # # #
# # # #
# ]
188 [ + - + - : 5629612 : value_type* data() { return vch.data() + m_read_pos; }
+ - + - ]
[ + - ]
[ + - + - ]
[ + - + -
+ - + - +
- ][ + - +
- + - + -
- - + - -
- # # # #
# # # # ]
[ - - - -
+ - + - +
- + - + -
+ - ][ # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # ]
189 : 79110 : const value_type* data() const { return vch.data() + m_read_pos; }
190 : :
191 : : inline void Compact()
192 : : {
193 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
194 : : m_read_pos = 0;
195 : : }
196 : :
197 : : bool Rewind(std::optional<size_type> n = std::nullopt)
198 : : {
199 : : // Total rewind if no size is passed
200 : : if (!n) {
201 : : m_read_pos = 0;
202 : : return true;
203 : : }
204 : : // Rewind by n characters if the buffer hasn't been compacted yet
205 : : if (*n > m_read_pos)
206 : : return false;
207 : : m_read_pos -= *n;
208 : : return true;
209 : : }
210 : :
211 : :
212 : : //
213 : : // Stream subset
214 : : //
215 [ # # ]: 0 : bool eof() const { return size() == 0; }
216 [ + + ]: 298 : int in_avail() const { return size(); }
217 : :
218 : 362770493 : void read(std::span<value_type> dst)
219 : : {
220 [ + + ]: 362770493 : if (dst.size() == 0) return;
221 : :
222 : : // Read from the beginning of the buffer
223 [ + - ]: 360015269 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
224 [ + - + + ]: 360015269 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
225 [ + - ]: 196059 : throw std::ios_base::failure("DataStream::read(): end of data");
226 : : }
227 [ + + ]: 359819210 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
228 [ + + ]: 359819210 : if (next_read_pos.value() == vch.size()) {
229 : 23324928 : m_read_pos = 0;
230 [ + - ]: 23324928 : vch.clear();
231 : 23324928 : return;
232 : : }
233 : 336494282 : m_read_pos = next_read_pos.value();
234 : : }
235 : :
236 : 1035988 : void ignore(size_t num_ignore)
237 : : {
238 : : // Ignore from the beginning of the buffer
239 : 1035988 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
240 [ + - + + ]: 1035988 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
241 [ + - ]: 2078 : throw std::ios_base::failure("DataStream::ignore(): end of data");
242 : : }
243 [ + + ]: 1033910 : if (next_read_pos.value() == vch.size()) {
244 : 974 : m_read_pos = 0;
245 [ + + ]: 974 : vch.clear();
246 : 974 : return;
247 : : }
248 : 1032936 : m_read_pos = next_read_pos.value();
249 : : }
250 : :
251 : 195368565 : void write(std::span<const value_type> src)
252 : : {
253 : : // Write to the end of the buffer
254 : 195368565 : vch.insert(vch.end(), src.begin(), src.end());
255 : 195368565 : }
256 : :
257 : : template<typename T>
258 : 46437618 : DataStream& operator<<(const T& obj)
259 : : {
260 [ + - + - : 44425310 : ::Serialize(*this, obj);
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # ][ - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - ]
[ + - + -
+ - + - +
- ][ + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
- - - - +
- + - + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
261 : 7106497 : return (*this);
262 : : }
263 : :
264 : : template<typename T>
265 : 54790722 : DataStream& operator>>(T&& obj)
266 : : {
267 [ + + ][ + + : 54754310 : ::Unserialize(*this, obj);
+ + + + ]
[ + - + +
+ - + - +
- ][ + + +
+ + + + +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
- + + + +
+ + + + ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - +
+ ][ + + +
+ # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ -
- + - + +
- - + + +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ +
+ + + + +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
+ - - - -
- - ][ - -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - - -
- - - + -
+ - + - +
- + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
268 : 24868869 : return (*this);
269 : : }
270 : :
271 : : /**
272 : : * XOR the contents of this stream with a certain key.
273 : : *
274 : : * @param[in] key The key used to XOR the data in this stream.
275 : : */
276 : 7342130 : void Xor(const std::vector<unsigned char>& key)
277 : : {
278 : 7342130 : util::Xor(MakeWritableByteSpan(*this), MakeByteSpan(key));
279 : 7342130 : }
280 : :
281 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
282 : : size_t GetMemoryUsage() const noexcept;
283 : : };
284 : :
285 : : template <typename IStream>
286 : : class BitStreamReader
287 : : {
288 : : private:
289 : : IStream& m_istream;
290 : :
291 : : /// Buffered byte read in from the input stream. A new byte is read into the
292 : : /// buffer when m_offset reaches 8.
293 : : uint8_t m_buffer{0};
294 : :
295 : : /// Number of high order bits in m_buffer already returned by previous
296 : : /// Read() calls. The next bit to be returned is at this offset from the
297 : : /// most significant bit position.
298 : : int m_offset{8};
299 : :
300 : : public:
301 [ + - ]: 1491 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
302 : :
303 : : /** Read the specified number of bits from the stream. The data is returned
304 : : * in the nbits least significant bits of a 64-bit uint.
305 : : */
306 : 1975760 : uint64_t Read(int nbits) {
307 [ + - ]: 1975760 : if (nbits < 0 || nbits > 64) {
308 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
309 : : }
310 : :
311 : : uint64_t data = 0;
312 [ + + ]: 5820634 : while (nbits > 0) {
313 [ + + ]: 3860559 : if (m_offset == 8) {
314 : 2257321 : m_istream >> m_buffer;
315 : 2241636 : m_offset = 0;
316 : : }
317 : :
318 [ + + ]: 3844874 : int bits = std::min(8 - m_offset, nbits);
319 : 3844874 : data <<= bits;
320 : 3844874 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
321 : 3844874 : m_offset += bits;
322 : 3844874 : nbits -= bits;
323 : : }
324 : 1960075 : return data;
325 : : }
326 : : };
327 : :
328 : : template <typename OStream>
329 : : class BitStreamWriter
330 : : {
331 : : private:
332 : : OStream& m_ostream;
333 : :
334 : : /// Buffered byte waiting to be written to the output stream. The byte is
335 : : /// written buffer when m_offset reaches 8 or Flush() is called.
336 : : uint8_t m_buffer{0};
337 : :
338 : : /// Number of high order bits in m_buffer already written by previous
339 : : /// Write() calls and not yet flushed to the stream. The next bit to be
340 : : /// written to is at this offset from the most significant bit position.
341 : : int m_offset{0};
342 : :
343 : : public:
344 [ + + ]: 210 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
345 : :
346 : 210 : ~BitStreamWriter()
347 : : {
348 : 210 : Flush();
349 : 210 : }
350 : :
351 : : /** Write the nbits least significant bits of a 64-bit int to the output
352 : : * stream. Data is buffered until it completes an octet.
353 : : */
354 : 63749 : void Write(uint64_t data, int nbits) {
355 [ + - ]: 63749 : if (nbits < 0 || nbits > 64) {
356 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
357 : : }
358 : :
359 [ + + ]: 186276 : while (nbits > 0) {
360 [ + + ]: 122527 : int bits = std::min(8 - m_offset, nbits);
361 : 122527 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
362 : 122527 : m_offset += bits;
363 : 122527 : nbits -= bits;
364 : :
365 [ + + ]: 122527 : if (m_offset == 8) {
366 : 66872 : Flush();
367 : : }
368 : : }
369 : 63749 : }
370 : :
371 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
372 : : * next byte boundary.
373 : : */
374 : 67292 : void Flush() {
375 [ + + ]: 67292 : if (m_offset == 0) {
376 : : return;
377 : : }
378 : :
379 : 67026 : m_ostream << m_buffer;
380 : 67026 : m_buffer = 0;
381 : 67026 : m_offset = 0;
382 : : }
383 : : };
384 : :
385 : : /** Non-refcounted RAII wrapper for FILE*
386 : : *
387 : : * Will automatically close the file when it goes out of scope if not null.
388 : : * If you're returning the file pointer, return file.release().
389 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
390 : : */
391 : : class AutoFile
392 : : {
393 : : protected:
394 : : std::FILE* m_file;
395 : : std::vector<std::byte> m_xor;
396 : : std::optional<int64_t> m_position;
397 : :
398 : : public:
399 : : explicit AutoFile(std::FILE* file, std::vector<std::byte> data_xor={});
400 : :
401 [ + - ]: 190507 : ~AutoFile() { fclose(); }
[ - + - - ]
402 : :
403 : : // Disallow copies
404 : : AutoFile(const AutoFile&) = delete;
405 : : AutoFile& operator=(const AutoFile&) = delete;
406 : :
407 : 9733 : bool feof() const { return std::feof(m_file); }
408 : :
409 : 190862 : int fclose()
410 : : {
411 [ # # ]: 170877 : if (auto rel{release()}) return std::fclose(rel);
412 : : return 0;
413 : : }
414 : :
415 : : /** Get wrapped FILE* with transfer of ownership.
416 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
417 : : * of this function to clean up the returned FILE*.
418 : : */
419 : 190907 : std::FILE* release()
420 : : {
421 : 190907 : std::FILE* ret{m_file};
422 : 190907 : m_file = nullptr;
423 [ # # ]: 190907 : return ret;
[ + + + + ]
424 : : }
425 : :
426 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
427 : : */
428 [ + + ]: 375787 : bool IsNull() const { return m_file == nullptr; }
[ + + + + ]
[ # # # #
# # # # #
# # # ][ -
- - - - +
+ + - + -
- ]
429 : :
430 : : /** Continue with a different XOR key */
431 [ + - + - ]: 1233 : void SetXor(std::vector<std::byte> data_xor) { m_xor = data_xor; }
432 : :
433 : : /** Implementation detail, only used internally. */
434 : : std::size_t detail_fread(std::span<std::byte> dst);
435 : :
436 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
437 : : void seek(int64_t offset, int origin);
438 : :
439 : : /** Find position within the file. Will throw if unknown. */
440 : : int64_t tell();
441 : :
442 : : /** Wrapper around FileCommit(). */
443 : : bool Commit();
444 : :
445 : : /** Wrapper around TruncateFile(). */
446 : : bool Truncate(unsigned size);
447 : :
448 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
449 : : void write_buffer(std::span<std::byte> src);
450 : :
451 : : //
452 : : // Stream subset
453 : : //
454 : : void read(std::span<std::byte> dst);
455 : : void ignore(size_t nSize);
456 : : void write(std::span<const std::byte> src);
457 : :
458 : : template <typename T>
459 : 985142 : AutoFile& operator<<(const T& obj)
460 : : {
461 [ + - ][ - - : 981079 : ::Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ + + + + ]
[ + + + -
+ + + - +
- + - + +
+ - ][ # #
# # # # #
# ][ # # #
# # # #
# ]
462 : 288559 : return *this;
463 : : }
464 : :
465 : : template <typename T>
466 : 2344479 : AutoFile& operator>>(T&& obj)
467 : : {
468 [ + + + + ]: 2335548 : ::Unserialize(*this, obj);
[ # # ][ - -
+ + + + +
+ + - + +
+ + + - +
- - - + -
- - - - ]
[ + - + -
+ - ][ + +
+ + + + +
+ + + + +
+ + + + ]
[ + + + +
+ + + + ]
[ + + + +
+ + + + +
+ + + ]
469 : 1284976 : return *this;
470 : : }
471 : : };
472 : :
473 : : using DataBuffer = std::vector<std::byte>;
474 : :
475 : : /** Wrapper around an AutoFile& that implements a ring buffer to
476 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
477 : : *
478 : : * Will automatically close the file when it goes out of scope if not null.
479 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
480 : : */
481 : 688 : class BufferedFile
482 : : {
483 : : private:
484 : : AutoFile& m_src;
485 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
486 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
487 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
488 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
489 : : DataBuffer vchBuf;
490 : :
491 : : //! read data from the source to fill the buffer
492 : 348679 : bool Fill() {
493 [ + + ]: 348679 : unsigned int pos = nSrcPos % vchBuf.size();
494 : 348679 : unsigned int readNow = vchBuf.size() - pos;
495 : 348679 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
496 [ + + ]: 348679 : if (nAvail < readNow)
497 : 315938 : readNow = nAvail;
498 [ + - ]: 348679 : if (readNow == 0)
499 : : return false;
500 : 348679 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
501 [ + + ]: 348489 : if (nBytes == 0) {
502 [ + + + - ]: 6179 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
503 : : }
504 : 344643 : nSrcPos += nBytes;
505 : 344643 : return true;
506 : : }
507 : :
508 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
509 : : //! filling the buffer from the file so that at least one byte is available.
510 : : //! Return a pointer to the available buffer data and the number of bytes
511 : : //! (which may be less than the requested length) that may be accessed
512 : : //! beginning at that pointer.
513 : 5079214 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
514 : : {
515 [ - + ]: 5079214 : assert(m_read_pos <= nSrcPos);
516 [ + + ]: 5079214 : if (m_read_pos + length > nReadLimit) {
517 [ + - ]: 21240 : throw std::ios_base::failure("Attempt to position past buffer limit");
518 : : }
519 : : // If there are no bytes available, read from the file.
520 [ + + + - ]: 5057974 : if (m_read_pos == nSrcPos && length > 0) Fill();
521 : :
522 : 5054580 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
523 : 5054580 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
524 : 5054580 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
525 : 5054580 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
526 : 5054580 : m_read_pos += advance;
527 : 5054580 : return std::make_pair(&vchBuf[buffer_offset], advance);
528 : : }
529 : :
530 : : public:
531 : 709 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
532 : 709 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
533 : : {
534 [ + + ]: 709 : if (nRewindIn >= nBufSize)
535 [ + - ]: 21 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
536 : 709 : }
537 : :
538 : : //! check whether we're at the end of the source file
539 : 900013 : bool eof() const {
540 [ + + + + ]: 900013 : return m_read_pos == nSrcPos && m_src.feof();
541 : : }
542 : :
543 : : //! read a number of bytes
544 : 4687224 : void read(std::span<std::byte> dst)
545 : : {
546 [ + + ]: 9481420 : while (dst.size() > 0) {
547 : 4817404 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
548 : 4794196 : memcpy(dst.data(), buffer_pointer, length);
549 : 4794196 : dst = dst.subspan(length);
550 : : }
551 : 4664016 : }
552 : :
553 : : //! Move the read position ahead in the stream to the given position.
554 : : //! Use SetPos() to back up in the stream, not SkipTo().
555 : 262355 : void SkipTo(const uint64_t file_pos)
556 : : {
557 [ + - ]: 262355 : assert(file_pos >= m_read_pos);
558 [ + + ]: 522739 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
559 : 260929 : }
560 : :
561 : : //! return the current reading position
562 : 1221527 : uint64_t GetPos() const {
563 [ + + + + : 1221527 : return m_read_pos;
+ - ]
564 : : }
565 : :
566 : : //! rewind to a given reading position
567 : 990919 : bool SetPos(uint64_t nPos) {
568 [ + + ]: 990919 : size_t bufsize = vchBuf.size();
569 [ + + ]: 990919 : if (nPos + bufsize < nSrcPos) {
570 : : // rewinding too far, rewind as far as possible
571 : 334 : m_read_pos = nSrcPos - bufsize;
572 : 334 : return false;
573 : : }
574 [ + + ]: 990585 : if (nPos > nSrcPos) {
575 : : // can't go this far forward, go as far as possible
576 : 1524 : m_read_pos = nSrcPos;
577 : 1524 : return false;
578 : : }
579 : 989061 : m_read_pos = nPos;
580 : 989061 : return true;
581 : : }
582 : :
583 : : //! prevent reading beyond a certain position
584 : : //! no argument removes the limit
585 : 1163873 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
586 [ + + ]: 264055 : if (nPos < m_read_pos)
587 : : return false;
588 : 1163438 : nReadLimit = nPos;
589 [ + + ]: 1163438 : return true;
590 : : }
591 : :
592 : : template<typename T>
593 : 1581476 : BufferedFile& operator>>(T&& obj) {
594 [ + + + + ]: 1581476 : ::Unserialize(*this, obj);
[ + + + +
+ + + + ]
595 : 1531323 : return (*this);
596 : : }
597 : :
598 : : //! search for a given byte in the stream, and remain positioned on it
599 : 901403 : void FindByte(std::byte byte)
600 : : {
601 : : // For best performance, avoid mod operation within the loop.
602 : 901403 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
603 : 1109965 : while (true) {
604 [ + + ]: 1109965 : if (m_read_pos == nSrcPos) {
605 : : // No more bytes available; read from the file into the buffer,
606 : : // setting nSrcPos to one beyond the end of the new data.
607 : : // Throws exception if end-of-file reached.
608 : 210742 : Fill();
609 : : }
610 [ + + ]: 1109323 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
611 [ + + ]: 1109323 : const auto it_start{vchBuf.begin() + buf_offset};
612 : 1109323 : const auto it_find{std::find(it_start, it_start + len, byte)};
613 [ + + ]: 1109323 : const size_t inc{size_t(std::distance(it_start, it_find))};
614 : 1109323 : m_read_pos += inc;
615 [ + + ]: 1109323 : if (inc < len) break;
616 : 208562 : buf_offset += inc;
617 [ + + ]: 208562 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
618 : : }
619 : 900761 : }
620 : : };
621 : :
622 : : /**
623 : : * Wrapper that buffers reads from an underlying stream.
624 : : * Requires underlying stream to support read() and detail_fread() calls
625 : : * to support fixed-size and variable-sized reads, respectively.
626 : : */
627 : : template <typename S>
628 : 0 : class BufferedReader
629 : : {
630 : : S& m_src;
631 : : DataBuffer m_buf;
632 : : size_t m_buf_pos;
633 : :
634 : : public:
635 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
636 : 0 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
637 : : requires std::is_rvalue_reference_v<S&&>
638 [ # # # # ]: 0 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
639 : :
640 : 0 : void read(std::span<std::byte> dst)
641 : : {
642 [ # # # # ]: 0 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
643 : 0 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
644 : 0 : m_buf_pos += available;
645 : 0 : dst = dst.subspan(available);
646 : : }
647 [ # # ]: 0 : if (dst.size()) {
648 [ # # ]: 0 : assert(m_buf_pos == m_buf.size());
649 : 0 : m_src.read(dst);
650 : :
651 : 0 : m_buf_pos = 0;
652 : 0 : m_buf.resize(m_src.detail_fread(m_buf));
653 : : }
654 : 0 : }
655 : :
656 : : template <typename T>
657 : 0 : BufferedReader& operator>>(T&& obj)
658 : : {
659 [ # # ]: 0 : Unserialize(*this, obj);
660 : 0 : return *this;
661 : : }
662 : : };
663 : :
664 : : /**
665 : : * Wrapper that buffers writes to an underlying stream.
666 : : * Requires underlying stream to support write_buffer() method
667 : : * for efficient buffer flushing and obfuscation.
668 : : */
669 : : template <typename S>
670 : : class BufferedWriter
671 : : {
672 : : S& m_dst;
673 : : DataBuffer m_buf;
674 : : size_t m_buf_pos{0};
675 : :
676 : : public:
677 [ + - + - : 157916 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
678 : :
679 : 157916 : ~BufferedWriter() { flush(); }
680 : :
681 : 231590 : void flush()
682 : : {
683 [ + + ]: 231590 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
684 : 231590 : m_buf_pos = 0;
685 : 231590 : }
686 : :
687 : 2881751 : void write(std::span<const std::byte> src)
688 : : {
689 [ + - + + ]: 11527004 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
690 : 2881751 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
691 : 2881751 : m_buf_pos += available;
692 [ - + ]: 2881751 : if (m_buf_pos == m_buf.size()) flush();
693 : 2881751 : src = src.subspan(available);
694 : : }
695 : 2881751 : }
696 : :
697 : : template <typename T>
698 : 622515 : BufferedWriter& operator<<(const T& obj)
699 : : {
700 [ - - + - : 464599 : Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- ]
701 : 316778 : return *this;
702 : : }
703 : : };
704 : :
705 : : #endif // BITCOIN_STREAMS_H
|