LCOV - code coverage report
Current view: top level - src - serialize.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 396 399 99.2 %
Date: 2024-05-24 08:22:33 Functions: 2022 2667 75.8 %
Branches: 362 694 52.2 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :            : // Copyright (c) 2009-2022 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_SERIALIZE_H
       7                 :            : #define BITCOIN_SERIALIZE_H
       8                 :            : 
       9                 :            : #include <attributes.h>
      10                 :            : #include <compat/assumptions.h> // IWYU pragma: keep
      11                 :            : #include <compat/endian.h>
      12                 :            : #include <prevector.h>
      13                 :            : #include <span.h>
      14                 :            : 
      15                 :            : #include <algorithm>
      16                 :            : #include <concepts>
      17                 :            : #include <cstdint>
      18                 :            : #include <cstring>
      19                 :            : #include <ios>
      20                 :            : #include <limits>
      21                 :            : #include <map>
      22                 :            : #include <memory>
      23                 :            : #include <set>
      24                 :            : #include <string>
      25                 :            : #include <utility>
      26                 :            : #include <vector>
      27                 :            : 
      28                 :            : /**
      29                 :            :  * The maximum size of a serialized object in bytes or number of elements
      30                 :            :  * (for eg vectors) when the size is encoded as CompactSize.
      31                 :            :  */
      32                 :            : static constexpr uint64_t MAX_SIZE = 0x02000000;
      33                 :            : 
      34                 :            : /** Maximum amount of memory (in bytes) to allocate at once when deserializing vectors. */
      35                 :            : static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
      36                 :            : 
      37                 :            : /**
      38                 :            :  * Dummy data type to identify deserializing constructors.
      39                 :            :  *
      40                 :            :  * By convention, a constructor of a type T with signature
      41                 :            :  *
      42                 :            :  *   template <typename Stream> T::T(deserialize_type, Stream& s)
      43                 :            :  *
      44                 :            :  * is a deserializing constructor, which builds the type by
      45                 :            :  * deserializing it from s. If T contains const fields, this
      46                 :            :  * is likely the only way to do so.
      47                 :            :  */
      48                 :            : struct deserialize_type {};
      49                 :            : constexpr deserialize_type deserialize {};
      50                 :            : 
      51                 :            : /*
      52                 :            :  * Lowest-level serialization and conversion.
      53                 :            :  */
      54                 :  642897755 : template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
      55                 :            : {
      56                 :  642897755 :     s.write(AsBytes(Span{&obj, 1}));
      57                 :  642897755 : }
      58                 :     326491 : template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
      59                 :            : {
      60                 :     326491 :     obj = htole16_internal(obj);
      61                 :     326491 :     s.write(AsBytes(Span{&obj, 1}));
      62                 :     326491 : }
      63                 :        199 : template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
      64                 :            : {
      65                 :        199 :     obj = htobe16_internal(obj);
      66                 :        199 :     s.write(AsBytes(Span{&obj, 1}));
      67                 :        199 : }
      68                 :  318167495 : template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
      69                 :            : {
      70                 :  318167495 :     obj = htole32_internal(obj);
      71                 :  318167495 :     s.write(AsBytes(Span{&obj, 1}));
      72                 :  318167495 : }
      73                 :        199 : template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
      74                 :            : {
      75                 :        199 :     obj = htobe32_internal(obj);
      76                 :        199 :     s.write(AsBytes(Span{&obj, 1}));
      77                 :        199 : }
      78                 :  176677302 : template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
      79                 :            : {
      80                 :  176677302 :     obj = htole64_internal(obj);
      81                 :  176677302 :     s.write(AsBytes(Span{&obj, 1}));
      82                 :  176677302 : }
      83                 :  308696850 : template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
      84                 :            : {
      85                 :  308696850 :     uint8_t obj;
      86                 :  308696850 :     s.read(AsWritableBytes(Span{&obj, 1}));
      87                 :  617393700 :     return obj;
      88                 :  308696850 : }
      89                 :      71073 : template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
      90                 :            : {
      91                 :      71073 :     uint16_t obj;
      92                 :      71073 :     s.read(AsWritableBytes(Span{&obj, 1}));
      93                 :     142146 :     return le16toh_internal(obj);
      94                 :      71073 : }
      95                 :        199 : template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
      96                 :            : {
      97                 :        199 :     uint16_t obj;
      98                 :        199 :     s.read(AsWritableBytes(Span{&obj, 1}));
      99                 :        398 :     return be16toh_internal(obj);
     100                 :        199 : }
     101                 :   55223108 : template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
     102                 :            : {
     103                 :   55223108 :     uint32_t obj;
     104                 :   55223108 :     s.read(AsWritableBytes(Span{&obj, 1}));
     105                 :  110446216 :     return le32toh_internal(obj);
     106                 :   55223108 : }
     107                 :        199 : template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
     108                 :            : {
     109                 :        199 :     uint32_t obj;
     110                 :        199 :     s.read(AsWritableBytes(Span{&obj, 1}));
     111                 :        398 :     return be32toh_internal(obj);
     112                 :        199 : }
     113                 :   17845207 : template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
     114                 :            : {
     115                 :   17845207 :     uint64_t obj;
     116                 :   17845207 :     s.read(AsWritableBytes(Span{&obj, 1}));
     117                 :   35690414 :     return le64toh_internal(obj);
     118                 :   17845207 : }
     119                 :            : 
     120                 :            : 
     121                 :            : class SizeComputer;
     122                 :            : 
     123                 :            : /**
     124                 :            :  * Convert any argument to a reference to X, maintaining constness.
     125                 :            :  *
     126                 :            :  * This can be used in serialization code to invoke a base class's
     127                 :            :  * serialization routines.
     128                 :            :  *
     129                 :            :  * Example use:
     130                 :            :  *   class Base { ... };
     131                 :            :  *   class Child : public Base {
     132                 :            :  *     int m_data;
     133                 :            :  *   public:
     134                 :            :  *     SERIALIZE_METHODS(Child, obj) {
     135                 :            :  *       READWRITE(AsBase<Base>(obj), obj.m_data);
     136                 :            :  *     }
     137                 :            :  *   };
     138                 :            :  *
     139                 :            :  * static_cast cannot easily be used here, as the type of Obj will be const Child&
     140                 :            :  * during serialization and Child& during deserialization. AsBase will convert to
     141                 :            :  * const Base& and Base& appropriately.
     142                 :            :  */
     143                 :            : template <class Out, class In>
     144                 :   36630622 : Out& AsBase(In& x)
     145                 :            : {
     146                 :            :     static_assert(std::is_base_of_v<Out, In>);
     147                 :   36630622 :     return x;
     148                 :            : }
     149                 :            : template <class Out, class In>
     150                 :  246606618 : const Out& AsBase(const In& x)
     151                 :            : {
     152                 :            :     static_assert(std::is_base_of_v<Out, In>);
     153                 :  246606618 :     return x;
     154                 :            : }
     155                 :            : 
     156                 :            : #define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__))
     157                 :            : #define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
     158                 :            : #define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; })
     159                 :            : 
     160                 :            : /**
     161                 :            :  * Implement the Ser and Unser methods needed for implementing a formatter (see Using below).
     162                 :            :  *
     163                 :            :  * Both Ser and Unser are delegated to a single static method SerializationOps, which is polymorphic
     164                 :            :  * in the serialized/deserialized type (allowing it to be const when serializing, and non-const when
     165                 :            :  * deserializing).
     166                 :            :  *
     167                 :            :  * Example use:
     168                 :            :  *   struct FooFormatter {
     169                 :            :  *     FORMATTER_METHODS(Class, obj) { READWRITE(obj.val1, VARINT(obj.val2)); }
     170                 :            :  *   }
     171                 :            :  *   would define a class FooFormatter that defines a serialization of Class objects consisting
     172                 :            :  *   of serializing its val1 member using the default serialization, and its val2 member using
     173                 :            :  *   VARINT serialization. That FooFormatter can then be used in statements like
     174                 :            :  *   READWRITE(Using<FooFormatter>(obj.bla)).
     175                 :            :  */
     176                 :            : #define FORMATTER_METHODS(cls, obj) \
     177                 :            :     template<typename Stream> \
     178                 :            :     static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}); } \
     179                 :            :     template<typename Stream> \
     180                 :            :     static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}); } \
     181                 :            :     template<typename Stream, typename Type, typename Operation> \
     182                 :            :     static void SerializationOps(Type& obj, Stream& s, Operation ser_action)
     183                 :            : 
     184                 :            : /**
     185                 :            :  * Formatter methods can retrieve parameters attached to a stream using the
     186                 :            :  * SER_PARAMS(type) macro as long as the stream is created directly or
     187                 :            :  * indirectly with a parameter of that type. This permits making serialization
     188                 :            :  * depend on run-time context in a type-safe way.
     189                 :            :  *
     190                 :            :  * Example use:
     191                 :            :  *   struct BarParameter { bool fancy; ... };
     192                 :            :  *   struct Bar { ... };
     193                 :            :  *   struct FooFormatter {
     194                 :            :  *     FORMATTER_METHODS(Bar, obj) {
     195                 :            :  *       auto& param = SER_PARAMS(BarParameter);
     196                 :            :  *       if (param.fancy) {
     197                 :            :  *         READWRITE(VARINT(obj.value));
     198                 :            :  *       } else {
     199                 :            :  *         READWRITE(obj.value);
     200                 :            :  *       }
     201                 :            :  *     }
     202                 :            :  *   };
     203                 :            :  * which would then be invoked as
     204                 :            :  *   READWRITE(BarParameter{...}(Using<FooFormatter>(obj.foo)))
     205                 :            :  *
     206                 :            :  * parameter(obj) can be invoked anywhere in the call stack; it is
     207                 :            :  * passed down recursively into all serialization code, until another
     208                 :            :  * serialization parameter overrides it.
     209                 :            :  *
     210                 :            :  * Parameters will be implicitly converted where appropriate. This means that
     211                 :            :  * "parent" serialization code can use a parameter that derives from, or is
     212                 :            :  * convertible to, a "child" formatter's parameter type.
     213                 :            :  *
     214                 :            :  * Compilation will fail in any context where serialization is invoked but
     215                 :            :  * no parameter of a type convertible to BarParameter is provided.
     216                 :            :  */
     217                 :            : #define SER_PARAMS(type) (s.template GetParams<type>())
     218                 :            : 
     219                 :            : #define BASE_SERIALIZE_METHODS(cls)                                                                 \
     220                 :            :     template <typename Stream>                                                                      \
     221                 :            :     void Serialize(Stream& s) const                                                                 \
     222                 :            :     {                                                                                               \
     223                 :            :         static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
     224                 :            :         Ser(s, *this);                                                                              \
     225                 :            :     }                                                                                               \
     226                 :            :     template <typename Stream>                                                                      \
     227                 :            :     void Unserialize(Stream& s)                                                                     \
     228                 :            :     {                                                                                               \
     229                 :            :         static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch");     \
     230                 :            :         Unser(s, *this);                                                                            \
     231                 :            :     }
     232                 :            : 
     233                 :            : /**
     234                 :            :  * Implement the Serialize and Unserialize methods by delegating to a single templated
     235                 :            :  * static method that takes the to-be-(de)serialized object as a parameter. This approach
     236                 :            :  * has the advantage that the constness of the object becomes a template parameter, and
     237                 :            :  * thus allows a single implementation that sees the object as const for serializing
     238                 :            :  * and non-const for deserializing, without casts.
     239                 :            :  */
     240                 :            : #define SERIALIZE_METHODS(cls, obj) \
     241                 :            :     BASE_SERIALIZE_METHODS(cls)     \
     242                 :            :     FORMATTER_METHODS(cls, obj)
     243                 :            : 
     244                 :            : // Templates for serializing to anything that looks like a stream,
     245                 :            : // i.e. anything that supports .read(Span<std::byte>) and .write(Span<const std::byte>)
     246                 :            : //
     247                 :            : // clang-format off
     248                 :            : 
     249                 :            : // Typically int8_t and char are distinct types, but some systems may define int8_t
     250                 :            : // in terms of char. Forbid serialization of char in the typical case, but allow it if
     251                 :            : // it's the only way to describe an int8_t.
     252                 :            : template<class T>
     253                 :            : concept CharNotInt8 = std::same_as<T, char> && !std::same_as<T, int8_t>;
     254                 :            : 
     255                 :            : template <typename Stream, CharNotInt8 V> void Serialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
     256                 :            : template <typename Stream> void Serialize(Stream& s, std::byte a) { ser_writedata8(s, uint8_t(a)); }
     257                 :       7319 : template<typename Stream> inline void Serialize(Stream& s, int8_t a  ) { ser_writedata8(s, a); }
     258                 :   85712897 : template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); }
     259                 :       1902 : template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); }
     260                 :       1732 : template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
     261                 :   93028022 : template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); }
     262                 :  225114679 : template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
     263                 :  142887294 : template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); }
     264                 :   33744817 : template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
     265                 :    1023310 : template <typename Stream, BasicByte B, int N> void Serialize(Stream& s, const B (&a)[N]) { s.write(MakeByteSpan(a)); }
     266                 :     519870 : template <typename Stream, BasicByte B, std::size_t N> void Serialize(Stream& s, const std::array<B, N>& a) { s.write(MakeByteSpan(a)); }
     267                 :  216517737 : template <typename Stream, BasicByte B> void Serialize(Stream& s, Span<B> span) { s.write(AsBytes(span)); }
     268                 :            : 
     269                 :            : template <typename Stream, CharNotInt8 V> void Unserialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
     270                 :            : template <typename Stream> void Unserialize(Stream& s, std::byte& a) { a = std::byte{ser_readdata8(s)}; }
     271                 :       1957 : template<typename Stream> inline void Unserialize(Stream& s, int8_t& a  ) { a = ser_readdata8(s); }
     272                 :   39899294 : template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); }
     273                 :       4631 : template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); }
     274                 :       2143 : template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
     275                 :   18878486 : template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); }
     276                 :   36327546 : template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
     277                 :   16219031 : template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); }
     278                 :    1608768 : template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
     279                 :    1273104 : template <typename Stream, BasicByte B, int N> void Unserialize(Stream& s, B (&a)[N]) { s.read(MakeWritableByteSpan(a)); }
     280                 :    3346892 : template <typename Stream, BasicByte B, std::size_t N> void Unserialize(Stream& s, std::array<B, N>& a) { s.read(MakeWritableByteSpan(a)); }
     281                 :   41330157 : template <typename Stream, BasicByte B> void Unserialize(Stream& s, Span<B> span) { s.read(AsWritableBytes(span)); }
     282                 :            : 
     283                 :     672437 : template <typename Stream> inline void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); }
     284                 :      14718 : template <typename Stream> inline void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
     285                 :            : // clang-format on
     286                 :            : 
     287                 :            : 
     288                 :            : /**
     289                 :            :  * Compact Size
     290                 :            :  * size <  253        -- 1 byte
     291                 :            :  * size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
     292                 :            :  * size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
     293                 :            :  * size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
     294                 :            :  */
     295                 :   16155824 : constexpr inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
     296                 :            : {
     297         [ +  + ]:   16155824 :     if (nSize < 253)             return sizeof(unsigned char);
     298         [ +  + ]:    8910987 :     else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
     299         [ +  + ]:    8908751 :     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
     300                 :        139 :     else                         return sizeof(unsigned char) + sizeof(uint64_t);
     301                 :   16155824 : }
     302                 :            : 
     303                 :            : inline void WriteCompactSize(SizeComputer& os, uint64_t nSize);
     304                 :            : 
     305                 :            : template<typename Stream>
     306                 :  542139941 : void WriteCompactSize(Stream& os, uint64_t nSize)
     307                 :            : {
     308   [ +  +  +  +  :  542139941 :     if (nSize < 253)
          +  +  +  +  +  
          +  +  -  +  +  
                   +  - ]
     309                 :            :     {
     310                 :  541747693 :         ser_writedata8(os, nSize);
     311                 :  541747693 :     }
     312   [ +  +  +  +  :     392248 :     else if (nSize <= std::numeric_limits<uint16_t>::max())
          +  -  +  +  +  
          +  #  #  +  +  
                   #  # ]
     313                 :            :     {
     314                 :     322658 :         ser_writedata8(os, 253);
     315                 :     322658 :         ser_writedata16(os, nSize);
     316                 :     322658 :     }
     317   [ +  +  +  -  :      69590 :     else if (nSize <= std::numeric_limits<unsigned int>::max())
          #  #  +  +  +  
          -  #  #  +  +  
                   #  # ]
     318                 :            :     {
     319                 :      24598 :         ser_writedata8(os, 254);
     320                 :      24598 :         ser_writedata32(os, nSize);
     321                 :      24598 :     }
     322                 :            :     else
     323                 :            :     {
     324                 :      44992 :         ser_writedata8(os, 255);
     325                 :      44992 :         ser_writedata64(os, nSize);
     326                 :            :     }
     327                 :  542139941 :     return;
     328                 :            : }
     329                 :            : 
     330                 :            : /**
     331                 :            :  * Decode a CompactSize-encoded variable-length integer.
     332                 :            :  *
     333                 :            :  * As these are primarily used to encode the size of vector-like serializations, by default a range
     334                 :            :  * check is performed. When used as a generic number encoding, range_check should be set to false.
     335                 :            :  */
     336                 :            : template<typename Stream>
     337                 :  220942493 : uint64_t ReadCompactSize(Stream& is, bool range_check = true)
     338                 :            : {
     339                 :  220942493 :     uint8_t chSize = ser_readdata8(is);
     340                 :  220942493 :     uint64_t nSizeRet = 0;
     341   [ +  +  +  +  :  220942493 :     if (chSize < 253)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     342                 :            :     {
     343                 :  220845141 :         nSizeRet = chSize;
     344                 :  220845141 :     }
     345   [ +  +  +  +  :      97352 :     else if (chSize == 253)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     346                 :            :     {
     347                 :      64090 :         nSizeRet = ser_readdata16(is);
     348   [ +  +  +  +  :      64090 :         if (nSizeRet < 253)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     349   [ +  -  +  -  :       2160 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
          +  -  +  -  +  
          -  +  -  #  #  
          #  #  #  #  #  
          #  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     350                 :      61930 :     }
     351   [ +  +  +  +  :      33262 :     else if (chSize == 254)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     352                 :            :     {
     353                 :      16842 :         nSizeRet = ser_readdata32(is);
     354   [ +  +  +  +  :      16842 :         if (nSizeRet < 0x10000u)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     355   [ +  -  +  -  :       2819 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
          +  -  +  -  +  
          -  +  -  #  #  
          #  #  #  #  #  
          #  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     356                 :      14023 :     }
     357                 :            :     else
     358                 :            :     {
     359                 :      16420 :         nSizeRet = ser_readdata64(is);
     360   [ +  +  +  +  :      16420 :         if (nSizeRet < 0x100000000ULL)
          +  +  #  #  #  
          #  +  +  +  +  
                   +  + ]
     361   [ +  -  +  -  :       2002 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
          +  -  +  -  +  
          -  +  -  #  #  
          #  #  #  #  #  
          #  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     362                 :            :     }
     363   [ +  -  +  +  :  220935512 :     if (range_check && nSizeRet > MAX_SIZE) {
          +  +  +  +  +  
          -  +  +  #  #  
          #  #  #  #  #  
          #  +  -  +  +  
          +  +  +  +  +  
                -  +  + ]
     364   [ +  -  +  -  :      10967 :         throw std::ios_base::failure("ReadCompactSize(): size too large");
          +  -  +  -  +  
          -  +  -  #  #  
          #  #  #  #  #  
          #  +  -  +  -  
          +  -  +  -  +  
                -  +  - ]
     365                 :            :     }
     366                 :  441849090 :     return nSizeRet;
     367                 :  220960441 : }
     368                 :            : 
     369                 :            : /**
     370                 :            :  * Variable-length integers: bytes are a MSB base-128 encoding of the number.
     371                 :            :  * The high bit in each byte signifies whether another digit follows. To make
     372                 :            :  * sure the encoding is one-to-one, one is subtracted from all but the last digit.
     373                 :            :  * Thus, the byte sequence a[] with length len, where all but the last byte
     374                 :            :  * has bit 128 set, encodes the number:
     375                 :            :  *
     376                 :            :  *  (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
     377                 :            :  *
     378                 :            :  * Properties:
     379                 :            :  * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
     380                 :            :  * * Every integer has exactly one encoding
     381                 :            :  * * Encoding does not depend on size of original integer type
     382                 :            :  * * No redundancy: every (infinite) byte sequence corresponds to a list
     383                 :            :  *   of encoded integers.
     384                 :            :  *
     385                 :            :  * 0:         [0x00]  256:        [0x81 0x00]
     386                 :            :  * 1:         [0x01]  16383:      [0xFE 0x7F]
     387                 :            :  * 127:       [0x7F]  16384:      [0xFF 0x00]
     388                 :            :  * 128:  [0x80 0x00]  16511:      [0xFF 0x7F]
     389                 :            :  * 255:  [0x80 0x7F]  65535: [0x82 0xFE 0x7F]
     390                 :            :  * 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
     391                 :            :  */
     392                 :            : 
     393                 :            : /**
     394                 :            :  * Mode for encoding VarInts.
     395                 :            :  *
     396                 :            :  * Currently there is no support for signed encodings. The default mode will not
     397                 :            :  * compile with signed values, and the legacy "nonnegative signed" mode will
     398                 :            :  * accept signed values, but improperly encode and decode them if they are
     399                 :            :  * negative. In the future, the DEFAULT mode could be extended to support
     400                 :            :  * negative numbers in a backwards compatible way, and additional modes could be
     401                 :            :  * added to support different varint formats (e.g. zigzag encoding).
     402                 :            :  */
     403                 :            : enum class VarIntMode { DEFAULT, NONNEGATIVE_SIGNED };
     404                 :            : 
     405                 :            : template <VarIntMode Mode, typename I>
     406                 :            : struct CheckVarIntMode {
     407                 :   57810720 :     constexpr CheckVarIntMode()
     408                 :            :     {
     409                 :            :         static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
     410                 :            :         static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
     411                 :   57810720 :     }
     412                 :            : };
     413                 :            : 
     414                 :            : template<VarIntMode Mode, typename I>
     415                 :            : inline unsigned int GetSizeOfVarInt(I n)
     416                 :            : {
     417                 :            :     CheckVarIntMode<Mode, I>();
     418                 :            :     int nRet = 0;
     419                 :            :     while(true) {
     420                 :            :         nRet++;
     421                 :            :         if (n <= 0x7F)
     422                 :            :             break;
     423                 :            :         n = (n >> 7) - 1;
     424                 :            :     }
     425                 :            :     return nRet;
     426                 :            : }
     427                 :            : 
     428                 :            : template<typename I>
     429                 :            : inline void WriteVarInt(SizeComputer& os, I n);
     430                 :            : 
     431                 :            : template<typename Stream, VarIntMode Mode, typename I>
     432                 :   12319072 : void WriteVarInt(Stream& os, I n)
     433                 :            : {
     434                 :   12319072 :     CheckVarIntMode<Mode, I>();
     435                 :   12319072 :     unsigned char tmp[(sizeof(n)*8+6)/7];
     436                 :   12319072 :     int len=0;
     437                 :   14364962 :     while(true) {
     438                 :   14364962 :         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
     439   [ +  +  +  +  :   14364962 :         if (n <= 0x7F)
          +  +  +  +  +  
          -  +  +  +  -  
             +  +  +  - ]
     440                 :   12319072 :             break;
     441                 :    2045890 :         n = (n >> 7) - 1;
     442                 :    2045890 :         len++;
     443                 :            :     }
     444                 :   12319072 :     do {
     445                 :   14364962 :         ser_writedata8(os, tmp[len]);
     446   [ +  +  +  +  :   14364962 :     } while(len--);
          +  +  +  +  -  
          +  +  +  -  +  
             +  +  -  + ]
     447                 :   12319072 : }
     448                 :            : 
     449                 :            : template<typename Stream, VarIntMode Mode, typename I>
     450                 :   45491648 : I ReadVarInt(Stream& is)
     451                 :            : {
     452                 :   45491648 :     CheckVarIntMode<Mode, I>();
     453                 :   45491648 :     I n = 0;
     454                 :   47830598 :     while(true) {
     455                 :   47830598 :         unsigned char chData = ser_readdata8(is);
     456   [ +  +  +  +  :   47830598 :         if (n > (std::numeric_limits<I>::max() >> 7)) {
          #  #  #  #  #  
                      # ]
     457   [ +  -  +  -  :        194 :            throw std::ios_base::failure("ReadVarInt(): size too large");
          +  -  +  -  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     458                 :            :         }
     459                 :   47830404 :         n = (n << 7) | (chData & 0x7F);
     460   [ +  +  +  +  :   47830404 :         if (chData & 0x80) {
          #  #  #  #  #  
                      # ]
     461   [ +  +  +  +  :    2339728 :             if (n == std::numeric_limits<I>::max()) {
          #  #  #  #  #  
                      # ]
     462   [ +  -  +  -  :         31 :                 throw std::ios_base::failure("ReadVarInt(): size too large");
          +  -  +  -  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     463                 :            :             }
     464                 :    2339697 :             n++;
     465                 :    2339697 :         } else {
     466                 :   45490676 :             return n;
     467                 :            :         }
     468   [ +  +  +  +  :   47830598 :     }
          #  #  #  #  #  
                      # ]
     469                 :   45491873 : }
     470                 :            : 
     471                 :            : /** Simple wrapper class to serialize objects using a formatter; used by Using(). */
     472                 :            : template<typename Formatter, typename T>
     473                 :            : class Wrapper
     474                 :            : {
     475                 :            :     static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
     476                 :            : protected:
     477                 :            :     T m_object;
     478                 :            : public:
     479                 :  272383119 :     explicit Wrapper(T obj) : m_object(obj) {}
     480                 :  115687112 :     template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
     481                 :  156662603 :     template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
     482                 :            : };
     483                 :            : 
     484                 :            : /** Cause serialization/deserialization of an object to be done using a specified formatter class.
     485                 :            :  *
     486                 :            :  * To use this, you need a class Formatter that has public functions Ser(stream, const object&) for
     487                 :            :  * serialization, and Unser(stream, object&) for deserialization. Serialization routines (inside
     488                 :            :  * READWRITE, or directly with << and >> operators), can then use Using<Formatter>(object).
     489                 :            :  *
     490                 :            :  * This works by constructing a Wrapper<Formatter, T>-wrapped version of object, where T is
     491                 :            :  * const during serialization, and non-const during deserialization, which maintains const
     492                 :            :  * correctness.
     493                 :            :  */
     494                 :            : template<typename Formatter, typename T>
     495                 :  272383119 : static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
     496                 :            : 
     497                 :            : #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
     498                 :            : #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
     499                 :            : #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
     500                 :            : #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
     501                 :            : 
     502                 :            : /** Serialization wrapper class for integers in VarInt format. */
     503                 :            : template<VarIntMode Mode>
     504                 :            : struct VarIntFormatter
     505                 :            : {
     506                 :   12319072 :     template<typename Stream, typename I> void Ser(Stream &s, I v)
     507                 :            :     {
     508                 :   12319072 :         WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
     509                 :   12319072 :     }
     510                 :            : 
     511                 :   45491648 :     template<typename Stream, typename I> void Unser(Stream& s, I& v)
     512                 :            :     {
     513                 :   45491648 :         v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
     514                 :   45491648 :     }
     515                 :            : };
     516                 :            : 
     517                 :            : /** Serialization wrapper class for custom integers and enums.
     518                 :            :  *
     519                 :            :  * It permits specifying the serialized size (1 to 8 bytes) and endianness.
     520                 :            :  *
     521                 :            :  * Use the big endian mode for values that are stored in memory in native
     522                 :            :  * byte order, but serialized in big endian notation. This is only intended
     523                 :            :  * to implement serializers that are compatible with existing formats, and
     524                 :            :  * its use is not recommended for new data structures.
     525                 :            :  */
     526                 :            : template<int Bytes, bool BigEndian = false>
     527                 :            : struct CustomUintFormatter
     528                 :            : {
     529                 :            :     static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
     530                 :            :     static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
     531                 :            : 
     532                 :    8536520 :     template <typename Stream, typename I> void Ser(Stream& s, I v)
     533                 :            :     {
     534   [ +  -  #  #  :    8536520 :         if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
          #  #  #  #  +  
          -  #  #  #  #  
          #  #  +  -  #  
          #  #  #  #  #  
          +  -  #  #  #  
                #  #  # ]
     535                 :            :         if (BigEndian) {
     536                 :    8238323 :             uint64_t raw = htobe64_internal(v);
     537                 :    8238323 :             s.write(AsBytes(Span{&raw, 1}).last(Bytes));
     538                 :    8238323 :         } else {
     539                 :     298197 :             uint64_t raw = htole64_internal(v);
     540                 :     298197 :             s.write(AsBytes(Span{&raw, 1}).first(Bytes));
     541                 :     298197 :         }
     542                 :    8536520 :     }
     543                 :            : 
     544                 :    9256061 :     template <typename Stream, typename I> void Unser(Stream& s, I& v)
     545                 :            :     {
     546                 :            :         using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
     547                 :            :         static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
     548                 :    9256061 :         uint64_t raw = 0;
     549                 :            :         if (BigEndian) {
     550                 :    8241044 :             s.read(AsWritableBytes(Span{&raw, 1}).last(Bytes));
     551                 :    8241044 :             v = static_cast<I>(be64toh_internal(raw));
     552                 :            :         } else {
     553                 :    1015017 :             s.read(AsWritableBytes(Span{&raw, 1}).first(Bytes));
     554                 :    1015017 :             v = static_cast<I>(le64toh_internal(raw));
     555                 :            :         }
     556                 :    9256061 :     }
     557                 :            : };
     558                 :            : 
     559                 :            : template<int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true>;
     560                 :            : 
     561                 :            : /** Formatter for integers in CompactSize format. */
     562                 :            : template<bool RangeCheck>
     563                 :            : struct CompactSizeFormatter
     564                 :            : {
     565                 :            :     template<typename Stream, typename I>
     566                 :   37869699 :     void Unser(Stream& s, I& v)
     567                 :            :     {
     568                 :   37869699 :         uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
     569   [ +  -  +  -  :   37869699 :         if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
          +  -  +  +  +  
          -  #  #  #  #  
          #  #  #  #  +  
             -  +  -  +  
                      - ]
     570   [ #  #  #  #  :         79 :             throw std::ios_base::failure("CompactSize exceeds limit of type");
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  +  
          -  -  +  +  -  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                #  #  # ]
     571                 :            :         }
     572                 :   37869620 :         v = n;
     573                 :   37869699 :     }
     574                 :            : 
     575                 :            :     template<typename Stream, typename I>
     576                 :    8301632 :     void Ser(Stream& s, I v)
     577                 :            :     {
     578                 :            :         static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers");
     579                 :            :         static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
     580                 :            : 
     581                 :    8301632 :         WriteCompactSize<Stream>(s, v);
     582                 :    8301632 :     }
     583                 :            : };
     584                 :            : 
     585                 :            : template <typename U, bool LOSSY = false>
     586                 :            : struct ChronoFormatter {
     587                 :            :     template <typename Stream, typename Tp>
     588                 :   15723001 :     void Unser(Stream& s, Tp& tp)
     589                 :            :     {
     590                 :   15723001 :         U u;
     591                 :   15723001 :         s >> u;
     592                 :            :         // Lossy deserialization does not make sense, so force Wnarrowing
     593                 :   15723001 :         tp = Tp{typename Tp::duration{typename Tp::duration::rep{u}}};
     594                 :   15723001 :     }
     595                 :            :     template <typename Stream, typename Tp>
     596                 :   16312544 :     void Ser(Stream& s, Tp tp)
     597                 :            :     {
     598                 :            :         if constexpr (LOSSY) {
     599                 :    8186139 :             s << U(tp.time_since_epoch().count());
     600                 :            :         } else {
     601                 :    8126405 :             s << U{tp.time_since_epoch().count()};
     602                 :            :         }
     603                 :   16312544 :     }
     604                 :            : };
     605                 :            : template <typename U>
     606                 :            : using LossyChronoFormatter = ChronoFormatter<U, true>;
     607                 :            : 
     608                 :            : class CompactSizeWriter
     609                 :            : {
     610                 :            : protected:
     611                 :            :     uint64_t n;
     612                 :            : public:
     613                 :     481618 :     explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { }
     614                 :            : 
     615                 :            :     template<typename Stream>
     616                 :     408479 :     void Serialize(Stream &s) const {
     617                 :     408479 :         WriteCompactSize<Stream>(s, n);
     618                 :     408479 :     }
     619                 :            : };
     620                 :            : 
     621                 :            : template<size_t Limit>
     622                 :            : struct LimitedStringFormatter
     623                 :            : {
     624                 :            :     template<typename Stream>
     625                 :      12308 :     void Unser(Stream& s, std::string& v)
     626                 :            :     {
     627                 :      12308 :         size_t size = ReadCompactSize(s);
     628         [ +  + ]:      12308 :         if (size > Limit) {
     629   [ +  -  -  +  :        253 :             throw std::ios_base::failure("String length limit exceeded");
                   +  - ]
     630                 :            :         }
     631                 :      12055 :         v.resize(size);
     632         [ +  + ]:      12055 :         if (size != 0) s.read(MakeWritableByteSpan(v));
     633                 :      12308 :     }
     634                 :            : 
     635                 :            :     template<typename Stream>
     636                 :        990 :     void Ser(Stream& s, const std::string& v)
     637                 :            :     {
     638                 :        990 :         s << v;
     639                 :        990 :     }
     640                 :            : };
     641                 :            : 
     642                 :            : /** Formatter to serialize/deserialize vector elements using another formatter
     643                 :            :  *
     644                 :            :  * Example:
     645                 :            :  *   struct X {
     646                 :            :  *     std::vector<uint64_t> v;
     647                 :            :  *     SERIALIZE_METHODS(X, obj) { READWRITE(Using<VectorFormatter<VarInt>>(obj.v)); }
     648                 :            :  *   };
     649                 :            :  * will define a struct that contains a vector of uint64_t, which is serialized
     650                 :            :  * as a vector of VarInt-encoded integers.
     651                 :            :  *
     652                 :            :  * V is not required to be an std::vector type. It works for any class that
     653                 :            :  * exposes a value_type, size, reserve, emplace_back, back, and const iterators.
     654                 :            :  */
     655                 :            : template<class Formatter>
     656                 :            : struct VectorFormatter
     657                 :            : {
     658                 :            :     template<typename Stream, typename V>
     659                 :   60905526 :     void Ser(Stream& s, const V& v)
     660                 :            :     {
     661                 :   60905526 :         Formatter formatter;
     662                 :   60905526 :         WriteCompactSize(s, v.size());
     663   [ +  +  +  +  :  375256576 :         for (const typename V::value_type& elem : v) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
                +  +  + ]
     664                 :  314351050 :             formatter.Ser(s, elem);
     665                 :  314351050 :         }
     666                 :   60905526 :     }
     667                 :            : 
     668                 :            :     template<typename Stream, typename V>
     669                 :   23453718 :     void Unser(Stream& s, V& v)
     670                 :            :     {
     671                 :   23453718 :         Formatter formatter;
     672                 :   23453718 :         v.clear();
     673                 :   23453718 :         size_t size = ReadCompactSize(s);
     674                 :   23453718 :         size_t allocated = 0;
     675   [ +  +  +  +  :   25129360 :         while (allocated < size) {
          +  +  +  +  #  
          #  #  #  +  +  
          #  #  #  #  +  
             +  +  +  +  
                      + ]
     676                 :            :             // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
     677                 :            :             // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
     678                 :            :             // X MiB of data to make us allocate X+5 Mib.
     679                 :            :             static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
     680                 :    1675642 :             allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
     681                 :    1675642 :             v.reserve(allocated);
     682   [ +  +  +  +  :  189190405 :             while (v.size() < allocated) {
          +  +  +  +  #  
          #  #  #  +  +  
          #  #  #  #  +  
             +  +  +  +  
                      + ]
     683                 :  187514763 :                 v.emplace_back();
     684                 :  187514763 :                 formatter.Unser(s, v.back());
     685                 :            :             }
     686                 :            :         }
     687                 :   23453718 :     };
     688                 :            : };
     689                 :            : 
     690                 :            : /**
     691                 :            :  * Forward declarations
     692                 :            :  */
     693                 :            : 
     694                 :            : /**
     695                 :            :  *  string
     696                 :            :  */
     697                 :            : template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
     698                 :            : template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
     699                 :            : 
     700                 :            : /**
     701                 :            :  * prevector
     702                 :            :  */
     703                 :            : template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
     704                 :            : template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
     705                 :            : 
     706                 :            : /**
     707                 :            :  * vector
     708                 :            :  */
     709                 :            : template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
     710                 :            : template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
     711                 :            : 
     712                 :            : /**
     713                 :            :  * pair
     714                 :            :  */
     715                 :            : template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
     716                 :            : template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
     717                 :            : 
     718                 :            : /**
     719                 :            :  * map
     720                 :            :  */
     721                 :            : template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
     722                 :            : template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
     723                 :            : 
     724                 :            : /**
     725                 :            :  * set
     726                 :            :  */
     727                 :            : template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
     728                 :            : template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
     729                 :            : 
     730                 :            : /**
     731                 :            :  * shared_ptr
     732                 :            :  */
     733                 :            : template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
     734                 :            : template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
     735                 :            : 
     736                 :            : /**
     737                 :            :  * unique_ptr
     738                 :            :  */
     739                 :            : template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
     740                 :            : template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
     741                 :            : 
     742                 :            : 
     743                 :            : /**
     744                 :            :  * If none of the specialized versions above matched, default to calling member function.
     745                 :            :  */
     746                 :            : template <class T, class Stream>
     747                 :            : concept Serializable = requires(T a, Stream s) { a.Serialize(s); };
     748                 :            : template <typename Stream, typename T>
     749                 :            :     requires Serializable<T, Stream>
     750                 :  943752780 : void Serialize(Stream& os, const T& a)
     751                 :            : {
     752                 :  943752780 :     a.Serialize(os);
     753                 :  943752780 : }
     754                 :            : 
     755                 :            : template <class T, class Stream>
     756                 :            : concept Unserializable = requires(T a, Stream s) { a.Unserialize(s); };
     757                 :            : template <typename Stream, typename T>
     758                 :            :     requires Unserializable<T, Stream>
     759                 :  303588586 : void Unserialize(Stream& is, T&& a)
     760                 :            : {
     761                 :  303588586 :     a.Unserialize(is);
     762                 :  303588586 : }
     763                 :            : 
     764                 :            : /** Default formatter. Serializes objects as themselves.
     765                 :            :  *
     766                 :            :  * The vector/prevector serialization code passes this to VectorFormatter
     767                 :            :  * to enable reusing that logic. It shouldn't be needed elsewhere.
     768                 :            :  */
     769                 :            : struct DefaultFormatter
     770                 :            : {
     771                 :            :     template<typename Stream, typename T>
     772                 :  310040840 :     static void Ser(Stream& s, const T& t) { Serialize(s, t); }
     773                 :            : 
     774                 :            :     template<typename Stream, typename T>
     775                 :  169088061 :     static void Unser(Stream& s, T& t) { Unserialize(s, t); }
     776                 :            : };
     777                 :            : 
     778                 :            : 
     779                 :            : 
     780                 :            : 
     781                 :            : 
     782                 :            : /**
     783                 :            :  * string
     784                 :            :  */
     785                 :            : template<typename Stream, typename C>
     786                 :    7197832 : void Serialize(Stream& os, const std::basic_string<C>& str)
     787                 :            : {
     788                 :    7197832 :     WriteCompactSize(os, str.size());
     789         [ +  + ]:    7197832 :     if (!str.empty())
     790                 :    6678055 :         os.write(MakeByteSpan(str));
     791                 :    7197832 : }
     792                 :            : 
     793                 :            : template<typename Stream, typename C>
     794                 :      13787 : void Unserialize(Stream& is, std::basic_string<C>& str)
     795                 :            : {
     796                 :      13787 :     unsigned int nSize = ReadCompactSize(is);
     797                 :      13787 :     str.resize(nSize);
     798         [ +  + ]:      13787 :     if (nSize != 0)
     799                 :       7289 :         is.read(MakeWritableByteSpan(str));
     800                 :      13787 : }
     801                 :            : 
     802                 :            : 
     803                 :            : 
     804                 :            : /**
     805                 :            :  * prevector
     806                 :            :  */
     807                 :            : template <typename Stream, unsigned int N, typename T>
     808                 :  236753757 : void Serialize(Stream& os, const prevector<N, T>& v)
     809                 :            : {
     810                 :            :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     811                 :  236753441 :         WriteCompactSize(os, v.size());
     812   [ +  +  +  +  :  236753441 :         if (!v.empty()) os.write(MakeByteSpan(v));
          -  +  +  +  -  
                +  -  + ]
     813                 :            :     } else {
     814                 :        316 :         Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
     815                 :            :     }
     816                 :  236753757 : }
     817                 :            : 
     818                 :            : 
     819                 :            : template <typename Stream, unsigned int N, typename T>
     820                 :   12507211 : void Unserialize(Stream& is, prevector<N, T>& v)
     821                 :            : {
     822                 :            :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     823                 :            :         // Limit size per read so bogus size value won't cause out of memory
     824                 :   12507211 :         v.clear();
     825                 :   12507211 :         unsigned int nSize = ReadCompactSize(is);
     826                 :   12507211 :         unsigned int i = 0;
     827   [ +  +  +  + ]:   18145669 :         while (i < nSize) {
     828                 :    5638458 :             unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
     829                 :    5638458 :             v.resize_uninitialized(i + blk);
     830                 :    5638458 :             is.read(AsWritableBytes(Span{&v[i], blk}));
     831                 :    5638458 :             i += blk;
     832                 :    5638458 :         }
     833                 :   12507211 :     } else {
     834                 :            :         Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
     835                 :            :     }
     836                 :   12507211 : }
     837                 :            : 
     838                 :            : 
     839                 :            : /**
     840                 :            :  * vector
     841                 :            :  */
     842                 :            : template <typename Stream, typename T, typename A>
     843                 :  288368818 : void Serialize(Stream& os, const std::vector<T, A>& v)
     844                 :            : {
     845                 :            :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     846                 :  230404646 :         WriteCompactSize(os, v.size());
     847   [ +  +  +  +  :  230404646 :         if (!v.empty()) os.write(MakeByteSpan(v));
          -  +  +  +  +  
                      + ]
     848                 :            :     } else if constexpr (std::is_same_v<T, bool>) {
     849                 :            :         // A special case for std::vector<bool>, as dereferencing
     850                 :            :         // std::vector<bool>::const_iterator does not result in a const bool&
     851                 :            :         // due to std::vector's special casing for bool arguments.
     852                 :       2180 :         WriteCompactSize(os, v.size());
     853         [ +  + ]:     345076 :         for (bool elem : v) {
     854                 :     342896 :             ::Serialize(os, elem);
     855                 :     342896 :         }
     856                 :            :     } else {
     857                 :   57961992 :         Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
     858                 :            :     }
     859                 :  288368818 : }
     860                 :            : 
     861                 :            : 
     862                 :            : template <typename Stream, typename T, typename A>
     863                 :  151372534 : void Unserialize(Stream& is, std::vector<T, A>& v)
     864                 :            : {
     865                 :            :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     866                 :            :         // Limit size per read so bogus size value won't cause out of memory
     867                 :  145742629 :         v.clear();
     868                 :  145742629 :         unsigned int nSize = ReadCompactSize(is);
     869                 :  145742629 :         unsigned int i = 0;
     870   [ +  +  +  +  :  148811650 :         while (i < nSize) {
                   +  + ]
     871                 :    3069021 :             unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
     872                 :    3069021 :             v.resize(i + blk);
     873                 :    3069021 :             is.read(AsWritableBytes(Span{&v[i], blk}));
     874                 :    3069021 :             i += blk;
     875                 :    3069021 :         }
     876                 :  145742629 :     } else {
     877                 :    5629905 :         Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
     878                 :            :     }
     879                 :  151372534 : }
     880                 :            : 
     881                 :            : 
     882                 :            : /**
     883                 :            :  * pair
     884                 :            :  */
     885                 :            : template<typename Stream, typename K, typename T>
     886                 :    4634903 : void Serialize(Stream& os, const std::pair<K, T>& item)
     887                 :            : {
     888                 :    4634903 :     Serialize(os, item.first);
     889                 :    4634903 :     Serialize(os, item.second);
     890                 :    4634903 : }
     891                 :            : 
     892                 :            : template<typename Stream, typename K, typename T>
     893                 :      81777 : void Unserialize(Stream& is, std::pair<K, T>& item)
     894                 :            : {
     895                 :      81777 :     Unserialize(is, item.first);
     896                 :      81777 :     Unserialize(is, item.second);
     897                 :      81777 : }
     898                 :            : 
     899                 :            : 
     900                 :            : 
     901                 :            : /**
     902                 :            :  * map
     903                 :            :  */
     904                 :            : template<typename Stream, typename K, typename T, typename Pred, typename A>
     905                 :     145183 : void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
     906                 :            : {
     907                 :     145183 :     WriteCompactSize(os, m.size());
     908         [ +  + ]:     583431 :     for (const auto& entry : m)
     909                 :     438248 :         Serialize(os, entry);
     910                 :     145183 : }
     911                 :            : 
     912                 :            : template<typename Stream, typename K, typename T, typename Pred, typename A>
     913                 :        144 : void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
     914                 :            : {
     915                 :        144 :     m.clear();
     916                 :        144 :     unsigned int nSize = ReadCompactSize(is);
     917                 :        144 :     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
     918         [ +  + ]:      81900 :     for (unsigned int i = 0; i < nSize; i++)
     919                 :            :     {
     920                 :      81756 :         std::pair<K, T> item;
     921         [ #  # ]:      81756 :         Unserialize(is, item);
     922         [ #  # ]:      81756 :         mi = m.insert(mi, item);
     923                 :      81756 :     }
     924                 :        144 : }
     925                 :            : 
     926                 :            : 
     927                 :            : 
     928                 :            : /**
     929                 :            :  * set
     930                 :            :  */
     931                 :            : template<typename Stream, typename K, typename Pred, typename A>
     932                 :      13610 : void Serialize(Stream& os, const std::set<K, Pred, A>& m)
     933                 :            : {
     934                 :      13610 :     WriteCompactSize(os, m.size());
     935         [ +  + ]:      59265 :     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
     936                 :      45655 :         Serialize(os, (*it));
     937                 :      13610 : }
     938                 :            : 
     939                 :            : template<typename Stream, typename K, typename Pred, typename A>
     940                 :      27046 : void Unserialize(Stream& is, std::set<K, Pred, A>& m)
     941                 :            : {
     942                 :      27046 :     m.clear();
     943                 :      27046 :     unsigned int nSize = ReadCompactSize(is);
     944                 :      27046 :     typename std::set<K, Pred, A>::iterator it = m.begin();
     945         [ +  + ]:     312970 :     for (unsigned int i = 0; i < nSize; i++)
     946                 :            :     {
     947                 :     285924 :         K key;
     948                 :     285924 :         Unserialize(is, key);
     949                 :     285924 :         it = m.insert(it, key);
     950                 :     285924 :     }
     951                 :      27046 : }
     952                 :            : 
     953                 :            : 
     954                 :            : 
     955                 :            : /**
     956                 :            :  * unique_ptr
     957                 :            :  */
     958                 :            : template<typename Stream, typename T> void
     959                 :            : Serialize(Stream& os, const std::unique_ptr<const T>& p)
     960                 :            : {
     961                 :            :     Serialize(os, *p);
     962                 :            : }
     963                 :            : 
     964                 :            : template<typename Stream, typename T>
     965                 :            : void Unserialize(Stream& is, std::unique_ptr<const T>& p)
     966                 :            : {
     967                 :            :     p.reset(new T(deserialize, is));
     968                 :            : }
     969                 :            : 
     970                 :            : 
     971                 :            : 
     972                 :            : /**
     973                 :            :  * shared_ptr
     974                 :            :  */
     975                 :            : template<typename Stream, typename T> void
     976                 :    3653316 : Serialize(Stream& os, const std::shared_ptr<const T>& p)
     977                 :            : {
     978                 :    3653316 :     Serialize(os, *p);
     979                 :    3653316 : }
     980                 :            : 
     981                 :            : template<typename Stream, typename T>
     982                 :    2868648 : void Unserialize(Stream& is, std::shared_ptr<const T>& p)
     983                 :            : {
     984                 :    2868648 :     p = std::make_shared<const T>(deserialize, is);
     985                 :    2868648 : }
     986                 :            : 
     987                 :            : /**
     988                 :            :  * Support for (un)serializing many things at once
     989                 :            :  */
     990                 :            : 
     991                 :            : template <typename Stream, typename... Args>
     992                 :  591357842 : void SerializeMany(Stream& s, const Args&... args)
     993                 :            : {
     994                 :  591357842 :     (::Serialize(s, args), ...);
     995                 :  591357842 : }
     996                 :            : 
     997                 :            : template <typename Stream, typename... Args>
     998                 :  105845852 : inline void UnserializeMany(Stream& s, Args&&... args)
     999                 :            : {
    1000                 :  105845852 :     (::Unserialize(s, args), ...);
    1001                 :  105845852 : }
    1002                 :            : 
    1003                 :            : /**
    1004                 :            :  * Support for all macros providing or using the ser_action parameter of the SerializationOps method.
    1005                 :            :  */
    1006                 :            : struct ActionSerialize {
    1007                 :            :     static constexpr bool ForRead() { return false; }
    1008                 :            : 
    1009                 :            :     template<typename Stream, typename... Args>
    1010                 :  590286012 :     static void SerReadWriteMany(Stream& s, const Args&... args)
    1011                 :            :     {
    1012                 :  590286012 :         ::SerializeMany(s, args...);
    1013                 :  590286012 :     }
    1014                 :            : 
    1015                 :            :     template<typename Stream, typename Type, typename Fn>
    1016                 :    9847671 :     static void SerRead(Stream& s, Type&&, Fn&&)
    1017                 :            :     {
    1018                 :    9847671 :     }
    1019                 :            : 
    1020                 :            :     template<typename Stream, typename Type, typename Fn>
    1021                 :    9846430 :     static void SerWrite(Stream& s, Type&& obj, Fn&& fn)
    1022                 :            :     {
    1023                 :    9846430 :         fn(s, std::forward<Type>(obj));
    1024                 :    9846430 :     }
    1025                 :            : };
    1026                 :            : struct ActionUnserialize {
    1027                 :            :     static constexpr bool ForRead() { return true; }
    1028                 :            : 
    1029                 :            :     template<typename Stream, typename... Args>
    1030                 :  105737574 :     static void SerReadWriteMany(Stream& s, Args&&... args)
    1031                 :            :     {
    1032                 :  105737574 :         ::UnserializeMany(s, args...);
    1033                 :  105737574 :     }
    1034                 :            : 
    1035                 :            :     template<typename Stream, typename Type, typename Fn>
    1036                 :    7766534 :     static void SerRead(Stream& s, Type&& obj, Fn&& fn)
    1037                 :            :     {
    1038                 :    7766534 :         fn(s, std::forward<Type>(obj));
    1039                 :    7766534 :     }
    1040                 :            : 
    1041                 :            :     template<typename Stream, typename Type, typename Fn>
    1042                 :    7766429 :     static void SerWrite(Stream& s, Type&&, Fn&&)
    1043                 :            :     {
    1044                 :    7766429 :     }
    1045                 :            : };
    1046                 :            : 
    1047                 :            : /* ::GetSerializeSize implementations
    1048                 :            :  *
    1049                 :            :  * Computing the serialized size of objects is done through a special stream
    1050                 :            :  * object of type SizeComputer, which only records the number of bytes written
    1051                 :            :  * to it.
    1052                 :            :  *
    1053                 :            :  * If your Serialize or SerializationOp method has non-trivial overhead for
    1054                 :            :  * serialization, it may be worthwhile to implement a specialized version for
    1055                 :            :  * SizeComputer, which uses the s.seek() method to record bytes that would
    1056                 :            :  * be written instead.
    1057                 :            :  */
    1058                 :            : class SizeComputer
    1059                 :            : {
    1060                 :            : protected:
    1061                 :    8943725 :     size_t nSize{0};
    1062                 :            : 
    1063                 :            : public:
    1064                 :   17887450 :     SizeComputer() {}
    1065                 :            : 
    1066                 :  571295678 :     void write(Span<const std::byte> src)
    1067                 :            :     {
    1068                 :  571295678 :         this->nSize += src.size();
    1069                 :  571295678 :     }
    1070                 :            : 
    1071                 :            :     /** Pretend _nSize bytes are written, without specifying them. */
    1072                 :    2693001 :     void seek(size_t _nSize)
    1073                 :            :     {
    1074                 :    2693001 :         this->nSize += _nSize;
    1075                 :    2693001 :     }
    1076                 :            : 
    1077                 :            :     template<typename T>
    1078                 :    8695130 :     SizeComputer& operator<<(const T& obj)
    1079                 :            :     {
    1080                 :    8695130 :         ::Serialize(*this, obj);
    1081                 :    8695130 :         return (*this);
    1082                 :            :     }
    1083                 :            : 
    1084                 :    8943725 :     size_t size() const {
    1085                 :    8943725 :         return nSize;
    1086                 :            :     }
    1087                 :            : };
    1088                 :            : 
    1089                 :            : template<typename I>
    1090                 :            : inline void WriteVarInt(SizeComputer &s, I n)
    1091                 :            : {
    1092                 :            :     s.seek(GetSizeOfVarInt<I>(n));
    1093                 :            : }
    1094                 :            : 
    1095                 :    2693001 : inline void WriteCompactSize(SizeComputer &s, uint64_t nSize)
    1096                 :            : {
    1097                 :    2693001 :     s.seek(GetSizeOfCompactSize(nSize));
    1098                 :    2693001 : }
    1099                 :            : 
    1100                 :            : template <typename T>
    1101                 :    8656960 : size_t GetSerializeSize(const T& t)
    1102                 :            : {
    1103                 :    8656960 :     return (SizeComputer() << t).size();
    1104                 :            : }
    1105                 :            : 
    1106                 :            : //! Check if type contains a stream by seeing if has a GetStream() method.
    1107                 :            : template<typename T>
    1108                 :            : concept ContainsStream = requires(T t) { t.GetStream(); };
    1109                 :            : 
    1110                 :            : /** Wrapper that overrides the GetParams() function of a stream. */
    1111                 :            : template <typename SubStream, typename Params>
    1112                 :            : class ParamsStream
    1113                 :            : {
    1114                 :            :     const Params& m_params;
    1115                 :            :     // If ParamsStream constructor is passed an lvalue argument, Substream will
    1116                 :            :     // be a reference type, and m_substream will reference that argument.
    1117                 :            :     // Otherwise m_substream will be a substream instance and move from the
    1118                 :            :     // argument. Letting ParamsStream contain a substream instance instead of
    1119                 :            :     // just a reference is useful to make the ParamsStream object self contained
    1120                 :            :     // and let it do cleanup when destroyed, for example by closing files if
    1121                 :            :     // SubStream is a file stream.
    1122                 :            :     SubStream m_substream;
    1123                 :            : 
    1124                 :            : public:
    1125                 :   46095191 :     ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
    1126                 :            : 
    1127                 :            :     template <typename NestedSubstream, typename Params1, typename Params2, typename... NestedParams>
    1128                 :            :     ParamsStream(NestedSubstream&& s, const Params1& params1 LIFETIMEBOUND, const Params2& params2 LIFETIMEBOUND, const NestedParams&... params LIFETIMEBOUND)
    1129                 :            :         : ParamsStream{::ParamsStream{std::forward<NestedSubstream>(s), params2, params...}, params1} {}
    1130                 :            : 
    1131                 :  238794519 :     template <typename U> ParamsStream& operator<<(const U& obj) { ::Serialize(*this, obj); return *this; }
    1132                 :  134843318 :     template <typename U> ParamsStream& operator>>(U&& obj) { ::Unserialize(*this, obj); return *this; }
    1133                 : 1022803350 :     void write(Span<const std::byte> src) { GetStream().write(src); }
    1134                 :  321716857 :     void read(Span<std::byte> dst) { GetStream().read(dst); }
    1135                 :     675985 :     void ignore(size_t num) { GetStream().ignore(num); }
    1136                 :          0 :     bool eof() const { return GetStream().eof(); }
    1137                 :            :     size_t size() const { return GetStream().size(); }
    1138                 :            : 
    1139                 :            :     //! Get reference to stream parameters.
    1140                 :            :     template <typename P>
    1141                 :   82752867 :     const auto& GetParams() const
    1142                 :            :     {
    1143                 :            :         if constexpr (std::is_convertible_v<Params, P>) {
    1144                 :   82752867 :             return m_params;
    1145                 :            :         } else {
    1146                 :            :             return m_substream.template GetParams<P>();
    1147                 :            :         }
    1148                 :            :     }
    1149                 :            : 
    1150                 :            :     //! Get reference to underlying stream.
    1151                 : 1409823852 :     auto& GetStream()
    1152                 :            :     {
    1153                 :            :         if constexpr (ContainsStream<SubStream>) {
    1154                 :   64627660 :             return m_substream.GetStream();
    1155                 :            :         } else {
    1156                 : 1345196192 :             return m_substream;
    1157                 :            :         }
    1158                 :            :     }
    1159                 :          0 :     const auto& GetStream() const
    1160                 :            :     {
    1161                 :            :         if constexpr (ContainsStream<SubStream>) {
    1162                 :            :             return m_substream.GetStream();
    1163                 :            :         } else {
    1164                 :          0 :             return m_substream;
    1165                 :            :         }
    1166                 :            :     }
    1167                 :            : };
    1168                 :            : 
    1169                 :            : /**
    1170                 :            :  * Explicit template deduction guide is required for single-parameter
    1171                 :            :  * constructor so Substream&& is treated as a forwarding reference, and
    1172                 :            :  * SubStream is deduced as reference type for lvalue arguments.
    1173                 :            :  */
    1174                 :            : template <typename Substream, typename Params>
    1175                 :            : ParamsStream(Substream&&, const Params&) -> ParamsStream<Substream, Params>;
    1176                 :            : 
    1177                 :            : /**
    1178                 :            :  * Template deduction guide for multiple params arguments that creates a nested
    1179                 :            :  * ParamsStream.
    1180                 :            :  */
    1181                 :            : template <typename Substream, typename Params1, typename Params2, typename... Params>
    1182                 :            : ParamsStream(Substream&& s, const Params1& params1, const Params2& params2, const Params&... params) ->
    1183                 :            :     ParamsStream<decltype(ParamsStream{std::forward<Substream>(s), params2, params...}), Params1>;
    1184                 :            : 
    1185                 :            : /** Wrapper that serializes objects with the specified parameters. */
    1186                 :            : template <typename Params, typename T>
    1187                 :            : class ParamsWrapper
    1188                 :            : {
    1189                 :            :     const Params& m_params;
    1190                 :            :     T& m_object;
    1191                 :            : 
    1192                 :            : public:
    1193                 :   46030131 :     explicit ParamsWrapper(const Params& params, T& obj) : m_params{params}, m_object{obj} {}
    1194                 :            : 
    1195                 :            :     template <typename Stream>
    1196                 :   22043950 :     void Serialize(Stream& s) const
    1197                 :            :     {
    1198                 :   22043950 :         ParamsStream ss{s, m_params};
    1199                 :   22043950 :         ::Serialize(ss, m_object);
    1200                 :   22043950 :     }
    1201                 :            :     template <typename Stream>
    1202                 :   24043509 :     void Unserialize(Stream& s)
    1203                 :            :     {
    1204                 :   24043509 :         ParamsStream ss{s, m_params};
    1205                 :   24043509 :         ::Unserialize(ss, m_object);
    1206                 :   24043509 :     }
    1207                 :            : };
    1208                 :            : 
    1209                 :            : /**
    1210                 :            :  * Helper macro for SerParams structs
    1211                 :            :  *
    1212                 :            :  * Allows you define SerParams instances and then apply them directly
    1213                 :            :  * to an object via function call syntax, eg:
    1214                 :            :  *
    1215                 :            :  *   constexpr SerParams FOO{....};
    1216                 :            :  *   ss << FOO(obj);
    1217                 :            :  */
    1218                 :            : #define SER_PARAMS_OPFUNC                                                                \
    1219                 :            :     /**                                                                                  \
    1220                 :            :      * Return a wrapper around t that (de)serializes it with specified parameter params. \
    1221                 :            :      *                                                                                   \
    1222                 :            :      * See SER_PARAMS for more information on serialization parameters.                  \
    1223                 :            :      */                                                                                  \
    1224                 :            :     template <typename T>                                                                \
    1225                 :            :     auto operator()(T&& t) const                                                         \
    1226                 :            :     {                                                                                    \
    1227                 :            :         return ParamsWrapper{*this, t};                                                  \
    1228                 :            :     }
    1229                 :            : 
    1230                 :            : #endif // BITCOIN_SERIALIZE_H

Generated by: LCOV version 1.16