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] vchDataIn Referenced byte vector to overwrite/append
39 : : * @param[in] nPosIn Starting position. Vector index where writes should start. The vector will initially
40 : : * grow as necessary to max(nPosIn, vec.size()). So to append, use vec.size().
41 : : */
42 : 640107 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
43 : : {
44 [ - + - + ]: 640107 : if(nPos > vchData.size())
45 : 0 : vchData.resize(nPos);
46 : 640107 : }
47 : : /*
48 : : * (other params same as above)
49 : : * @param[in] args A list of items to serialize starting at nPosIn.
50 : : */
51 : : template <typename... Args>
52 [ + - + - : 550282 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - - - -
- - - + -
+ - - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - ][ + - ]
[ + - + -
# # ][ + -
+ - + - ]
53 : : {
54 [ + - + - : 550282 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - - - -
- - - + -
+ - - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - ][ + - ]
[ + - + -
# # ][ + -
+ - + - ]
55 : 205932 : }
56 : 6817696 : void write(std::span<const std::byte> src)
57 : : {
58 [ - + - + ]: 6817696 : assert(nPos <= vchData.size());
59 [ + + ]: 6817696 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
60 [ - + ]: 6817696 : if (nOverwrite) {
61 : 0 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
62 : : }
63 [ + + ]: 6817696 : if (nOverwrite < src.size()) {
64 : 6759677 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
65 : : }
66 : 6817696 : nPos += src.size();
67 : 6817696 : }
68 : : template <typename T>
69 : 1873855 : VectorWriter& operator<<(const T& obj)
70 : : {
71 [ + - + - : 1761611 : ::Serialize(*this, obj);
+ - + - +
- + - +
- ][ + - +
- + - + -
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ]
72 : 164469 : return (*this);
73 : : }
74 : :
75 : : private:
76 : : std::vector<unsigned char>& vchData;
77 : : size_t nPos;
78 : : };
79 : :
80 : : /** Minimal stream for reading from an existing byte array by std::span.
81 : : */
82 : : class SpanReader
83 : : {
84 : : private:
85 : : std::span<const std::byte> m_data;
86 : :
87 : : public:
88 : : /**
89 : : * @param[in] data Referenced byte vector to overwrite/append
90 : : */
91 : 2322754 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
92 [ + + ]: 3746591 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
93 : :
94 : : template<typename T>
95 : 30103781 : SpanReader& operator>>(T&& obj)
96 : : {
97 [ + + + + : 30088353 : ::Unserialize(*this, obj);
+ + + + ]
[ + + # #
# # # # ]
[ + + + +
+ + ][ + +
+ + # # ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - +
+ ][ + + +
+ + + + +
+ + + + +
- + - + -
+ + + - +
+ + - + -
+ + + - +
+ + + + +
+ + + - +
+ + - + -
+ - + - +
- + + + +
+ - + + +
+ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ - -
+ + + - +
+ + + + +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ - + - +
+ + + + -
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + - - -
- - - + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ][ - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
+ - - - -
- - # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
98 : 16591433 : return (*this);
99 : : }
100 : :
101 [ + + + + : 248314 : size_t size() const { return m_data.size(); }
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + ]
102 [ + + ]: 2295462 : bool empty() const { return m_data.empty(); }
[ + + + + ]
[ - - - -
- - - - -
- - - - -
- - - - +
+ ][ + + +
+ + + + +
+ + + + +
+ + + +
+ ]
103 : :
104 : 287514068 : void read(std::span<std::byte> dst)
105 : : {
106 [ + + ]: 287514068 : if (dst.size() == 0) {
107 : : return;
108 : : }
109 : :
110 : : // Read from the beginning of the buffer
111 [ + + ]: 283325457 : if (dst.size() > m_data.size()) {
112 [ + - ]: 741156 : throw std::ios_base::failure("SpanReader::read(): end of data");
113 : : }
114 : 282954879 : memcpy(dst.data(), m_data.data(), dst.size());
115 : 282954879 : m_data = m_data.subspan(dst.size());
116 : : }
117 : :
118 : 2916 : void ignore(size_t n)
119 : : {
120 [ + + ]: 2916 : if (n > m_data.size()) {
121 [ + - ]: 1770 : throw std::ios_base::failure("SpanReader::ignore(): end of data");
122 : : }
123 : 2031 : m_data = m_data.subspan(n);
124 : 2031 : }
125 : : };
126 : :
127 : : /** Minimal stream for writing to an existing span of bytes.
128 : : */
129 : : class SpanWriter
130 : : {
131 : : private:
132 : : std::span<std::byte> m_dest;
133 : :
134 : : public:
135 : : explicit SpanWriter(std::span<std::byte> dest) : m_dest{dest} {}
136 : : template <typename... Args>
137 : : SpanWriter(std::span<std::byte> dest, Args&&... args) : SpanWriter{dest}
138 : : {
139 : : ::SerializeMany(*this, std::forward<Args>(args)...);
140 : : }
141 : :
142 : : void write(std::span<const std::byte> src)
143 : : {
144 : : if (src.size() > m_dest.size()) {
145 : : throw std::ios_base::failure("SpanWriter::write(): exceeded buffer size");
146 : : }
147 : : memcpy(m_dest.data(), src.data(), src.size());
148 : : m_dest = m_dest.subspan(src.size());
149 : : }
150 : :
151 : : template<typename T>
152 : : SpanWriter& operator<<(const T& obj)
153 : : {
154 : : ::Serialize(*this, obj);
155 : : return *this;
156 : : }
157 : : };
158 : :
159 : : /** Double ended buffer combining vector and stream-like interfaces.
160 : : *
161 : : * >> and << read and write unformatted data using the above serialization templates.
162 : : * Fills with data in linear time; some stringstream implementations take N^2 time.
163 : : */
164 [ + + + - ]: 34249519 : class DataStream
[ + - ][ - -
- - - - ]
165 : : {
166 : : protected:
167 : : using vector_type = SerializeData;
168 : : vector_type vch;
169 : : vector_type::size_type m_read_pos{0};
170 : :
171 : : public:
172 : : typedef vector_type::allocator_type allocator_type;
173 : : typedef vector_type::size_type size_type;
174 : : typedef vector_type::difference_type difference_type;
175 : : typedef vector_type::reference reference;
176 : : typedef vector_type::const_reference const_reference;
177 : : typedef vector_type::value_type value_type;
178 : : typedef vector_type::iterator iterator;
179 : : typedef vector_type::const_iterator const_iterator;
180 : : typedef vector_type::reverse_iterator reverse_iterator;
181 : :
182 : : explicit DataStream() = default;
183 : 9550 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
184 : 8819736 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
185 : :
186 : 357 : std::string str() const
187 : : {
188 : 1071 : return std::string{UCharCast(data()), UCharCast(data() + size())};
189 : : }
190 : :
191 : :
192 : : //
193 : : // Vector subset
194 : : //
195 : : const_iterator begin() const { return vch.begin() + m_read_pos; }
196 : 1850875 : iterator begin() { return vch.begin() + m_read_pos; }
197 : : const_iterator end() const { return vch.end(); }
198 [ + - ]: 962660 : iterator end() { return vch.end(); }
[ # # # # ]
199 [ - + + + : 38922528 : size_type size() const { return vch.size() - m_read_pos; }
- + + + -
+ + - - +
+ - - + +
+ - + + +
+ + + + +
+ + + +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - + + +
- + + + #
# # # # #
# # ][ - +
+ - - + -
+ - + +
- ][ - + +
- - + + -
- + + - -
+ + - ][ #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# ][ - + -
+ + - - +
- + + - -
+ - + - +
- + - - -
+ + - - +
+ - - + +
- - + + -
- - - - ]
[ - + + +
# # # # #
# ][ - - -
- - + # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ - +
# # # # #
# # # # #
# # ][ - +
- + + - -
+ - + ]
200 [ - + + + : 56732 : bool empty() const { return vch.size() == m_read_pos; }
- + + + -
+ + + - +
+ + ][ - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ ][ - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + -
+ ][ - + -
+ - + -
+ ]
201 : 601514 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
202 [ + - + - : 24073151 : void reserve(size_type n) { vch.reserve(n + m_read_pos); }
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- - - ][ +
- # # # #
# # # # #
# # # #
# ][ # # #
# # # # #
# # # # ]
[ # # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ + -
+ - - - -
- - - - -
- - - - +
- + - + -
+ - + - +
- - - - -
- - + - +
- - - + -
+ - - - -
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
+ - - - -
- - - - -
- - - - ]
203 : : const_reference operator[](size_type pos) const { return vch[pos + m_read_pos]; }
204 [ + + ]: 3425276 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
205 [ + - + - : 24441057 : void clear() { vch.clear(); m_read_pos = 0; }
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - + -
+ - + - +
- + - - -
# # # # #
# ][ + + +
+ # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # ][ # #
# # # # ]
206 [ - + - + : 44161938 : value_type* data() { return vch.data() + m_read_pos; }
- + - + -
+ - + - +
- + - + -
+ - + - +
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - + - +
- + - + ]
[ - + - +
- + - + -
+ - + - +
- + - - -
+ - + - +
- + - - ]
[ - + - +
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # ][ -
+ # # # #
# # # # ]
[ - + - +
- + - + -
+ - + - +
- + ][ - +
- + - + #
# # # # #
# # # # ]
207 [ - + ]: 64501 : const value_type* data() const { return vch.data() + m_read_pos; }
208 : :
209 : : inline void Compact()
210 : : {
211 : : vch.erase(vch.begin(), vch.begin() + m_read_pos);
212 : : m_read_pos = 0;
213 : : }
214 : :
215 : : bool Rewind(std::optional<size_type> n = std::nullopt)
216 : : {
217 : : // Total rewind if no size is passed
218 : : if (!n) {
219 : : m_read_pos = 0;
220 : : return true;
221 : : }
222 : : // Rewind by n characters if the buffer hasn't been compacted yet
223 : : if (*n > m_read_pos)
224 : : return false;
225 : : m_read_pos -= *n;
226 : : return true;
227 : : }
228 : :
229 : :
230 : : //
231 : : // Stream subset
232 : : //
233 [ - + + + ]: 321 : int in_avail() const { return size(); }
234 : :
235 : 171309900 : void read(std::span<value_type> dst)
236 : : {
237 [ + + ]: 171309900 : if (dst.size() == 0) return;
238 : :
239 : : // Read from the beginning of the buffer
240 [ + - ]: 171295917 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
241 [ + - - + : 171295917 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
+ + ]
242 [ + - ]: 20450 : throw std::ios_base::failure("DataStream::read(): end of data");
243 : : }
244 [ - + ]: 171285692 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
245 [ - + + + ]: 171285692 : if (next_read_pos.value() == vch.size()) {
246 : 21827885 : m_read_pos = 0;
247 [ + - ]: 21827885 : vch.clear();
248 : 21827885 : return;
249 : : }
250 : 149457807 : m_read_pos = next_read_pos.value();
251 : : }
252 : :
253 : 603669 : void ignore(size_t num_ignore)
254 : : {
255 : : // Ignore from the beginning of the buffer
256 : 603669 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
257 [ + - - + : 603669 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
+ + ]
258 [ + - ]: 4140 : throw std::ios_base::failure("DataStream::ignore(): end of data");
259 : : }
260 [ + + ]: 601599 : if (next_read_pos.value() == vch.size()) {
261 : 379 : m_read_pos = 0;
262 [ + + ]: 379 : vch.clear();
263 : 379 : return;
264 : : }
265 : 601220 : m_read_pos = next_read_pos.value();
266 : : }
267 : :
268 : 256285207 : void write(std::span<const value_type> src)
269 : : {
270 : : // Write to the end of the buffer
271 : 256285207 : vch.insert(vch.end(), src.begin(), src.end());
272 : 256285207 : }
273 : :
274 : : template<typename T>
275 : 89440145 : DataStream& operator<<(const T& obj)
276 : : {
277 [ + - + - : 80563345 : ::Serialize(*this, obj);
+ - + - +
- # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ - - -
- - - - -
- - - - -
- - - - -
- - - - +
- + - - -
- - - - -
- - - - -
+ - + - +
- + - + -
+ - - - -
- - - + -
+ - - - +
- + - - -
- - + - +
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - +
- + - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - ][ # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
- + - # #
# # # # #
# # # # #
# # # # #
# ][ + - #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # ][ -
- - - - -
- - - - -
- - - - -
+ - + - +
- + - + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ][ - - -
- - - - -
- - - - -
- - - + -
+ - + - +
- ]
278 : 15228867 : return (*this);
279 : : }
280 : :
281 : : template <typename T>
282 : 35450934 : DataStream& operator>>(T&& obj)
283 : : {
284 [ + + ]: 35416118 : ::Unserialize(*this, obj);
[ + + + + ]
[ + - + -
+ - ][ + +
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + + + +
+ + + + +
- - + + +
+ + + + +
+ - + + +
+ + + ][ +
- + - + -
+ - + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ]
285 : 13954767 : return (*this);
286 : : }
287 : :
288 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
289 : : size_t GetMemoryUsage() const noexcept;
290 : : };
291 : :
292 : : template <typename IStream>
293 : : class BitStreamReader
294 : : {
295 : : private:
296 : : IStream& m_istream;
297 : :
298 : : /// Buffered byte read in from the input stream. A new byte is read into the
299 : : /// buffer when m_offset reaches 8.
300 : : uint8_t m_buffer{0};
301 : :
302 : : /// Number of high order bits in m_buffer already returned by previous
303 : : /// Read() calls. The next bit to be returned is at this offset from the
304 : : /// most significant bit position.
305 : : int m_offset{8};
306 : :
307 : : public:
308 [ + - ]: 1735 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
309 : :
310 : : /** Read the specified number of bits from the stream. The data is returned
311 : : * in the nbits least significant bits of a 64-bit uint.
312 : : */
313 : 2141226 : uint64_t Read(int nbits) {
314 [ + - ]: 2141226 : if (nbits < 0 || nbits > 64) {
315 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
316 : : }
317 : :
318 : : uint64_t data = 0;
319 [ + + ]: 6286730 : while (nbits > 0) {
320 [ + + ]: 4158232 : if (m_offset == 8) {
321 : 2421408 : m_istream >> m_buffer;
322 : 2408680 : m_offset = 0;
323 : : }
324 : :
325 [ + + ]: 4145504 : int bits = std::min(8 - m_offset, nbits);
326 : 4145504 : data <<= bits;
327 : 4145504 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
328 : 4145504 : m_offset += bits;
329 : 4145504 : nbits -= bits;
330 : : }
331 : 2128498 : return data;
332 : : }
333 : : };
334 : :
335 : : template <typename OStream>
336 : : class BitStreamWriter
337 : : {
338 : : private:
339 : : OStream& m_ostream;
340 : :
341 : : /// Buffered byte waiting to be written to the output stream. The byte is
342 : : /// written buffer when m_offset reaches 8 or Flush() is called.
343 : : uint8_t m_buffer{0};
344 : :
345 : : /// Number of high order bits in m_buffer already written by previous
346 : : /// Write() calls and not yet flushed to the stream. The next bit to be
347 : : /// written to is at this offset from the most significant bit position.
348 : : int m_offset{0};
349 : :
350 : : public:
351 [ + + ]: 263 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
352 : :
353 : 263 : ~BitStreamWriter()
354 : : {
355 : 263 : Flush();
356 : 263 : }
357 : :
358 : : /** Write the nbits least significant bits of a 64-bit int to the output
359 : : * stream. Data is buffered until it completes an octet.
360 : : */
361 : 93811 : void Write(uint64_t data, int nbits) {
362 [ + - ]: 93811 : if (nbits < 0 || nbits > 64) {
363 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
364 : : }
365 : :
366 [ + + ]: 274228 : while (nbits > 0) {
367 [ + + ]: 180417 : int bits = std::min(8 - m_offset, nbits);
368 : 180417 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
369 : 180417 : m_offset += bits;
370 : 180417 : nbits -= bits;
371 : :
372 [ + + ]: 180417 : if (m_offset == 8) {
373 : 98235 : Flush();
374 : : }
375 : : }
376 : 93811 : }
377 : :
378 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
379 : : * next byte boundary.
380 : : */
381 : 98761 : void Flush() {
382 [ + + ]: 98761 : if (m_offset == 0) {
383 : : return;
384 : : }
385 : :
386 : 98435 : m_ostream << m_buffer;
387 : 98435 : m_buffer = 0;
388 : 98435 : m_offset = 0;
389 : : }
390 : : };
391 : :
392 : : /** Non-refcounted RAII wrapper for FILE*
393 : : *
394 : : * Will automatically close the file when it goes out of scope if not null.
395 : : * If you're returning the file pointer, return file.release().
396 : : * If you need to close the file early, use autofile.fclose() instead of fclose(underlying_FILE).
397 : : *
398 : : * @note If the file has been written to, then the caller must close it
399 : : * explicitly with the `fclose()` method, check if it returns an error and treat
400 : : * such an error as if the `write()` method failed. The OS's `fclose(3)` may
401 : : * fail to flush to disk data that has been previously written, rendering the
402 : : * file corrupt.
403 : : */
404 : : class AutoFile
405 : : {
406 : : protected:
407 : : std::FILE* m_file;
408 : : Obfuscation m_obfuscation;
409 : : std::optional<int64_t> m_position;
410 : : bool m_was_written{false};
411 : :
412 : : public:
413 : : explicit AutoFile(std::FILE* file, const Obfuscation& obfuscation = {});
414 : :
415 : 392833 : ~AutoFile()
416 : : {
417 [ + + ]: 392833 : if (m_was_written) {
418 : : // Callers that wrote to the file must have closed it explicitly
419 : : // with the fclose() method and checked that the close succeeded.
420 : : // This is because here in the destructor we have no way to signal
421 : : // errors from fclose() which, after write, could mean the file is
422 : : // corrupted and must be handled properly at the call site.
423 : : // Destructors in C++ cannot signal an error to the callers because
424 : : // they do not return a value and are not allowed to throw exceptions.
425 : 750111 : Assume(IsNull());
426 : : }
427 : :
428 [ + + ]: 14529 : if (fclose() != 0) {
429 : 2174 : LogError("Failed to close file: %s", SysErrorString(errno));
430 : : }
431 : 392833 : }
432 : :
433 : : // Disallow copies
434 : : AutoFile(const AutoFile&) = delete;
435 : : AutoFile& operator=(const AutoFile&) = delete;
436 : :
437 : 10788 : bool feof() const { return std::feof(m_file); }
438 : :
439 : 752730 : [[nodiscard]] int fclose()
440 : : {
441 [ + - ][ + - : 373959 : if (auto rel{release()}) return std::fclose(rel);
+ - + - ]
[ + - + - ]
442 : : return 0;
443 : : }
444 : :
445 : : /** Get wrapped FILE* with transfer of ownership.
446 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
447 : : * of this function to clean up the returned FILE*.
448 : : */
449 : 752754 : std::FILE* release()
450 : : {
451 : 752754 : std::FILE* ret{m_file};
452 : 752754 : m_file = nullptr;
453 [ # # ][ + + : 752754 : return ret;
+ + + + ]
[ + - - -
# # ][ + -
+ - + - -
- ][ # # #
# # # # #
# # ]
454 : : }
455 : :
456 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
457 : : */
458 [ + + + + : 1135489 : bool IsNull() const { return m_file == nullptr; }
+ + ]
[ + + - - ]
[ - - - -
- + + + -
+ - - -
- ][ # # #
# # # # #
# # # # #
# ][ - + #
# # # # #
# # ]
459 : :
460 : : /** Continue with a different XOR key */
461 : 1506 : void SetObfuscation(const Obfuscation& obfuscation) { m_obfuscation = obfuscation; }
462 : :
463 : : /** Implementation detail, only used internally. */
464 : : std::size_t detail_fread(std::span<std::byte> dst);
465 : :
466 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
467 : : void seek(int64_t offset, int origin);
468 : :
469 : : /** Find position within the file. Will throw if unknown. */
470 : : int64_t tell();
471 : :
472 : : /** Return the size of the file. Will throw if unknown. */
473 : : int64_t size();
474 : :
475 : : /** Wrapper around FileCommit(). */
476 : : bool Commit();
477 : :
478 : : /** Wrapper around TruncateFile(). */
479 : : bool Truncate(unsigned size);
480 : :
481 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
482 : : void write_buffer(std::span<std::byte> src);
483 : :
484 : : //
485 : : // Stream subset
486 : : //
487 : : void read(std::span<std::byte> dst);
488 : : void ignore(size_t nSize);
489 : : void write(std::span<const std::byte> src);
490 : :
491 : : template <typename T>
492 : 1379630 : AutoFile& operator<<(const T& obj)
493 : : {
494 [ + - + + : 1373852 : ::Serialize(*this, obj);
+ - + + -
- - - - -
+ + + - ]
[ + - # #
# # # # #
# # # # #
# # # # ]
[ + + + + ]
[ # # # #
# # ][ + +
+ - + - +
- + - + -
+ - ][ # #
# # # # #
# ][ - - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ]
495 : 316549 : return *this;
496 : : }
497 : :
498 : : template <typename T>
499 : 5267484 : AutoFile& operator>>(T&& obj)
500 : : {
501 [ + + + + : 5253725 : ::Unserialize(*this, obj);
+ + + + ]
[ # # # #
# # # # #
# # # # #
# # # # ]
[ + + + +
+ + + + +
+ + + + +
+ + + + ]
[ + - + -
+ - ][ + +
+ + + + +
+ + + ]
[ + + + + ]
[ - - + +
+ + + + +
- + + + +
+ - + - -
- + - - -
- - ]
502 : 2954310 : return *this;
503 : : }
504 : : };
505 : :
506 : : using DataBuffer = std::vector<std::byte>;
507 : :
508 : : /** Wrapper around an AutoFile& that implements a ring buffer to
509 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
510 : : *
511 : : * Will automatically close the file when it goes out of scope if not null.
512 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
513 : : */
514 : 830 : class BufferedFile
515 : : {
516 : : private:
517 : : AutoFile& m_src;
518 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
519 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
520 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
521 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
522 : : DataBuffer vchBuf;
523 : :
524 : : //! read data from the source to fill the buffer
525 : 282291 : bool Fill() {
526 [ - + ]: 282291 : unsigned int pos = nSrcPos % vchBuf.size();
527 : 282291 : unsigned int readNow = vchBuf.size() - pos;
528 : 282291 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
529 [ + + ]: 282291 : if (nAvail < readNow)
530 : 262956 : readNow = nAvail;
531 [ + - ]: 282291 : if (readNow == 0)
532 : : return false;
533 : 282291 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
534 [ + + ]: 282058 : if (nBytes == 0) {
535 [ + + + - ]: 6740 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
536 : : }
537 : 278688 : nSrcPos += nBytes;
538 : 278688 : return true;
539 : : }
540 : :
541 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
542 : : //! filling the buffer from the file so that at least one byte is available.
543 : : //! Return a pointer to the available buffer data and the number of bytes
544 : : //! (which may be less than the requested length) that may be accessed
545 : : //! beginning at that pointer.
546 : 5986124 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
547 : : {
548 [ - + ]: 5986124 : assert(m_read_pos <= nSrcPos);
549 [ + + ]: 5986124 : if (m_read_pos + length > nReadLimit) {
550 [ + - ]: 37438 : throw std::ios_base::failure("Attempt to position past buffer limit");
551 : : }
552 : : // If there are no bytes available, read from the file.
553 [ + + + - ]: 5967405 : if (m_read_pos == nSrcPos && length > 0) Fill();
554 : :
555 [ - + ]: 5964410 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
556 : 5964410 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
557 : 5964410 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
558 : 5964410 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
559 : 5964410 : m_read_pos += advance;
560 : 5964410 : return std::make_pair(&vchBuf[buffer_offset], advance);
561 : : }
562 : :
563 : : public:
564 : 843 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
565 : 843 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
566 : : {
567 [ + + ]: 843 : if (nRewindIn >= nBufSize)
568 [ + - ]: 26 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
569 : 843 : }
570 : :
571 : : //! check whether we're at the end of the source file
572 : 1958786 : bool eof() const {
573 [ + + + + ]: 1958786 : return m_read_pos == nSrcPos && m_src.feof();
574 : : }
575 : :
576 : : //! read a number of bytes
577 : 5497895 : void read(std::span<std::byte> dst)
578 : : {
579 [ + + ]: 11201700 : while (dst.size() > 0) {
580 : 5724464 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
581 : 5703805 : memcpy(dst.data(), buffer_pointer, length);
582 : 5703805 : dst = dst.subspan(length);
583 : : }
584 : 5477236 : }
585 : :
586 : : //! Move the read position ahead in the stream to the given position.
587 : : //! Use SetPos() to back up in the stream, not SkipTo().
588 : 264015 : void SkipTo(const uint64_t file_pos)
589 : : {
590 [ + - ]: 264015 : assert(file_pos >= m_read_pos);
591 [ + + ]: 524620 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
592 : 262960 : }
593 : :
594 : : //! return the current reading position
595 : 2285520 : uint64_t GetPos() const {
596 [ + + + + : 2285520 : return m_read_pos;
+ - ]
597 : : }
598 : :
599 : : //! rewind to a given reading position
600 : 2048588 : bool SetPos(uint64_t nPos) {
601 [ - + ]: 2048588 : size_t bufsize = vchBuf.size();
602 [ + + ]: 2048588 : if (nPos + bufsize < nSrcPos) {
603 : : // rewinding too far, rewind as far as possible
604 : 386 : m_read_pos = nSrcPos - bufsize;
605 : 386 : return false;
606 : : }
607 [ + + ]: 2048202 : if (nPos > nSrcPos) {
608 : : // can't go this far forward, go as far as possible
609 : 1122 : m_read_pos = nSrcPos;
610 : 1122 : return false;
611 : : }
612 : 2047080 : m_read_pos = nPos;
613 : 2047080 : return true;
614 : : }
615 : :
616 : : //! prevent reading beyond a certain position
617 : : //! no argument removes the limit
618 : 2223896 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
619 [ + + ]: 265338 : if (nPos < m_read_pos)
620 : : return false;
621 : 2223688 : nReadLimit = nPos;
622 [ + + ]: 2223688 : return true;
623 : : }
624 : :
625 : : template<typename T>
626 : 2642444 : BufferedFile& operator>>(T&& obj) {
627 [ + + + + : 2642444 : ::Unserialize(*this, obj);
+ + + + ]
[ + + + + ]
628 : 2602241 : return (*this);
629 : : }
630 : :
631 : : //! search for a given byte in the stream, and remain positioned on it
632 : 1959725 : void FindByte(std::byte byte)
633 : : {
634 : : // For best performance, avoid mod operation within the loop.
635 [ - + ]: 1959725 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
636 : 2003953 : while (true) {
637 [ + + ]: 2003953 : if (m_read_pos == nSrcPos) {
638 : : // No more bytes available; read from the file into the buffer,
639 : : // setting nSrcPos to one beyond the end of the new data.
640 : : // Throws exception if end-of-file reached.
641 : 46009 : Fill();
642 : : }
643 [ - + + + ]: 2003345 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
644 [ + + ]: 2003345 : const auto it_start{vchBuf.begin() + buf_offset};
645 : 2003345 : const auto it_find{std::find(it_start, it_start + len, byte)};
646 [ + + ]: 2003345 : const size_t inc{size_t(std::distance(it_start, it_find))};
647 : 2003345 : m_read_pos += inc;
648 [ + + ]: 2003345 : if (inc < len) break;
649 : 44228 : buf_offset += inc;
650 [ + + ]: 44228 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
651 : : }
652 : 1959117 : }
653 : : };
654 : :
655 : : /**
656 : : * Wrapper that buffers reads from an underlying stream.
657 : : * Requires underlying stream to support read() and detail_fread() calls
658 : : * to support fixed-size and variable-sized reads, respectively.
659 : : */
660 : : template <typename S>
661 : 0 : class BufferedReader
662 : : {
663 : : S& m_src;
664 : : DataBuffer m_buf;
665 : : size_t m_buf_pos;
666 : :
667 : : public:
668 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
669 : 0 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
670 : : requires std::is_rvalue_reference_v<S&&>
671 [ # # # # ]: 0 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
672 : :
673 : 0 : void read(std::span<std::byte> dst)
674 : : {
675 [ # # # # : 0 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
# # ]
676 : 0 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
677 : 0 : m_buf_pos += available;
678 : 0 : dst = dst.subspan(available);
679 : : }
680 [ # # ]: 0 : if (dst.size()) {
681 [ # # # # ]: 0 : assert(m_buf_pos == m_buf.size());
682 : 0 : m_src.read(dst);
683 : :
684 : 0 : m_buf_pos = 0;
685 [ # # ]: 0 : m_buf.resize(m_src.detail_fread(m_buf));
686 : : }
687 : 0 : }
688 : :
689 : : template <typename T>
690 : 0 : BufferedReader& operator>>(T&& obj)
691 : : {
692 [ # # ]: 0 : Unserialize(*this, obj);
693 : 0 : return *this;
694 : : }
695 : : };
696 : :
697 : : /**
698 : : * Wrapper that buffers writes to an underlying stream.
699 : : * Requires underlying stream to support write_buffer() method
700 : : * for efficient buffer flushing and obfuscation.
701 : : */
702 : : template <typename S>
703 : : class BufferedWriter
704 : : {
705 : : S& m_dst;
706 : : DataBuffer m_buf;
707 : : size_t m_buf_pos{0};
708 : :
709 : : public:
710 [ + - + - : 354183 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
711 : :
712 [ + - + - ]: 354183 : ~BufferedWriter() { flush(); }
713 : :
714 : 354183 : void flush()
715 : : {
716 [ + - - + ]: 354183 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
717 : 354183 : m_buf_pos = 0;
718 : 354183 : }
719 : :
720 : 6081451 : void write(std::span<const std::byte> src)
721 : : {
722 [ - + + - : 24325804 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
+ + ]
723 : 6081451 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
724 : 6081451 : m_buf_pos += available;
725 [ - + - + ]: 6081451 : if (m_buf_pos == m_buf.size()) flush();
726 : 6081451 : src = src.subspan(available);
727 : : }
728 : 6081451 : }
729 : :
730 : : template <typename T>
731 : 1408415 : BufferedWriter& operator<<(const T& obj)
732 : : {
733 [ - - + - : 1054232 : Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- ]
734 : 709142 : return *this;
735 : : }
736 : : };
737 : :
738 : : #endif // BITCOIN_STREAMS_H
|