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 : 1244 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn) : vchData{vchDataIn}, nPos{nPosIn}
43 : : {
44 [ - + + + ]: 1244 : if(nPos > vchData.size())
45 : 1 : vchData.resize(nPos);
46 : 1244 : }
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 [ + - + - : 46 : VectorWriter(std::vector<unsigned char>& vchDataIn, size_t nPosIn, Args&&... args) : VectorWriter{vchDataIn, nPosIn}
+ - - - -
- - - - -
- - - - -
- - - - -
+ - - - -
- - - - -
- - - - -
- + - + -
- - ][ + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
53 : : {
54 [ + - + - : 46 : ::SerializeMany(*this, std::forward<Args>(args)...);
+ - - - -
- - - - -
- - - - -
- - - - -
+ - - - -
- - - - -
- - - - -
- + - + -
- - ][ + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
55 : 32 : }
56 : 208930 : void write(std::span<const std::byte> src)
57 : : {
58 [ - + - + ]: 208930 : assert(nPos <= vchData.size());
59 [ + + ]: 208930 : size_t nOverwrite = std::min(src.size(), vchData.size() - nPos);
60 [ + + ]: 208930 : if (nOverwrite) {
61 : 19 : memcpy(vchData.data() + nPos, src.data(), nOverwrite);
62 : : }
63 [ + + ]: 208930 : if (nOverwrite < src.size()) {
64 : 208912 : vchData.insert(vchData.end(), UCharCast(src.data()) + nOverwrite, UCharCast(src.data() + src.size()));
65 : : }
66 : 208930 : nPos += src.size();
67 : 208930 : }
68 : : template <typename T>
69 : 152915 : VectorWriter& operator<<(const T& obj)
70 : : {
71 [ - - - - : 152915 : ::Serialize(*this, obj);
- - - - -
- - - -
- ][ + - +
- + - + -
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
+ - + - +
- ]
72 : 151960 : 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 : 3898 : explicit SpanReader(std::span<const unsigned char> data) : m_data{std::as_bytes(data)} {}
92 [ + + + - ]: 17600 : explicit SpanReader(std::span<const std::byte> data) : m_data{data} {}
[ + - # # ]
[ + + + +
+ + ]
93 : :
94 : : template<typename T>
95 : 829835 : SpanReader& operator>>(T&& obj)
96 : : {
97 [ + + + - : 829830 : ::Unserialize(*this, obj);
+ - + - +
- ][ + + #
# # # # #
# # ][ + -
+ - + + +
+ ][ + + +
+ # # #
# ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + + +
- + - + -
+ + + - +
- + - + +
+ - + - +
- + + + -
+ - + - +
+ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
[ # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
- + + - -
+ # # ][ +
- + - + -
+ - - + -
+ ][ + - +
- - + + -
+ - + - +
- + - ]
98 : 636420 : return (*this);
99 : : }
100 : :
101 [ # # # # : 5 : size_t size() const { return m_data.size(); }
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ # # ]
[ + - + -
+ - + - +
- ]
102 [ + + ]: 17389 : bool empty() const { return m_data.empty(); }
[ + - + - ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ ][ # # #
# # # #
# ][ + - +
- + - + -
+ - + - ]
103 : :
104 : 1745534 : void read(std::span<std::byte> dst)
105 : : {
106 [ + + ]: 1745534 : if (dst.size() == 0) {
107 : : return;
108 : : }
109 : :
110 : : // Read from the beginning of the buffer
111 [ + + ]: 1744280 : if (dst.size() > m_data.size()) {
112 [ + - ]: 1930 : throw std::ios_base::failure("SpanReader::read(): end of data");
113 : : }
114 : 1743315 : memcpy(dst.data(), m_data.data(), dst.size());
115 : 1743315 : m_data = m_data.subspan(dst.size());
116 : : }
117 : :
118 : 1 : void ignore(size_t n)
119 : : {
120 [ + - ]: 1 : if (n > m_data.size()) {
121 [ + - ]: 2 : throw std::ios_base::failure("SpanReader::ignore(): end of data");
122 : : }
123 : 0 : m_data = m_data.subspan(n);
124 : 0 : }
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 : 14 : explicit SpanWriter(std::span<std::byte> dest) : m_dest{dest} {}
136 : : template <typename... Args>
137 : 2 : SpanWriter(std::span<std::byte> dest, Args&&... args) : SpanWriter{dest}
138 : : {
139 [ - + ]: 2 : ::SerializeMany(*this, std::forward<Args>(args)...);
140 : 0 : }
141 : :
142 : 87 : void write(std::span<const std::byte> src)
143 : : {
144 [ + + ]: 87 : if (src.size() > m_dest.size()) {
145 [ + - ]: 4 : throw std::ios_base::failure("SpanWriter::write(): exceeded buffer size");
146 : : }
147 : 85 : memcpy(m_dest.data(), src.data(), src.size());
148 : 85 : m_dest = m_dest.subspan(src.size());
149 : 85 : }
150 : :
151 : : template<typename T>
152 : 43 : SpanWriter& operator<<(const T& obj)
153 : : {
154 [ + - ]: 41 : ::Serialize(*this, obj);
[ + - - + ]
155 : 13 : 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 [ + + + - ]: 3946289 : 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 : 214 : explicit DataStream(std::span<const uint8_t> sp) : DataStream{std::as_bytes(sp)} {}
184 : 11692 : explicit DataStream(std::span<const value_type> sp) : vch(sp.data(), sp.data() + sp.size()) {}
185 : :
186 : 19 : std::string str() const
187 : : {
188 : 57 : 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 : 229 : iterator begin() { return vch.begin() + m_read_pos; }
197 : : const_iterator end() const { return vch.end(); }
198 [ + - ]: 187 : iterator end() { return vch.end(); }
[ + - + - ]
[ + - + -
+ - + - ]
199 [ - + + - ]: 12744444 : size_type size() const { return vch.size() - m_read_pos; }
[ - - - +
- + - + -
+ + - - +
+ - - + -
+ - + - +
+ - - + +
- - + + -
# # # # #
# # # # #
# # # # #
# # # ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ - + +
- - + + +
+ + + + +
- - + +
- ][ - + +
- - + - +
+ - - + ]
[ - + + -
- + + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
+ - + - +
- + + - ]
[ - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - ]
[ - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - -
- ][ - + -
+ - + - +
- + - + +
- - + - +
- + + - -
+ - + - +
+ - - + +
- - + + -
- + + - -
+ + - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ - + -
- - - - +
- + + - -
+ - + - +
- + - - -
+ + - - +
+ - - + +
- - + + -
- - - - ]
[ - + - +
+ + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # ][ -
+ - + - +
+ - - + -
+ + - - +
+ - - + -
+ + - - +
+ - ][ - -
- - - - -
- - - - -
- + - - -
- - + + -
- + - - -
- - + +
- ][ - + -
+ + - - -
- + - + +
- # # # #
# # # # #
# # # #
# ][ - + #
# # # # #
# # # # #
# ][ - + +
+ + + + +
- + ]
200 [ - + + + : 265 : bool empty() const { return vch.size() == m_read_pos; }
- + + + -
+ + + - +
+ + ][ - +
+ - - + +
- - + + -
- + + - -
+ + + # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # ][ - +
- + - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - - + +
- - + + -
- + + - -
+ + - - +
+ - ][ - +
+ - - - -
- ]
201 : 315 : void resize(size_type n, value_type c = value_type{}) { vch.resize(n + m_read_pos, c); }
202 [ + - + - : 3792331 : 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 [ + + ]: 8488193 : reference operator[](size_type pos) { return vch[pos + m_read_pos]; }
205 [ - + + - : 209162 : void clear() { vch.clear(); m_read_pos = 0; }
+ + + - +
+ + - + +
+ - + + +
- + + ][ +
- + - + -
+ - + - +
- + - - -
# # # # #
# ][ + + +
+ # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- ][ + - +
- - - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ - + +
- - + + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ -
+ - + -
+ ]
206 [ - + + + : 3974066 : value_type* data() { return vch.data() + m_read_pos; }
- + - + -
+ - + - +
- + - + -
+ - + - +
# # ][ # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + ][ -
+ - - - +
- + - + -
+ - + - +
- - - + -
+ - + - +
- - ][ - +
- + # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ - + -
+ - + - +
- + - + -
+ - + - +
# # ][ - -
- - - - -
- - + - -
- + - + -
- - + ][ -
+ - + - +
+ + - + ]
[ + + # #
# # # # #
# ][ # # #
# # # # #
# # # # #
# # # ][ -
+ - + - +
# # # # #
# # # #
# ]
207 [ - + ]: 318 : const value_type* data() const { return vch.data() + m_read_pos; }
208 : :
209 : : //
210 : : // Stream subset
211 : : //
212 [ # # # # ]: 0 : int in_avail() const { return size(); }
213 : :
214 : 460349 : void read(std::span<value_type> dst)
215 : : {
216 [ + + ]: 460349 : if (dst.size() == 0) return;
217 : :
218 : : // Read from the beginning of the buffer
219 [ + - ]: 460341 : auto next_read_pos{CheckedAdd(m_read_pos, dst.size())};
220 [ + - - + : 460341 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
+ + ]
221 [ + - ]: 42 : throw std::ios_base::failure("DataStream::read(): end of data");
222 : : }
223 [ - + ]: 460320 : memcpy(dst.data(), &vch[m_read_pos], dst.size());
224 [ - + + + ]: 460320 : if (next_read_pos.value() == vch.size()) {
225 : : // If fully consumed, reset to empty state.
226 [ + - ]: 12485 : clear();
227 : 12485 : return;
228 : : }
229 : 447835 : m_read_pos = next_read_pos.value();
230 : : }
231 : :
232 : 7 : void ignore(size_t num_ignore)
233 : : {
234 : : // Ignore from the beginning of the buffer
235 : 7 : auto next_read_pos{CheckedAdd(m_read_pos, num_ignore)};
236 [ + - - + : 7 : if (!next_read_pos.has_value() || next_read_pos.value() > vch.size()) {
- + ]
237 [ # # ]: 0 : throw std::ios_base::failure("DataStream::ignore(): end of data");
238 : : }
239 [ + + ]: 7 : if (next_read_pos.value() == vch.size()) {
240 : : // If all bytes are ignored, reset to empty state.
241 [ + + ]: 3 : clear();
242 : 3 : return;
243 : : }
244 : 4 : m_read_pos = next_read_pos.value();
245 : : }
246 : :
247 : 23538959 : void write(std::span<const value_type> src)
248 : : {
249 : : // Write to the end of the buffer
250 : 23538959 : vch.insert(vch.end(), src.begin(), src.end());
251 : 23538959 : }
252 : :
253 : : template<typename T>
254 : 8560510 : DataStream& operator<<(const T& obj)
255 : : {
256 [ + - ][ + - : 8470908 : ::Serialize(*this, obj);
+ - + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
+ - + - +
- + - +
- ][ + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - - - -
- + - + -
+ - + - +
- + - - -
- - - - +
- + - - -
+ - + - +
- + - + -
+ - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - + - +
- + - - -
- - - - +
- + - + -
- - - - -
- - - + -
+ - + - +
- - - ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ][ + - +
- + - - -
+ - + - +
- + - + -
+ - - - ]
[ + - + -
# # # # #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- ][ # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ][ + - +
- + - + -
+ - + - +
- + - +
- ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
257 : 4487854 : return (*this);
258 : : }
259 : :
260 : : template <typename T>
261 : 147568 : DataStream& operator>>(T&& obj)
262 : : {
263 [ + + ]: 147337 : ::Unserialize(*this, obj);
[ + - + - ]
[ - - - -
- - - - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - +
- + - + -
+ - + - +
- + - + -
+ + - - +
- + - + -
- + + - -
- - - - -
- - - - -
- - - + -
- - - - -
- - - - -
- - - - -
- - - ][ +
- + - + -
+ - + - +
- + - + -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - ]
[ - - + -
- - - - -
- - - - -
- - + - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
- - - + -
- - - - +
- + - + -
+ - + - ]
[ + - + -
+ - + - #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
- + - ][ +
+ + + + -
+ - + - +
- + - + -
+ - ][ + -
- + - + -
+ + - + -
- + + - +
- + - + -
- + + - -
+ + - + -
- + - + +
- + - ][ +
- + - + -
+ - + - #
# # # # #
# # # # #
# # # ][ +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
264 : 123030 : return (*this);
265 : : }
266 : :
267 : : /** Compute total memory usage of this object (own memory + any dynamic memory). */
268 : : size_t GetMemoryUsage() const noexcept;
269 : : };
270 : :
271 : : template <typename IStream>
272 : : class BitStreamReader
273 : : {
274 : : private:
275 : : IStream& m_istream;
276 : :
277 : : /// Buffered byte read in from the input stream. A new byte is read into the
278 : : /// buffer when m_offset reaches 8.
279 : : uint8_t m_buffer{0};
280 : :
281 : : /// Number of high order bits in m_buffer already returned by previous
282 : : /// Read() calls. The next bit to be returned is at this offset from the
283 : : /// most significant bit position.
284 : : int m_offset{8};
285 : :
286 : : public:
287 [ + - ]: 211 : explicit BitStreamReader(IStream& istream) : m_istream(istream) {}
288 : :
289 : : /** Read the specified number of bits from the stream. The data is returned
290 : : * in the nbits least significant bits of a 64-bit uint.
291 : : */
292 : 24252 : uint64_t Read(int nbits) {
293 [ + - ]: 24252 : if (nbits < 0 || nbits > 64) {
294 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
295 : : }
296 : :
297 : : uint64_t data = 0;
298 [ + + ]: 59825 : while (nbits > 0) {
299 [ + + ]: 35574 : if (m_offset == 8) {
300 : 14038 : m_istream >> m_buffer;
301 : 14037 : m_offset = 0;
302 : : }
303 : :
304 [ + + ]: 35573 : int bits = std::min(8 - m_offset, nbits);
305 : 35573 : data <<= bits;
306 : 35573 : data |= static_cast<uint8_t>(m_buffer << m_offset) >> (8 - bits);
307 : 35573 : m_offset += bits;
308 : 35573 : nbits -= bits;
309 : : }
310 : 24251 : return data;
311 : : }
312 : : };
313 : :
314 : : template <typename OStream>
315 : : class BitStreamWriter
316 : : {
317 : : private:
318 : : OStream& m_ostream;
319 : :
320 : : /// Buffered byte waiting to be written to the output stream. The byte is
321 : : /// written buffer when m_offset reaches 8 or Flush() is called.
322 : : uint8_t m_buffer{0};
323 : :
324 : : /// Number of high order bits in m_buffer already written by previous
325 : : /// Write() calls and not yet flushed to the stream. The next bit to be
326 : : /// written to is at this offset from the most significant bit position.
327 : : int m_offset{0};
328 : :
329 : : public:
330 [ + - ]: 236 : explicit BitStreamWriter(OStream& ostream) : m_ostream(ostream) {}
331 : :
332 : 236 : ~BitStreamWriter()
333 : : {
334 : 236 : Flush();
335 : 236 : }
336 : :
337 : : /** Write the nbits least significant bits of a 64-bit int to the output
338 : : * stream. Data is buffered until it completes an octet.
339 : : */
340 : 871 : void Write(uint64_t data, int nbits) {
341 [ + - ]: 871 : if (nbits < 0 || nbits > 64) {
342 [ # # ]: 0 : throw std::out_of_range("nbits must be between 0 and 64");
343 : : }
344 : :
345 [ + + ]: 2413 : while (nbits > 0) {
346 [ + + ]: 1542 : int bits = std::min(8 - m_offset, nbits);
347 : 1542 : m_buffer |= (data << (64 - nbits)) >> (64 - 8 + m_offset);
348 : 1542 : m_offset += bits;
349 : 1542 : nbits -= bits;
350 : :
351 [ + + ]: 1542 : if (m_offset == 8) {
352 : 709 : Flush();
353 : : }
354 : : }
355 : 871 : }
356 : :
357 : : /** Flush any unwritten bits to the output stream, padding with 0's to the
358 : : * next byte boundary.
359 : : */
360 : 1181 : void Flush() {
361 [ + + ]: 1181 : if (m_offset == 0) {
362 : : return;
363 : : }
364 : :
365 : 944 : m_ostream << m_buffer;
366 : 944 : m_buffer = 0;
367 : 944 : m_offset = 0;
368 : : }
369 : : };
370 : :
371 : : /** Non-refcounted RAII wrapper for FILE*
372 : : *
373 : : * Will automatically close the file when it goes out of scope if not null.
374 : : * If you're returning the file pointer, return file.release().
375 : : * If you need to close the file early, use autofile.fclose() instead of fclose(underlying_FILE).
376 : : *
377 : : * @note If the file has been written to, then the caller must close it
378 : : * explicitly with the `fclose()` method, check if it returns an error and treat
379 : : * such an error as if the `write()` method failed. The OS's `fclose(3)` may
380 : : * fail to flush to disk data that has been previously written, rendering the
381 : : * file corrupt.
382 : : */
383 : : class AutoFile
384 : : {
385 : : protected:
386 : : std::FILE* m_file;
387 : : Obfuscation m_obfuscation;
388 : : std::optional<int64_t> m_position;
389 : : bool m_was_written{false};
390 : :
391 : : public:
392 : : explicit AutoFile(std::FILE* file, const Obfuscation& obfuscation = {});
393 : :
394 : 23880 : ~AutoFile()
395 : : {
396 [ + + ]: 23880 : if (m_was_written) {
397 : : // Callers that wrote to the file must have closed it explicitly
398 : : // with the fclose() method and checked that the close succeeded.
399 : : // This is because here in the destructor we have no way to signal
400 : : // errors from fclose() which, after write, could mean the file is
401 : : // corrupted and must be handled properly at the call site.
402 : : // Destructors in C++ cannot signal an error to the callers because
403 : : // they do not return a value and are not allowed to throw exceptions.
404 : 17297 : Assume(IsNull());
405 : : }
406 : :
407 [ - + ]: 6571 : if (fclose() != 0) {
408 : 0 : LogError("Failed to close file: %s", SysErrorString(errno));
409 : : }
410 : 23880 : }
411 : :
412 : : // Disallow copies
413 : : AutoFile(const AutoFile&) = delete;
414 : : AutoFile& operator=(const AutoFile&) = delete;
415 : :
416 : 197 : bool feof() const { return std::feof(m_file); }
417 : :
418 : 41180 : [[nodiscard]] int fclose()
419 : : {
420 [ + - ][ + - : 23871 : if (auto rel{release()}) return std::fclose(rel);
+ - + - ]
[ + - + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - ]
[ + - + -
+ - + - #
# # # # #
# # # # ]
421 : : return 0;
422 : : }
423 : :
424 : : /** Get wrapped FILE* with transfer of ownership.
425 : : * @note This will invalidate the AutoFile object, and makes it the responsibility of the caller
426 : : * of this function to clean up the returned FILE*.
427 : : */
428 : 41180 : std::FILE* release()
429 : : {
430 : 41180 : std::FILE* ret{m_file};
431 : 41180 : m_file = nullptr;
432 [ + + ][ + - : 41180 : return ret;
- - - - ]
[ + - - -
# # ][ + -
+ - + - +
+ ][ + - +
- + - + -
- - ][ + -
+ - + - +
- + - + -
+ - + - +
- - - ]
433 : : }
434 : :
435 : : /** Return true if the wrapped FILE* is nullptr, false otherwise.
436 : : */
437 [ + + + + : 64948 : bool IsNull() const { return m_file == nullptr; }
+ + ][ - + ]
[ + + + + ]
[ + - + -
- + + + -
+ + + ][ +
- - + + -
- + ]
438 : :
439 : : /** Continue with a different XOR key */
440 : 1 : void SetObfuscation(const Obfuscation& obfuscation) { m_obfuscation = obfuscation; }
441 : :
442 : : /** Implementation detail, only used internally. */
443 : : std::size_t detail_fread(std::span<std::byte> dst);
444 : :
445 : : /** Wrapper around fseek(). Will throw if seeking is not possible. */
446 : : void seek(int64_t offset, int origin);
447 : :
448 : : /** Find position within the file. Will throw if unknown. */
449 : : int64_t tell();
450 : :
451 : : /** Return the size of the file. Will throw if unknown. */
452 : : int64_t size();
453 : :
454 : : /** Wrapper around FileCommit(). */
455 : : bool Commit();
456 : :
457 : : /** Wrapper around TruncateFile(). */
458 : : bool Truncate(unsigned size);
459 : :
460 : : //! Write a mutable buffer more efficiently than write(), obfuscating the buffer in-place.
461 : : void write_buffer(std::span<std::byte> src);
462 : :
463 : : //
464 : : // Stream subset
465 : : //
466 : : void read(std::span<std::byte> dst);
467 : : void ignore(size_t nSize);
468 : : void write(std::span<const std::byte> src);
469 : :
470 : : template <typename T>
471 : 65802 : AutoFile& operator<<(const T& obj)
472 : : {
473 [ + - + - : 65543 : ::Serialize(*this, obj);
+ - + - -
- - - - -
+ - + - ]
[ + - # #
# # # # #
# # # # #
# # # # ]
[ + - + - ]
[ + - + +
+ - ][ + -
+ - + - +
- + + + -
+ - ][ + -
- - - - +
- ]
474 : 10757 : return *this;
475 : : }
476 : :
477 : : template <typename T>
478 : 20736 : AutoFile& operator>>(T&& obj)
479 : : {
480 [ + - + + : 15241 : ::Unserialize(*this, obj);
+ - + + ]
[ + - # #
# # # # #
# # # # #
# # # # ]
[ # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - ][ # #
# # # # #
# # # ]
[ + - + - ]
[ + - + -
+ - + - +
- + - + -
+ - ][ + -
+ - - + -
+ + - + -
+ - - + +
- - + ][ #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
481 : 11355 : return *this;
482 : : }
483 : : };
484 : :
485 : : using DataBuffer = std::vector<std::byte>;
486 : :
487 : : /** Wrapper around an AutoFile& that implements a ring buffer to
488 : : * deserialize from. It guarantees the ability to rewind a given number of bytes.
489 : : *
490 : : * Will automatically close the file when it goes out of scope if not null.
491 : : * If you need to close the file early, use file.fclose() instead of fclose(file).
492 : : */
493 : 54 : class BufferedFile
494 : : {
495 : : private:
496 : : AutoFile& m_src;
497 : : uint64_t nSrcPos{0}; //!< how many bytes have been read from source
498 : : uint64_t m_read_pos{0}; //!< how many bytes have been read from this
499 : : uint64_t nReadLimit; //!< up to which position we're allowed to read
500 : : uint64_t nRewind; //!< how many bytes we guarantee to rewind
501 : : DataBuffer vchBuf;
502 : :
503 : : //! read data from the source to fill the buffer
504 : 300 : bool Fill() {
505 [ - + ]: 300 : unsigned int pos = nSrcPos % vchBuf.size();
506 : 300 : unsigned int readNow = vchBuf.size() - pos;
507 : 300 : unsigned int nAvail = vchBuf.size() - (nSrcPos - m_read_pos) - nRewind;
508 [ + + ]: 300 : if (nAvail < readNow)
509 : 259 : readNow = nAvail;
510 [ + - ]: 300 : if (readNow == 0)
511 : : return false;
512 : 300 : size_t nBytes{m_src.detail_fread(std::span{vchBuf}.subspan(pos, readNow))};
513 [ + + ]: 300 : if (nBytes == 0) {
514 [ - + + - ]: 6 : throw std::ios_base::failure{m_src.feof() ? "BufferedFile::Fill: end of file" : "BufferedFile::Fill: fread failed"};
515 : : }
516 : 297 : nSrcPos += nBytes;
517 : 297 : return true;
518 : : }
519 : :
520 : : //! Advance the stream's read pointer (m_read_pos) by up to 'length' bytes,
521 : : //! filling the buffer from the file so that at least one byte is available.
522 : : //! Return a pointer to the available buffer data and the number of bytes
523 : : //! (which may be less than the requested length) that may be accessed
524 : : //! beginning at that pointer.
525 : 3268 : std::pair<std::byte*, size_t> AdvanceStream(size_t length)
526 : : {
527 [ - + ]: 3268 : assert(m_read_pos <= nSrcPos);
528 [ + + ]: 3268 : if (m_read_pos + length > nReadLimit) {
529 [ + - ]: 4 : throw std::ios_base::failure("Attempt to position past buffer limit");
530 : : }
531 : : // If there are no bytes available, read from the file.
532 [ + + + - ]: 3266 : if (m_read_pos == nSrcPos && length > 0) Fill();
533 : :
534 [ - + ]: 3265 : size_t buffer_offset{static_cast<size_t>(m_read_pos % vchBuf.size())};
535 : 3265 : size_t buffer_available{static_cast<size_t>(vchBuf.size() - buffer_offset)};
536 : 3265 : size_t bytes_until_source_pos{static_cast<size_t>(nSrcPos - m_read_pos)};
537 : 3265 : size_t advance{std::min({length, buffer_available, bytes_until_source_pos})};
538 : 3265 : m_read_pos += advance;
539 : 3265 : return std::make_pair(&vchBuf[buffer_offset], advance);
540 : : }
541 : :
542 : : public:
543 : 55 : BufferedFile(AutoFile& file LIFETIMEBOUND, uint64_t nBufSize, uint64_t nRewindIn)
544 : 55 : : m_src{file}, nReadLimit{std::numeric_limits<uint64_t>::max()}, nRewind{nRewindIn}, vchBuf(nBufSize, std::byte{0})
545 : : {
546 [ + + ]: 55 : if (nRewindIn >= nBufSize)
547 [ + - ]: 2 : throw std::ios_base::failure("Rewind limit must be less than buffer size");
548 : 55 : }
549 : :
550 : : //! check whether we're at the end of the source file
551 : 3888 : bool eof() const {
552 [ + + + + ]: 3888 : return m_read_pos == nSrcPos && m_src.feof();
553 : : }
554 : :
555 : : //! read a number of bytes
556 : 2654 : void read(std::span<std::byte> dst)
557 : : {
558 [ + + ]: 5405 : while (dst.size() > 0) {
559 : 2753 : auto [buffer_pointer, length]{AdvanceStream(dst.size())};
560 : 2751 : memcpy(dst.data(), buffer_pointer, length);
561 : 2751 : dst = dst.subspan(length);
562 : : }
563 : 2652 : }
564 : :
565 : : //! Move the read position ahead in the stream to the given position.
566 : : //! Use SetPos() to back up in the stream, not SkipTo().
567 : 622 : void SkipTo(const uint64_t file_pos)
568 : : {
569 [ + - ]: 622 : assert(file_pos >= m_read_pos);
570 [ + + ]: 1136 : while (m_read_pos < file_pos) AdvanceStream(file_pos - m_read_pos);
571 : 621 : }
572 : :
573 : : //! return the current reading position
574 : 5211 : uint64_t GetPos() const {
575 [ + - + - : 5211 : return m_read_pos;
+ - ][ + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
576 : : }
577 : :
578 : : //! rewind to a given reading position
579 : 676 : bool SetPos(uint64_t nPos) {
580 [ - + ][ - + : 676 : size_t bufsize = vchBuf.size();
- + - + -
+ - + - +
- + - + -
+ - + ]
581 [ - + ][ + + : 676 : if (nPos + bufsize < nSrcPos) {
- + - + -
+ - + - +
- + - + -
+ + - ]
582 : : // rewinding too far, rewind as far as possible
583 : 67 : m_read_pos = nSrcPos - bufsize;
584 : 67 : return false;
585 : : }
586 [ - + ][ + + : 606 : if (nPos > nSrcPos) {
- + - + -
+ - + -
+ ]
587 : : // can't go this far forward, go as far as possible
588 : 17 : m_read_pos = nSrcPos;
589 : 17 : return false;
590 : : }
591 : 592 : m_read_pos = nPos;
592 : 592 : return true;
593 : : }
594 : :
595 : : //! prevent reading beyond a certain position
596 : : //! no argument removes the limit
597 : 3203 : bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
598 [ + - ][ + - : 3196 : if (nPos < m_read_pos)
+ - + - +
- + - + -
+ - ]
599 : : return false;
600 : 3203 : nReadLimit = nPos;
601 [ + + ]: 3203 : return true;
602 : : }
603 : :
604 : : template<typename T>
605 : 2608 : BufferedFile& operator>>(T&& obj) {
606 [ + - + - : 2608 : ::Unserialize(*this, obj);
+ - + - ]
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- + + - +
- + - + -
+ - - + +
- ]
607 : 2606 : return (*this);
608 : : }
609 : :
610 : : //! search for a given byte in the stream, and remain positioned on it
611 : 656 : void FindByte(std::byte byte)
612 : : {
613 : : // For best performance, avoid mod operation within the loop.
614 [ - + ]: 656 : size_t buf_offset{size_t(m_read_pos % uint64_t(vchBuf.size()))};
615 : 738 : while (true) {
616 [ + + ]: 738 : if (m_read_pos == nSrcPos) {
617 : : // No more bytes available; read from the file into the buffer,
618 : : // setting nSrcPos to one beyond the end of the new data.
619 : : // Throws exception if end-of-file reached.
620 : 97 : Fill();
621 : : }
622 [ - + + + ]: 736 : const size_t len{std::min<size_t>(vchBuf.size() - buf_offset, nSrcPos - m_read_pos)};
623 [ + + ]: 736 : const auto it_start{vchBuf.begin() + buf_offset};
624 : 736 : const auto it_find{std::find(it_start, it_start + len, byte)};
625 [ + + ]: 736 : const size_t inc{size_t(std::distance(it_start, it_find))};
626 : 736 : m_read_pos += inc;
627 [ + + ]: 736 : if (inc < len) break;
628 : 82 : buf_offset += inc;
629 [ + + ]: 82 : if (buf_offset >= vchBuf.size()) buf_offset = 0;
630 : : }
631 : 654 : }
632 : : };
633 : :
634 : : /**
635 : : * Wrapper that buffers reads from an underlying stream.
636 : : * Requires underlying stream to support read() and detail_fread() calls
637 : : * to support fixed-size and variable-sized reads, respectively.
638 : : */
639 : : template <typename S>
640 : 914 : class BufferedReader
641 : : {
642 : : S& m_src;
643 : : DataBuffer m_buf;
644 : : size_t m_buf_pos;
645 : :
646 : : public:
647 : : //! Requires stream ownership to prevent leaving the stream at an unexpected position after buffered reads.
648 : 914 : explicit BufferedReader(S&& stream LIFETIMEBOUND, size_t size = 1 << 16)
649 : : requires std::is_rvalue_reference_v<S&&>
650 [ + - + - ]: 914 : : m_src{stream}, m_buf(size), m_buf_pos{size} {}
[ + - + -
+ - ]
651 : :
652 : 1881 : void read(std::span<std::byte> dst)
653 : : {
654 [ - + + + : 2846 : if (const auto available{std::min(dst.size(), m_buf.size() - m_buf_pos)}) {
+ + ]
655 : 965 : std::copy_n(m_buf.begin() + m_buf_pos, available, dst.begin());
656 : 965 : m_buf_pos += available;
657 : 965 : dst = dst.subspan(available);
658 : : }
659 [ + + ]: 1881 : if (dst.size()) {
660 [ - + - + ]: 916 : assert(m_buf_pos == m_buf.size());
661 : 916 : m_src.read(dst);
662 : :
663 : 914 : m_buf_pos = 0;
664 [ - + ]: 914 : m_buf.resize(m_src.detail_fread(m_buf));
665 : : }
666 : 1879 : }
667 : :
668 : : template <typename T>
669 : 914 : BufferedReader& operator>>(T&& obj)
670 : : {
671 [ + - ]: 913 : Unserialize(*this, obj);
[ + - + - ]
672 : 913 : return *this;
673 : : }
674 : : };
675 : :
676 : : /**
677 : : * Wrapper that buffers writes to an underlying stream.
678 : : * Requires underlying stream to support write_buffer() method
679 : : * for efficient buffer flushing and obfuscation.
680 : : */
681 : : template <typename S>
682 : : class BufferedWriter
683 : : {
684 : : S& m_dst;
685 : : DataBuffer m_buf;
686 : : size_t m_buf_pos{0};
687 : :
688 : : public:
689 [ + - + - : 16915 : explicit BufferedWriter(S& stream LIFETIMEBOUND, size_t size = 1 << 16) : m_dst{stream}, m_buf(size) {}
+ - + - ]
[ + - + -
+ - ]
690 : :
691 [ + - + - ]: 16915 : ~BufferedWriter() { flush(); }
692 : :
693 : 16917 : void flush()
694 : : {
695 [ + + - + ]: 16917 : if (m_buf_pos) m_dst.write_buffer(std::span{m_buf}.first(m_buf_pos));
696 : 16917 : m_buf_pos = 0;
697 : 16917 : }
698 : :
699 : 283662 : void write(std::span<const std::byte> src)
700 : : {
701 [ - + + + : 1134649 : while (const auto available{std::min(src.size(), m_buf.size() - m_buf_pos)}) {
+ + ]
702 : 283663 : std::copy_n(src.begin(), available, m_buf.begin() + m_buf_pos);
703 : 283663 : m_buf_pos += available;
704 [ - + + + ]: 283663 : if (m_buf_pos == m_buf.size()) flush();
705 : 283663 : src = src.subspan(available);
706 : : }
707 : 283662 : }
708 : :
709 : : template <typename T>
710 : 67653 : BufferedWriter& operator<<(const T& obj)
711 : : {
712 [ + - + - : 50739 : Serialize(*this, obj);
+ - + - +
- + - + -
+ - + - +
- ]
[ + - + - ]
713 : 33951 : return *this;
714 : : }
715 : : };
716 : :
717 : : #endif // BITCOIN_STREAMS_H
|