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/check.h>
13 : : #include <util/log.h>
14 : : #include <util/obfuscation.h>
15 : : #include <util/overflow.h>
16 : : #include <util/syserror.h>
17 : :
18 : : #include <algorithm>
19 : : #include <cassert>
20 : : #include <cstddef>
21 : : #include <cstdint>
22 : : #include <cstdio>
23 : : #include <cstring>
24 : : #include <ios>
25 : : #include <limits>
26 : : #include <optional>
27 : : #include <string>
28 : : #include <vector>
29 : :
30 : : /* Minimal stream for overwriting and/or appending to an existing byte vector
31 : : *
32 : : * The referenced vector will grow as necessary
33 : : */
34 : : class VectorWriter
35 : : {
36 : : public:
37 : : /**
38 : : * @param[in,out] vchDataIn Referenced byte vector to overwrite/append
39 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will
40 : : * initially grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
41 : : */
42 : 6032614 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
43 : : {
44 [ - + - + ]: 6032614 : if(nPos > vchData.size())
45 : 0 : vchData.resize(nPos);
46 : 6032614 : }
47 : : /**
48 : : * @param[in,out] vchDataIn Referenced byte vector to overwrite/append
49 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will
50 : : * initially grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
51 : : * @param[in] args A list of items to serialize starting at nPosIn.
52 : : */
53 : : template <typename... Args>
54 [ + - ]: 5812813 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
[ + - + - ]
[ + - + -
+ - ][ + -
+ - + - +
- + - ]
[ + - + -
- - + - -
- - - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
+ - ]
55 : : {
56 [ + - ]: 5812813 : ::SerializeMany(*this, std::forward<Args>(args)...);
[ + - + - ]
[ + - + -
+ - ][ + -
+ - + - +
- + - ]
[ + - + -
- - + - -
- - - + -
+ - - - -
- - - + -
+ - - - -
- - - + -
+ - + - +
- + - + -
+ - ]
57 : 4869706 : }
58 : 38332870 : void write(std::span<const std::byte> src)
59 : : {
60 [ - + - + ]: 38332870 : assert(nPos <= vchData.size());
61 [ + + ]: 38332870 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
62 [ - + ]: 38332870 : if (nOverwrite) {
63 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
64 : : }
65 [ + + ]: 38332870 : if (nOverwrite < src.size()) {
66 : 38271678 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
67 : : }
68 : 38332870 : nPos += src.size();
69 : 38332870 : }
70 : : template <typename T>
71 : 27842688 : VectorWriter& operator<<(const T& obj)
72 : : {
73 [ + - + - : 10995624 : ::Serialize(*this, obj);
+ - + - ]
[ + - + -
+ - + - +
- + - +
- ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
74 : 121327 : return (*this);
75 : : }
76 : :
77 : : private:
78 : : std::vector<unsigned char>& vchData;
79 : : size_t nPos;
80 : : };
81 : :
82 : : /** Minimal stream for reading from an existing byte array by std::span.
83 : : */
84 : : class SpanReader
85 : : {
86 : : private:
87 : : std::span<const std::byte> m_data;
88 : :
89 : : public:
90 : : /**
91 : : * @param[in] data Referenced byte vector to overwrite/append
92 : : */
93 : 2361102 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
94 [ + + ]: 10627510 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
[ + + + - ]
95 : :
96 : : template<typename T>
97 : 44455687 : SpanReader& operator>>(T&& obj)
98 : : {
99 [ + + ]: 43333928 : ::Unserialize(*this, obj);
[ + + + + ]
[ + - + +
+ + ][ + +
+ + + + +
+ ][ + - +
- + - + +
+ - ]
[ # # # #
# # # # #
# # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
[ + + + +
+ + + + +
+ + + + -
+ - + - +
+ + - + +
+ - + - +
+ + - + +
+ + + - +
+ + - + +
+ - + - +
- + - + -
+ + + + +
- + + +
+ ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
[ - - + +
+ - + + +
+ + + + +
+ + + - +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - + - +
+ + + + -
+ + + + +
+ + + + +
- - - - -
- + + + -
+ - + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + ]
100 : 28589643 : return (*this);
101 : : }
102 : :
103 : 160562 : size_t size() const { return m_data.size(); }
[ - + + +
+ + + + -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
104 [ # # ][ + + ]: 1226986 : bool empty() const { return m_data.empty(); }
[ + + + + ]
[ + + + +
+ + + + +
+ + + + +
+ + + + ]
[ - - - -
- - - - -
- - - - -
- - - - +
+ ]
105 : :
106 : 302950292 : void read(std::span<std::byte> dst)
107 : : {
108 [ + + ]: 302950292 : if (dst.size() == 0) {
109 : : return;
110 : : }
111 : :
112 : : // Read from the beginning of the buffer
113 [ + + ]: 299116017 : if (dst.size() > m_data.size()) {
114 [ + - ]: 930808 : throw std::ios_base::failure("SpanReader::read(): end of data");
115 : : }
116 : 298650613 : memcpy(dst.data(), m_data.data(), dst.size());
117 : 298650613 : m_data = m_data.subspan(dst.size());
118 : : }
119 : :
120 : 8932 : void ignore(size_t n)
121 : : {
122 [ + + ]: 8932 : if (n > m_data.size()) {
123 [ + - ]: 13734 : throw std::ios_base::failure("SpanReader::ignore(): end of data");
124 : : }
125 : 2065 : m_data = m_data.subspan(n);
126 : 2065 : }
127 : : };
128 : :
129 : : /** Minimal stream for writing to an existing span of bytes.
130 : : */
131 : : class SpanWriter
132 : : {
133 : : private:
134 : : std::span<std::byte> m_dest;
135 : :
136 : : public:
137 : 0 : explicit SpanWriter(std::span<std::byte> dest) : m_dest{dest} {}
138 : : template <typename... Args>
139 : : SpanWriter(std::span<std::byte> dest, Args&&... args) : SpanWriter{dest}
140 : : {
141 : : ::SerializeMany(*this, std::forward<Args>(args)...);
142 : : }
143 : :
144 : 0 : void write(std::span<const std::byte> src)
145 : : {
146 [ # # ]: 0 : if (src.size() > m_dest.size()) {
147 [ # # ]: 0 : throw std::ios_base::failure("SpanWriter::write(): exceeded buffer size");
148 : : }
149 : 0 : memcpy(m_dest.data(), src.data(), src.size());
150 : 0 : m_dest = m_dest.subspan(src.size());
151 : 0 : }
152 : :
153 : : template<typename T>
154 : 0 : SpanWriter& operator<<(const T& obj)
155 : : {
156 [ # # # # ]: 0 : ::Serialize(*this, obj);
157 : 0 : return *this;
158 : : }
159 : : };
160 : :
161 : : /** Double ended buffer combining vector and stream-like interfaces.
162 : : *
163 : : * >> and << read and write unformatted data using the above serialization templates.
164 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
165 : : */
166 [ + - ][ + - ]: 35586580 : class DataStream
[ + + + - ]
[ # # # #
# # ][ - -
- - - - ]
167 : : {
168 : : protected:
169 : : using vector_type = SerializeData;
170 : : vector_type vch;
171 : : vector_type::size_type m_read_pos{0};
172 : :
173 : : public:
174 : : typedef vector_type::allocator_type allocator_type;
175 : : typedef vector_type::size_type size_type;
176 : : typedef vector_type::difference_type difference_type;
177 : : typedef vector_type::reference reference;
178 : : typedef vector_type::const_reference const_reference;
179 : : typedef vector_type::value_type value_type;
180 : : typedef vector_type::iterator iterator;
181 : : typedef vector_type::const_iterator const_iterator;
182 : : typedef vector_type::reverse_iterator reverse_iterator;
183 : :
184 [ # # ][ + - : 21430 : explicit DataStream() = default;
+ - + - ]
[ + - + -
+ - + - +
- + + +
- ]
185 : 9561 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
186 : 9561 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
187 : :
188 : 329 : std::string str() const
189 : : {
190 : 987 : return std::string{UCharCast(data()), UCharCast(data() + size())};
191 : : }
192 : :
193 : : //
194 : : // Vector subset
195 : : //
196 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
197 : 411094 : iterator begin() { return vch.begin() + m_read_pos; }
198 : : const_iterator end() const { return vch.end(); }
199 [ + - ]: 245871 : iterator end() { return vch.end(); }
[ # # # # ]
200 [ - + ]: 67069491 : size_type size() const { return vch.size() - m_read_pos; }
[ - + + + ]
[ - + + - ]
[ - - - -
- + ][ - +
- + - + +
+ ][ - + +
- - + +
- ][ - - -
+ + + - -
- - ]
[ - + + -
- + - + -
+ + - ]
[ - + + -
- + - + +
- - + ]
[ - + + -
- + + - -
+ - + ]
[ - + + -
- + + - -
+ + - - +
+ - ]
[ - - - -
- - - + +
- - + + -
- - - - ]
[ # # # #
# # # # #
# # # # #
# # # # #
# ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - + + -
- + + - -
+ - + + -
- + + - -
+ + - - +
+ - - + -
+ + - ]
[ - - - -
- - - - -
+ + - - -
- - - + +
- - + - +
+ - - - -
- - + +
- ]
[ - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - -
- ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + - + +
- - + + -
- + + - -
+ + - - -
- - ]
[ - + + -
- + + - -
+ - + + -
- + - + +
- - + + -
- + + - -
+ + - - +
+ - - - -
- - + + -
- + + - -
- - - ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
201 [ - + - + : 108855536 : bool empty() const { return vch.size() == m_read_pos; }
- + - + ]
[ # # # #
# # # # ]
[ - + + +
- + + + -
+ + + - +
+ + - + +
+ ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + ]
202 : 1576073 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
203 [ + - ]: 17617120 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
[ # # # # ]
[ + - + -
+ - + - ]
[ + - + -
+ - + - +
- ]
[ + - + -
+ - + - +
- + - ]
[ - - - -
- - - - +
- + - - -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - -
- - - - -
+ - + - -
- + - + -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - - - -
- - - - -
- - ]
204 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
205 [ + + ]: 3867594 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
206 [ # # # # ]: 152887400 : void clear() { vch.clear(); m_read_pos = 0; }
[ - + - + ]
[ # # # #
# # ]
207 [ - + ]: 78556594 : value_type* data() { return vch.data() + m_read_pos; }
[ - + - + ]
[ - + - +
- + ][ - +
- + - + -
+ ][ - - -
- - + - +
- - ]
[ # # # #
# # # # #
# # # #
# ]
[ - + - +
- + - + -
+ - + - +
- + ]
[ - + - +
- + - + -
+ - + - +
- + - + ]
[ # # # #
# # # # #
# # # # #
# # # # #
# ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ - + -
- ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - +
- + - - ]
208 [ - + ]: 25042 : const value_type* data() const { return vch.data() + m_read_pos; }
209 : :
210 : : //
211 : : // Stream subset
212 : : //
213 : 194996491 : void read(std::span<value_type> dst)
214 : : {
215 [ + + ]: 194996491 : if (dst.size() == 0) return;
216 : :
217 : : // Read from the beginning of the buffer
218 [ + - ]: 194978840 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
219 [ + - - + : 194978840 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
+ + ]
220 [ + - ]: 20994 : throw std::ios_base::failure("DataStream::read(): end of data");
221 : : }
222 [ - + ]: 194968343 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
223 [ - + + + ]: 194968343 : if (next_read_pos.value() == vch.size()) {
224 : : // If fully consumed, reset to empty state.
225 [ + - ]: 24421432 : clear();
226 : 24421432 : return;
227 : : }
228 : 170546911 : m_read_pos = next_read_pos.value();
229 : : }
230 : :
231 : 731970 : void ignore(size_t num_ignore)
232 : : {
233 : : // Ignore from the beginning of the buffer
234 : 731970 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
235 [ + - - + : 731970 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
+ + ]
236 [ + - ]: 3538 : throw std::ios_base::failure("DataStream::ignore(): end of data");
237 : : }
238 [ + + ]: 730201 : if (next_read_pos.value() == vch.size()) {
239 : : // If all bytes are ignored, reset to empty state.
240 [ + + ]: 259 : clear();
241 : 259 : return;
242 : : }
243 : 729942 : m_read_pos = next_read_pos.value();
244 : : }
245 : :
246 : 307190725 : void write(std::span<const value_type> src)
247 : : {
248 : : // Write to the end of the buffer
249 : 307190725 : vch.insert(vch.end(), src.begin(), src.end());
250 : 307190725 : }
251 : :
252 : : template<typename T>
253 : 109026643 : DataStream& operator<<(const T& obj)
254 : : {
255 [ + - ]: 119381561 : ::Serialize(*this, obj);
[ + - + - ]
[ + - - -
- - ][ + -
+ - + - +
- ]
[ # # # #
# # # # #
# # # #
# ]
[ + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ - - - -
- - - - -
- - - - -
- - + - +
- + - +
- ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - ]
[ - - - -
- - - - -
- - - - -
- - + - +
- + - + -
+ - + - +
- + - +
- ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ]
[ - - - -
- - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - + -
+ - - - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ + - + -
+ - + - +
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- + - + -
- - - - -
- - - - -
- - - - +
- + - + -
+ - + - +
- - - - -
- - + - +
- - - + -
+ - - - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - ]
256 : 60003746 : return (*this);
257 : : }
258 : :
259 : : template <typename T>
260 : 51279265 : DataStream& operator>>(T&& obj)
261 : : {
262 [ + + ]: 51191848 : ::Unserialize(*this, obj);
[ + + + + ]
[ + - + -
+ - + - +
- ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ]
[ + - + +
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ]
263 : 20510643 : return (*this);
264 : : }
265 : :
266 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
267 : : size_t GetMemoryUsage() const noexcept;
268 : : };
269 : :
270 : : // Require empty scratch streams on entry and reset them on exit.
271 : : class ScopedDataStreamUsage
272 : : {
273 : : DataStream& m_stream;
274 : :
275 : : public:
276 [ - + - + ]: 51540605 : explicit ScopedDataStreamUsage(DataStream& stream) : m_stream{stream} { assert(m_stream.empty()); }
277 : :
278 : : ScopedDataStreamUsage(const ScopedDataStreamUsage&) = delete;
279 : : ScopedDataStreamUsage& operator=(const ScopedDataStreamUsage&) = delete;
280 : :
281 [ + + ]: 51540605 : ~ScopedDataStreamUsage() { m_stream.clear(); }
282 : : };
283 : :
284 : : template <typename IStream>
285 : : class BitStreamReader
286 : : {
287 : : private:
288 : : IStream& m_istream;
289 : :
290 : : /// Buffered byte read in from the input stream. A new byte is read into the
291 : : /// buffer when m_offset reaches 8.
292 : : uint8_t m_buffer{0};
293 : :
294 : : /// Number of high order bits in m_buffer already returned by previous
295 : : /// Read() calls. The next bit to be returned is at this offset from the
296 : : /// most significant bit position.
297 : : int m_offset{8};
298 : :
299 : : public:
300 [ + - ]: 1727 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
301 : :
302 : : /** Read the specified number of bits from the stream. The data is returned
303 : : * in the nbits least significant bits of a 64-bit uint.
304 : : */
305 : 2201504 : uint64_t Read(int nbits) {
306 [ + - ]: 2201504 : if (nbits < 0 || nbits > 64) {
307 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
308 : : }
309 : :
310 : : uint64_t data = 0;
311 [ + + ]: 6461913 : while (nbits > 0) {
312 [ + + ]: 4275135 : if (m_offset == 8) {
313 : 2487900 : m_istream >> m_buffer;
314 : 2473174 : m_offset = 0;
315 : : }
316 : :
317 [ + + ]: 4260409 : int bits = std::min(8 - m_offset, nbits);
318 : 4260409 : data <<= bits;
319 : 4260409 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
320 : 4260409 : m_offset += bits;
321 : 4260409 : nbits -= bits;
322 : : }
323 : 2186778 : return data;
324 : : }
325 : : };
326 : :
327 : : template <typename OStream>
328 : : class BitStreamWriter
329 : : {
330 : : private:
331 : : OStream& m_ostream;
332 : :
333 : : /// Buffered byte waiting to be written to the output stream. The byte is
334 : : /// written buffer when m_offset reaches 8 or Flush() is called.
335 : : uint8_t m_buffer{0};
336 : :
337 : : /// Number of high order bits in m_buffer already written by previous
338 : : /// Write() calls and not yet flushed to the stream. The next bit to be
339 : : /// written to is at this offset from the most significant bit position.
340 : : int m_offset{0};
341 : :
342 : : public:
343 [ + + ][ + - ]: 89915 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
344 : :
345 : 89915 : ~BitStreamWriter()
346 : : {
347 : 89915 : Flush();
348 : 89915 : }
349 : :
350 : : /** Write the nbits least significant bits of a 64-bit int to the output
351 : : * stream. Data is buffered until it completes an octet.
352 : : */
353 : 299616 : void Write(uint64_t data, int nbits) {
354 [ + - ]: 299616 : if (nbits < 0 || nbits > 64) {
355 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
356 : : }
357 : :
358 [ + + ]: 864785 : while (nbits > 0) {
359 [ + + ]: 565169 : int bits = std::min(8 - m_offset, nbits);
360 : 565169 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
361 : 565169 : m_offset += bits;
362 : 565169 : nbits -= bits;
363 : :
364 [ + + ]: 565169 : if (m_offset == 8) {
365 : 277284 : Flush();
366 : : }
367 : : }
368 : 299616 : }
369 : :
370 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
371 : : * next byte boundary.
372 : : */
373 : 457114 : void Flush() {
374 [ + + ]: 457114 : if (m_offset == 0) {
375 : : return;
376 : : }
377 : :
378 : 367145 : m_ostream << m_buffer;
379 : 367145 : m_buffer = 0;
380 : 367145 : m_offset = 0;
381 : : }
382 : : };
383 : :
384 : : /** Non-refcounted RAII wrapper for FILE*
385 : : *
386 : : * Will automatically close the file when it goes out of scope if not null.
387 : : * If you're returning the file pointer, return file.release().
388 : : * If you need to close the file early, use autofile.fclose() instead of fclose(underlying_FILE).
389 : : *
390 : : * @note If the file has been written to, then the caller must close it
391 : : * explicitly with the `fclose()` method, check if it returns an error and treat
392 : : * such an error as if the `write()` method failed. The OS's `fclose(3)` may
393 : : * fail to flush to disk data that has been previously written, rendering the
394 : : * file corrupt.
395 : : */
396 : : class AutoFile
397 : : {
398 : : protected:
399 : : std::FILE* m_file;
400 : : Obfuscation m_obfuscation;
401 : : std::optional<int64_t> m_position;
402 : : bool m_was_written{false};
403 : :
404 : : public:
405 : : explicit AutoFile(std::FILE* file, const Obfuscation& obfuscation = {});
406 : :
407 : 1203736 : ~AutoFile()
408 : : {
409 [ + + ]: 1203736 : if (m_was_written) {
410 : : // Callers that wrote to the file must have closed it explicitly
411 : : // with the fclose() method and checked that the close succeeded.
412 : : // This is because here in the destructor we have no way to signal
413 : : // errors from fclose() which, after write, could mean the file is
414 : : // corrupted and must be handled properly at the call site.
415 : : // Destructors in C++ cannot signal an error to the callers because
416 : : // they do not return a value and are not allowed to throw exceptions.
417 : 985150 : Assume(IsNull());
418 : : }
419 : :
420 [ + + ]: 196220 : if (fclose() != 0) {
421 : 2123 : LogError("Failed to close file: %s", SysErrorString(errno));
422 : : }
423 : 1203736 : }
424 : :
425 : : // Disallow copies
426 : : AutoFile(const AutoFile&) = delete;
427 : : AutoFile& operator=(const AutoFile&) = delete;
428 : :
429 : 9851 : bool feof() const { return std::feof(m_file); }
430 : :
431 : 2191427 : [[nodiscard]] int fclose()
432 : : {
433 [ + - ]: 1183496 : if (auto rel{release()}) return std::fclose(rel);
[ + - + - ]
[ + - + -
+ - ]
434 : : return 0;
435 : : }
436 : :
437 : : /** Get wrapped FILE* with transfer of ownership.
438 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
439 : : * of this function to clean up the returned FILE*.
440 : : */
441 : 2191444 : std::FILE* release()
442 : : {
443 : 2191444 : std::FILE* ret{m_file};
444 : 2191444 : m_file = nullptr;
445 [ # # ]: 2191444 : return ret;
[ + - - - ]
[ + - - -
- - ][ + +
+ + + + ]
[ + - + -
+ - - - ]
[ - - + -
- - - - -
- ]
446 : : }
447 : :
448 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
449 : : */
450 [ + + ]: 3382962 : bool IsNull() const { return m_file == nullptr; }
[ + + + + ]
[ - + - +
+ + ][ - -
- + + - -
- ]
[ - - - -
- + + + -
+ - + ]
451 : :
452 : : /** Continue with a different XOR key */
453 [ - + ]: 1448 : void SetObfuscation(const Obfuscation& obfuscation) { m_obfuscation = obfuscation; }
454 : :
455 : : /** Implementation detail, only used internally. */
456 : : std::size_t detail_fread(std::span<std::byte> dst);
457 : :
458 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
459 : : void seek(int64_t offset, int origin);
460 : :
461 : : /** Find position within the file. Will throw if unknown. */
462 : : int64_t tell();
463 : :
464 : : /** Return the size of the file. Will throw if unknown. */
465 : : int64_t size();
466 : :
467 : : /** Wrapper around FileCommit(). */
468 : : bool Commit();
469 : :
470 : : /** Wrapper around TruncateFile(). */
471 : : bool Truncate(uint64_t size);
472 : :
473 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
474 : : void write_buffer(std::span<std::byte> src);
475 : :
476 : : //
477 : : // Stream subset
478 : : //
479 : : void read(std::span<std::byte> dst);
480 : : void ignore(size_t nSize);
481 : : void write(std::span<const std::byte> src);
482 : :
483 : : template <typename T>
484 : 1382856 : AutoFile& operator<<(const T& obj)
485 : : {
486 [ + - ]: 1286852 : ::Serialize(*this, obj);
[ + + + + ]
[ + + + -
+ - ][ # #
# # # # #
# ]
[ + + + -
+ - + - +
- + - +
- ]
[ + - + +
+ - + + -
- - - - -
+ + + - ]
[ - - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
487 : 434529 : return *this;
488 : : }
489 : :
490 : : template <typename T>
491 : 9042795 : AutoFile& operator>>(T&& obj)
492 : : {
493 [ # # ]: 8933322 : ::Unserialize(*this, obj);
[ + + + + ]
[ + + + +
+ + ][ + +
+ + + + +
+ ][ + + +
+ + + + +
+ + ]
[ + + + +
+ + + + +
+ + + + +
+ + + + ]
[ - - + +
+ + + + +
- + + + +
+ + + - +
- - - + -
- - - - ]
494 : 4862634 : return *this;
495 : : }
496 : : };
497 : :
498 : : using DataBuffer = std::vector<std::byte>;
499 : :
500 : : /** Wrapper around an AutoFile& that implements a ring buffer to
501 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
502 : : *
503 : : * Will automatically close the file when it goes out of scope if not null.
504 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
505 : : */
506 : 820 : class BufferedFile
507 : : {
508 : : private:
509 : : AutoFile& m_src;
510 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
511 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
512 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
513 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
514 : : DataBuffer vchBuf;
515 : :
516 : : //! read data from the source to fill the buffer
517 : 271625 : bool Fill() {
518 [ - + ]: 271625 : unsigned int pos = nSrcPos % vchBuf.size();
519 : 271625 : unsigned int readNow = vchBuf.size() - pos;
520 : 271625 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
521 [ + + ]: 271625 : if (nAvail < readNow)
522 : 249186 : readNow = nAvail;
523 [ + - ]: 271625 : if (readNow == 0)
524 : : return false;
525 : 271625 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
526 [ + + ]: 271442 : if (nBytes == 0) {
527 [ + + + - ]: 5296 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
528 : : }
529 : 268794 : nSrcPos += nBytes;
530 : 268794 : return true;
531 : : }
532 : :
533 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
534 : : //! filling the buffer from the file so that at least one byte is available.
535 : : //! Return a pointer to the available buffer data and the number of bytes
536 : : //! (which may be less than the requested length) that may be accessed
537 : : //! beginning at that pointer.
538 : 5589179 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
539 : : {
540 [ - + ]: 5589179 : assert(m_read_pos <= nSrcPos);
541 [ + + ]: 5589179 : if (m_read_pos + length > nReadLimit) {
542 [ + - ]: 39086 : throw std::ios_base::failure("Attempt to position past buffer limit");
543 : : }
544 : : // If there are no bytes available, read from the file.
545 [ + + + - ]: 5569636 : if (m_read_pos == nSrcPos && length > 0) Fill();
546 : :
547 [ - + ]: 5567428 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
548 : 5567428 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
549 : 5567428 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
550 : 5567428 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
551 : 5567428 : m_read_pos += advance;
552 : 5567428 : return std::make_pair(&vchBuf[buffer_offset], advance);
553 : : }
554 : :
555 : : public:
556 : 832 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
557 : 832 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
558 : : {
559 [ + + ]: 832 : if (nRewindIn >= nBufSize)
560 [ + - ]: 24 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
561 : 832 : }
562 : :
563 : : //! check whether we're at the end of the source file
564 : 1520879 : bool eof() const {
565 [ + + + + ]: 1520879 : return m_read_pos == nSrcPos && m_src.feof();
566 : : }
567 : :
568 : : //! read a number of bytes
569 : 5122589 : void read(std::span<std::byte> dst)
570 : : {
571 [ + + ]: 10431204 : while (dst.size() > 0) {
572 : 5329679 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
573 : 5308615 : memcpy(dst.data(), buffer_pointer, length);
574 : 5308615 : dst = dst.subspan(length);
575 : : }
576 : 5101525 : }
577 : :
578 : : //! Move the read position ahead in the stream to the given position.
579 : : //! Use SetPos() to back up in the stream, not SkipTo().
580 : 261649 : void SkipTo(const uint64_t file_pos)
581 : : {
582 [ + - ]: 261649 : assert(file_pos >= m_read_pos);
583 [ + + ]: 520462 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
584 : 260962 : }
585 : :
586 : : //! return the current reading position
587 : 1845716 : uint64_t GetPos() const {
588 [ + + + + : 1845716 : return m_read_pos;
+ - ]
589 : : }
590 : :
591 : : //! rewind to a given reading position
592 : 1612881 : bool SetPos(uint64_t nPos) {
593 [ - + ]: 1612881 : size_t bufsize = vchBuf.size();
594 [ + + ]: 1612881 : if (nPos + bufsize < nSrcPos) {
595 : : // rewinding too far, rewind as far as possible
596 : 334 : m_read_pos = nSrcPos - bufsize;
597 : 334 : return false;
598 : : }
599 [ + + ]: 1612547 : if (nPos > nSrcPos) {
600 : : // can't go this far forward, go as far as possible
601 : 756 : m_read_pos = nSrcPos;
602 : 756 : return false;
603 : : }
604 : 1611791 : m_read_pos = nPos;
605 : 1611791 : return true;
606 : : }
607 : :
608 : : //! prevent reading beyond a certain position
609 : : //! no argument removes the limit
610 : 1783720 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
611 [ + + ]: 263067 : if (nPos < m_read_pos)
612 : : return false;
613 : 1783487 : nReadLimit = nPos;
614 [ + + ]: 1783487 : return true;
615 : : }
616 : :
617 : : template<typename T>
618 : 2197159 : BufferedFile& operator>>(T&& obj) {
619 [ + + + + ]: 2197159 : ::Unserialize(*this, obj);
[ + + + +
+ + + + ]
620 : 2157716 : return (*this);
621 : : }
622 : :
623 : : //! search for a given byte in the stream, and remain positioned on it
624 : 1521831 : void FindByte(std::byte byte)
625 : : {
626 : : // For best performance, avoid mod operation within the loop.
627 [ - + ]: 1521831 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
628 : 1576648 : while (true) {
629 [ + + ]: 1576648 : if (m_read_pos == nSrcPos) {
630 : : // No more bytes available; read from the file into the buffer,
631 : : // setting nSrcPos to one beyond the end of the new data.
632 : : // Throws exception if end-of-file reached.
633 : 56220 : Fill();
634 : : }
635 [ - + + + ]: 1576025 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
636 [ + + ]: 1576025 : const auto it_start{vchBuf.begin() + buf_offset};
637 : 1576025 : const auto it_find{std::find(it_start, it_start + len, byte)};
638 [ + + ]: 1576025 : const size_t inc{size_t(std::distance(it_start, it_find))};
639 : 1576025 : m_read_pos += inc;
640 [ + + ]: 1576025 : if (inc < len) break;
641 : 54817 : buf_offset += inc;
642 [ + + ]: 54817 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
643 : : }
644 : 1521208 : }
645 : : };
646 : :
647 : : /**
648 : : * Wrapper that buffers reads from an underlying stream.
649 : : * Requires underlying stream to support read() and detail_fread() calls
650 : : * to support fixed-size and variable-sized reads, respectively.
651 : : */
652 : : template <typename S>
653 : 89200 : class BufferedReader
654 : : {
655 : : S& m_src;
656 : : DataBuffer m_buf;
657 : : size_t m_buf_pos;
658 : :
659 : : public:
660 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
661 : 89200 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
662 : : requires std::is_rvalue_reference_v<S&&>
663 [ + - + - ]: 89200 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
664 : :
665 : 178400 : void read(std::span<std::byte> dst)
666 : : {
667 [ - + + + : 267600 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
+ + ]
668 : 89200 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
669 : 89200 : m_buf_pos += available;
670 : 89200 : dst = dst.subspan(available);
671 : : }
672 [ + + ]: 178400 : if (dst.size()) {
673 [ - + - + ]: 89200 : assert(m_buf_pos == m_buf.size());
674 : 89200 : m_src.read(dst);
675 : :
676 : 89200 : m_buf_pos = 0;
677 [ - + ]: 89200 : m_buf.resize(m_src.detail_fread(m_buf));
678 : : }
679 : 178400 : }
680 : :
681 : : template <typename T>
682 : 89200 : BufferedReader& operator>>(T&& obj)
683 : : {
684 [ + - ]: 89200 : Unserialize(*this, obj);
685 : 89200 : return *this;
686 : : }
687 : : };
688 : :
689 : : /**
690 : : * Wrapper that buffers writes to an underlying stream.
691 : : * Requires underlying stream to support write_buffer() method
692 : : * for efficient buffer flushing and obfuscation.
693 : : */
694 : : template <typename S>
695 : : class BufferedWriter
696 : : {
697 : : S& m_dst;
698 : : DataBuffer m_buf;
699 : : size_t m_buf_pos{0};
700 : :
701 : : public:
702 [ + - + - : 891680 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
703 : :
704 [ + - + - ]: 891680 : ~BufferedWriter() { flush(); }
705 : :
706 : 891680 : void flush()
707 : : {
708 [ + - - + ]: 891680 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
709 : 891680 : m_buf_pos = 0;
710 : 891680 : }
711 : :
712 : 15092785 : void write(std::span<const std::byte> src)
713 : : {
714 [ - + + - : 60371140 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
+ + ]
715 : 15092785 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
716 : 15092785 : m_buf_pos += available;
717 [ - + - + ]: 15092785 : if (m_buf_pos == m_buf.size()) flush();
718 : 15092785 : src = src.subspan(available);
719 : : }
720 : 15092785 : }
721 : :
722 : : template <typename T>
723 : 3555069 : BufferedWriter& operator<<(const T& obj)
724 : : {
725 : 2663389 : Serialize(*this, obj);
[ - - + -
+ - + - +
- + - + -
+ - + - +
- ]
726 : 1786022 : return *this;
727 : : }
728 : : };
729 : :
730 : : #endif // BITCOIN_STREAMS_H
|