LCOV - code coverage report
Current view: top level - src - serialize.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 93.0 % 343 319
Test Date: 2025-06-01 05:54:06 Functions: 67.7 % 1665 1127
Branches: 35.7 % 1014 362

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #ifndef BITCOIN_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                 :    36536524 : template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
      55                 :             : {
      56                 :    36536524 :     s.write(std::as_bytes(std::span{&obj, 1}));
      57                 :    36536522 : }
      58                 :        4157 : template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
      59                 :             : {
      60                 :        4157 :     obj = htole16_internal(obj);
      61                 :        4157 :     s.write(std::as_bytes(std::span{&obj, 1}));
      62                 :        4157 : }
      63                 :             : template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
      64                 :             : {
      65                 :             :     obj = htobe16_internal(obj);
      66                 :             :     s.write(std::as_bytes(std::span{&obj, 1}));
      67                 :             : }
      68                 :    38597102 : template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
      69                 :             : {
      70                 :    38597102 :     obj = htole32_internal(obj);
      71                 :    38597102 :     s.write(std::as_bytes(std::span{&obj, 1}));
      72                 :    38597102 : }
      73                 :        1387 : template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
      74                 :             : {
      75                 :        1387 :     obj = htobe32_internal(obj);
      76                 :        1387 :     s.write(std::as_bytes(std::span{&obj, 1}));
      77                 :        1387 : }
      78                 :    15501506 : template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
      79                 :             : {
      80                 :    15501506 :     obj = htole64_internal(obj);
      81                 :    15501506 :     s.write(std::as_bytes(std::span{&obj, 1}));
      82                 :    15501506 : }
      83                 :     1035435 : template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
      84                 :             : {
      85                 :             :     uint8_t obj;
      86                 :     1035435 :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
      87                 :     1035414 :     return obj;
      88                 :             : }
      89                 :         114 : template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
      90                 :             : {
      91                 :             :     uint16_t obj;
      92                 :         114 :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
      93                 :         114 :     return le16toh_internal(obj);
      94                 :             : }
      95                 :             : template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
      96                 :             : {
      97                 :             :     uint16_t obj;
      98                 :             :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
      99                 :             :     return be16toh_internal(obj);
     100                 :             : }
     101                 :       45858 : template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
     102                 :             : {
     103                 :             :     uint32_t obj;
     104                 :       45858 :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
     105                 :       45837 :     return le32toh_internal(obj);
     106                 :             : }
     107                 :         445 : template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
     108                 :             : {
     109                 :             :     uint32_t obj;
     110                 :         445 :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
     111                 :         445 :     return be32toh_internal(obj);
     112                 :             : }
     113                 :       15014 : template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
     114                 :             : {
     115                 :             :     uint64_t obj;
     116                 :       15014 :     s.read(std::as_writable_bytes(std::span{&obj, 1}));
     117                 :       15014 :     return le64toh_internal(obj);
     118                 :             : }
     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                 :       22086 : Out& AsBase(In& x)
     145                 :             : {
     146                 :             :     static_assert(std::is_base_of_v<Out, In>);
     147                 :       22086 :     return x;
     148                 :             : }
     149                 :             : template <class Out, class In>
     150                 :    16648535 : const Out& AsBase(const In& x)
     151                 :             : {
     152                 :             :     static_assert(std::is_base_of_v<Out, In>);
     153                 :    16648535 :     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, std::remove_const_t<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_v<const cls&, decltype(*this)>, "Serialize type mismatch");      \
     224                 :             :         Ser(s, *this);                                                                              \
     225                 :             :     }                                                                                               \
     226                 :             :     template <typename Stream>                                                                      \
     227                 :             :     void Unserialize(Stream& s)                                                                     \
     228                 :             :     {                                                                                               \
     229                 :             :         static_assert(std::is_same_v<cls&, decltype(*this)>, "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(std::span<std::byte>) and .write(std::span<const std::byte>)
     246                 :             : //
     247                 :             : 
     248                 :             : // Typically int8_t and char are distinct types, but some systems may define int8_t
     249                 :             : // in terms of char. Forbid serialization of char in the typical case, but allow it if
     250                 :             : // it's the only way to describe an int8_t.
     251                 :             : template<class T>
     252                 :             : concept CharNotInt8 = std::same_as<T, char> && !std::same_as<T, int8_t>;
     253                 :             : 
     254                 :             : // clang-format off
     255                 :             : template <typename Stream, CharNotInt8 V> void Serialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
     256                 :           2 : template <typename Stream> void Serialize(Stream& s, std::byte a) { ser_writedata8(s, uint8_t(a)); }
     257                 :           2 : template <typename Stream> void Serialize(Stream& s, int8_t a)    { ser_writedata8(s, uint8_t(a)); }
     258                 :     4080598 : template <typename Stream> void Serialize(Stream& s, uint8_t a)   { ser_writedata8(s, a); }
     259                 :           2 : template <typename Stream> void Serialize(Stream& s, int16_t a)   { ser_writedata16(s, uint16_t(a)); }
     260                 :          35 : template <typename Stream> void Serialize(Stream& s, uint16_t a)  { ser_writedata16(s, a); }
     261                 :     4804606 : template <typename Stream> void Serialize(Stream& s, int32_t a)   { ser_writedata32(s, uint32_t(a)); }
     262                 :    33792442 : template <typename Stream> void Serialize(Stream& s, uint32_t a)  { ser_writedata32(s, a); }
     263                 :    15471039 : template <typename Stream> void Serialize(Stream& s, int64_t a)   { ser_writedata64(s, uint64_t(a)); }
     264                 :       30462 : template <typename Stream> void Serialize(Stream& s, uint64_t a)  { ser_writedata64(s, a); }
     265                 :             : 
     266                 :         325 : template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const B (&a)[N])           { s.write(MakeByteSpan(a)); }
     267                 :       14694 : template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, const std::array<B, N>& a) { s.write(MakeByteSpan(a)); }
     268                 :    26418889 : template <typename Stream, BasicByte B, size_t N> void Serialize(Stream& s, std::span<B, N> span)      { s.write(std::as_bytes(span)); }
     269                 :       31897 : template <typename Stream, BasicByte B>           void Serialize(Stream& s, std::span<B> span)         { s.write(std::as_bytes(span)); }
     270                 :             : 
     271                 :             : template <typename Stream, CharNotInt8 V> void Unserialize(Stream&, V) = delete; // char serialization forbidden. Use uint8_t or int8_t
     272                 :          17 : template <typename Stream> void Unserialize(Stream& s, std::byte& a) { a = std::byte(ser_readdata8(s)); }
     273                 :           1 : template <typename Stream> void Unserialize(Stream& s, int8_t& a)    { a = int8_t(ser_readdata8(s)); }
     274                 :       42957 : template <typename Stream> void Unserialize(Stream& s, uint8_t& a)   { a = ser_readdata8(s); }
     275                 :             : template <typename Stream> void Unserialize(Stream& s, int16_t& a)   { a = int16_t(ser_readdata16(s)); }
     276                 :          34 : template <typename Stream> void Unserialize(Stream& s, uint16_t& a)  { a = ser_readdata16(s); }
     277                 :       10371 : template <typename Stream> void Unserialize(Stream& s, int32_t& a)   { a = int32_t(ser_readdata32(s)); }
     278                 :       35465 : template <typename Stream> void Unserialize(Stream& s, uint32_t& a)  { a = ser_readdata32(s); }
     279                 :       13246 : template <typename Stream> void Unserialize(Stream& s, int64_t& a)   { a = int64_t(ser_readdata64(s)); }
     280                 :        1766 : template <typename Stream> void Unserialize(Stream& s, uint64_t& a)  { a = ser_readdata64(s); }
     281                 :             : 
     282                 :        1949 : template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, B (&a)[N])            { s.read(MakeWritableByteSpan(a)); }
     283                 :        2133 : template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::array<B, N>& a)  { s.read(MakeWritableByteSpan(a)); }
     284                 :           1 : template <typename Stream, BasicByte B, size_t N> void Unserialize(Stream& s, std::span<B, N> span) { s.read(std::as_writable_bytes(span)); }
     285                 :       71471 : template <typename Stream, BasicByte B>           void Unserialize(Stream& s, std::span<B> span)    { s.read(std::as_writable_bytes(span)); }
     286                 :             : 
     287                 :        3259 : template <typename Stream> void Serialize(Stream& s, bool a)    { uint8_t f = a; ser_writedata8(s, f); }
     288                 :          12 : template <typename Stream> void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
     289                 :             : // clang-format on
     290                 :             : 
     291                 :             : 
     292                 :             : /**
     293                 :             :  * Compact Size
     294                 :             :  * size <  253        -- 1 byte
     295                 :             :  * size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
     296                 :             :  * size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
     297                 :             :  * size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
     298                 :             :  */
     299                 :       25844 : constexpr inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
     300                 :             : {
     301 [ +  + ][ -  +  :       15813 :     if (nSize < 253)             return sizeof(unsigned char);
          -  +  -  +  -  
                +  -  + ]
     302 [ +  + ][ -  +  :          86 :     else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
             -  -  -  - ]
           [ #  #  #  # ]
           [ #  #  #  #  
          #  #  #  #  #  
                #  #  # ]
     303 [ -  + ][ #  #  :           2 :     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
             #  #  #  # ]
           [ #  #  #  # ]
           [ #  #  #  #  
          #  #  #  #  #  
                      # ]
     304                 :           0 :     else                         return sizeof(unsigned char) + sizeof(uint64_t);
     305                 :             : }
     306                 :             : 
     307                 :             : inline void WriteCompactSize(SizeComputer& os, uint64_t nSize);
     308                 :             : 
     309                 :             : template<typename Stream>
     310                 :    20927283 : void WriteCompactSize(Stream& os, uint64_t nSize)
     311                 :             : {
     312         [ +  + ]:    20927283 :     if (nSize < 253)
     313                 :             :     {
     314                 :    20923114 :         ser_writedata8(os, nSize);
     315                 :             :     }
     316         [ +  + ]:        4169 :     else if (nSize <= std::numeric_limits<uint16_t>::max())
     317                 :             :     {
     318                 :        4120 :         ser_writedata8(os, 253);
     319                 :        4120 :         ser_writedata16(os, nSize);
     320                 :             :     }
     321         [ +  - ]:          49 :     else if (nSize <= std::numeric_limits<unsigned int>::max())
     322                 :             :     {
     323                 :          49 :         ser_writedata8(os, 254);
     324                 :          49 :         ser_writedata32(os, nSize);
     325                 :             :     }
     326                 :             :     else
     327                 :             :     {
     328                 :           0 :         ser_writedata8(os, 255);
     329                 :           0 :         ser_writedata64(os, nSize);
     330                 :             :     }
     331                 :    20927282 :     return;
     332                 :             : }
     333                 :             : 
     334                 :             : /**
     335                 :             :  * Decode a CompactSize-encoded variable-length integer.
     336                 :             :  *
     337                 :             :  * As these are primarily used to encode the size of vector-like serializations, by default a range
     338                 :             :  * check is performed. When used as a generic number encoding, range_check should be set to false.
     339                 :             :  */
     340                 :             : template<typename Stream>
     341                 :       54285 : uint64_t ReadCompactSize(Stream& is, bool range_check = true)
     342                 :             : {
     343                 :       54285 :     uint8_t chSize = ser_readdata8(is);
     344                 :       54279 :     uint64_t nSizeRet = 0;
     345         [ +  + ]:       54279 :     if (chSize < 253)
     346                 :             :     {
     347                 :       54175 :         nSizeRet = chSize;
     348                 :             :     }
     349         [ +  + ]:         104 :     else if (chSize == 253)
     350                 :             :     {
     351                 :          80 :         nSizeRet = ser_readdata16(is);
     352         [ +  + ]:          80 :         if (nSizeRet < 253)
     353         [ +  - ]:           2 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
     354                 :             :     }
     355         [ +  + ]:          24 :     else if (chSize == 254)
     356                 :             :     {
     357                 :          22 :         nSizeRet = ser_readdata32(is);
     358         [ +  + ]:          22 :         if (nSizeRet < 0x10000u)
     359         [ +  - ]:           2 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
     360                 :             :     }
     361                 :             :     else
     362                 :             :     {
     363                 :           2 :         nSizeRet = ser_readdata64(is);
     364         [ +  - ]:           2 :         if (nSizeRet < 0x100000000ULL)
     365         [ +  - ]:           2 :             throw std::ios_base::failure("non-canonical ReadCompactSize()");
     366                 :             :     }
     367         [ -  + ]:       54273 :     if (range_check && nSizeRet > MAX_SIZE) {
     368         [ #  # ]:           0 :         throw std::ios_base::failure("ReadCompactSize(): size too large");
     369                 :             :     }
     370                 :       54273 :     return nSizeRet;
     371                 :             : }
     372                 :             : 
     373                 :             : /**
     374                 :             :  * Variable-length integers: bytes are a MSB base-128 encoding of the number.
     375                 :             :  * The high bit in each byte signifies whether another digit follows. To make
     376                 :             :  * sure the encoding is one-to-one, one is subtracted from all but the last digit.
     377                 :             :  * Thus, the byte sequence a[] with length len, where all but the last byte
     378                 :             :  * has bit 128 set, encodes the number:
     379                 :             :  *
     380                 :             :  *  (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
     381                 :             :  *
     382                 :             :  * Properties:
     383                 :             :  * * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
     384                 :             :  * * Every integer has exactly one encoding
     385                 :             :  * * Encoding does not depend on size of original integer type
     386                 :             :  * * No redundancy: every (infinite) byte sequence corresponds to a list
     387                 :             :  *   of encoded integers.
     388                 :             :  *
     389                 :             :  * 0:         [0x00]  256:        [0x81 0x00]
     390                 :             :  * 1:         [0x01]  16383:      [0xFE 0x7F]
     391                 :             :  * 127:       [0x7F]  16384:      [0xFF 0x00]
     392                 :             :  * 128:  [0x80 0x00]  16511:      [0xFF 0x7F]
     393                 :             :  * 255:  [0x80 0x7F]  65535: [0x82 0xFE 0x7F]
     394                 :             :  * 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
     395                 :             :  */
     396                 :             : 
     397                 :             : /**
     398                 :             :  * Mode for encoding VarInts.
     399                 :             :  *
     400                 :             :  * Currently there is no support for signed encodings. The default mode will not
     401                 :             :  * compile with signed values, and the legacy "nonnegative signed" mode will
     402                 :             :  * accept signed values, but improperly encode and decode them if they are
     403                 :             :  * negative. In the future, the DEFAULT mode could be extended to support
     404                 :             :  * negative numbers in a backwards compatible way, and additional modes could be
     405                 :             :  * added to support different varint formats (e.g. zigzag encoding).
     406                 :             :  */
     407                 :             : enum class VarIntMode { DEFAULT, NONNEGATIVE_SIGNED };
     408                 :             : 
     409                 :             : template <VarIntMode Mode, typename I>
     410                 :             : struct CheckVarIntMode {
     411                 :     4551545 :     constexpr CheckVarIntMode()
     412                 :             :     {
     413                 :             :         static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned_v<I>, "Unsigned type required with mode DEFAULT.");
     414                 :             :         static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed_v<I>, "Signed type required with mode NONNEGATIVE_SIGNED.");
     415                 :             :     }
     416                 :             : };
     417                 :             : 
     418                 :             : template<VarIntMode Mode, typename I>
     419                 :             : inline unsigned int GetSizeOfVarInt(I n)
     420                 :             : {
     421                 :             :     CheckVarIntMode<Mode, I>();
     422                 :             :     int nRet = 0;
     423                 :             :     while(true) {
     424                 :             :         nRet++;
     425                 :             :         if (n <= 0x7F)
     426                 :             :             break;
     427                 :             :         n = (n >> 7) - 1;
     428                 :             :     }
     429                 :             :     return nRet;
     430                 :             : }
     431                 :             : 
     432                 :             : template<typename I>
     433                 :             : inline void WriteVarInt(SizeComputer& os, I n);
     434                 :             : 
     435                 :             : template<typename Stream, VarIntMode Mode, typename I>
     436                 :     4220126 : void WriteVarInt(Stream& os, I n)
     437                 :             : {
     438                 :             :     CheckVarIntMode<Mode, I>();
     439                 :             :     unsigned char tmp[(sizeof(n)*8+6)/7];
     440                 :     4220126 :     int len=0;
     441                 :     7303867 :     while(true) {
     442         [ +  + ]:    11523993 :         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
     443         [ +  + ]:    11523992 :         if (n <= 0x7F)
     444                 :             :             break;
     445                 :     7303867 :         n = (n >> 7) - 1;
     446                 :     7303867 :         len++;
     447                 :             :     }
     448         [ +  + ]:    11523993 :     do {
     449                 :    11523993 :         ser_writedata8(os, tmp[len]);
     450                 :             :     } while(len--);
     451                 :     4220126 : }
     452                 :             : 
     453                 :             : template<typename Stream, VarIntMode Mode, typename I>
     454                 :      331419 : I ReadVarInt(Stream& is)
     455                 :             : {
     456                 :             :     CheckVarIntMode<Mode, I>();
     457                 :      331419 :     I n = 0;
     458                 :      606299 :     while(true) {
     459                 :      937718 :         unsigned char chData = ser_readdata8(is);
     460         [ -  + ]:      937718 :         if (n > (std::numeric_limits<I>::max() >> 7)) {
     461         [ #  # ]:           0 :            throw std::ios_base::failure("ReadVarInt(): size too large");
     462                 :             :         }
     463                 :      937718 :         n = (n << 7) | (chData & 0x7F);
     464         [ +  + ]:      937718 :         if (chData & 0x80) {
     465         [ -  + ]:      606299 :             if (n == std::numeric_limits<I>::max()) {
     466         [ #  # ]:           0 :                 throw std::ios_base::failure("ReadVarInt(): size too large");
     467                 :             :             }
     468                 :      606299 :             n++;
     469                 :             :         } else {
     470                 :      331419 :             return n;
     471                 :             :         }
     472                 :             :     }
     473                 :             : }
     474                 :             : 
     475                 :             : /** Simple wrapper class to serialize objects using a formatter; used by Using(). */
     476                 :             : template<typename Formatter, typename T>
     477                 :             : class Wrapper
     478                 :             : {
     479                 :             :     static_assert(std::is_lvalue_reference_v<T>, "Wrapper needs an lvalue reference type T");
     480                 :             : protected:
     481                 :             :     T m_object;
     482                 :             : public:
     483                 :     8633089 :     explicit Wrapper(T obj) : m_object(obj) {}
     484                 :    12414168 :     template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
     485                 :      966565 :     template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
     486                 :             : };
     487                 :             : 
     488                 :             : /** Cause serialization/deserialization of an object to be done using a specified formatter class.
     489                 :             :  *
     490                 :             :  * To use this, you need a class Formatter that has public functions Ser(stream, const object&) for
     491                 :             :  * serialization, and Unser(stream, object&) for deserialization. Serialization routines (inside
     492                 :             :  * READWRITE, or directly with << and >> operators), can then use Using<Formatter>(object).
     493                 :             :  *
     494                 :             :  * This works by constructing a Wrapper<Formatter, T>-wrapped version of object, where T is
     495                 :             :  * const during serialization, and non-const during deserialization, which maintains const
     496                 :             :  * correctness.
     497                 :             :  */
     498                 :             : template<typename Formatter, typename T>
     499 [ +  - ][ +  -  :     4410067 : static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
           -  +  - ][ +  
          -  -  +  +  -  
          +  -  +  -  +  
           -  -  + ][ +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
           [ +  -  +  -  
             +  -  +  - ]
           [ +  -  +  - ]
     500                 :             : 
     501                 :             : #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
     502                 :             : #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
     503                 :             : #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
     504                 :             : #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
     505                 :             : 
     506                 :             : /** Serialization wrapper class for integers in VarInt format. */
     507                 :             : template<VarIntMode Mode>
     508                 :             : struct VarIntFormatter
     509                 :             : {
     510                 :     4220126 :     template<typename Stream, typename I> void Ser(Stream &s, I v)
     511                 :             :     {
     512                 :     4220126 :         WriteVarInt<Stream,Mode, std::remove_cv_t<I>>(s, v);
     513                 :             :     }
     514                 :             : 
     515                 :      331419 :     template<typename Stream, typename I> void Unser(Stream& s, I& v)
     516                 :             :     {
     517                 :      662838 :         v = ReadVarInt<Stream,Mode, std::remove_cv_t<I>>(s);
     518                 :             :     }
     519                 :             : };
     520                 :             : 
     521                 :             : /** Serialization wrapper class for custom integers and enums.
     522                 :             :  *
     523                 :             :  * It permits specifying the serialized size (1 to 8 bytes) and endianness.
     524                 :             :  *
     525                 :             :  * Use the big endian mode for values that are stored in memory in native
     526                 :             :  * byte order, but serialized in big endian notation. This is only intended
     527                 :             :  * to implement serializers that are compatible with existing formats, and
     528                 :             :  * its use is not recommended for new data structures.
     529                 :             :  */
     530                 :             : template<int Bytes, bool BigEndian = false>
     531                 :             : struct CustomUintFormatter
     532                 :             : {
     533                 :             :     static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
     534                 :             :     static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
     535                 :             : 
     536                 :          70 :     template <typename Stream, typename I> void Ser(Stream& s, I v)
     537                 :             :     {
     538   [ -  +  -  - ]:          32 :         if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
     539                 :             :         if (BigEndian) {
     540                 :          31 :             uint64_t raw = htobe64_internal(v);
     541                 :          31 :             s.write(std::as_bytes(std::span{&raw, 1}).last(Bytes));
     542                 :             :         } else {
     543                 :          39 :             uint64_t raw = htole64_internal(v);
     544                 :          39 :             s.write(std::as_bytes(std::span{&raw, 1}).first(Bytes));
     545                 :             :         }
     546                 :          70 :     }
     547                 :             : 
     548                 :          57 :     template <typename Stream, typename I> void Unser(Stream& s, I& v)
     549                 :             :     {
     550                 :             :         using U = typename std::conditional_t<std::is_enum_v<I>, std::underlying_type<I>, std::common_type<I>>::type;
     551                 :             :         static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
     552                 :          57 :         uint64_t raw = 0;
     553                 :             :         if (BigEndian) {
     554                 :          26 :             s.read(std::as_writable_bytes(std::span{&raw, 1}).last(Bytes));
     555                 :          26 :             v = static_cast<I>(be64toh_internal(raw));
     556                 :             :         } else {
     557                 :          31 :             s.read(std::as_writable_bytes(std::span{&raw, 1}).first(Bytes));
     558                 :          31 :             v = static_cast<I>(le64toh_internal(raw));
     559                 :             :         }
     560                 :          57 :     }
     561                 :             : };
     562                 :             : 
     563                 :             : template<int Bytes> using BigEndianFormatter = CustomUintFormatter<Bytes, true>;
     564                 :             : 
     565                 :             : /** Formatter for integers in CompactSize format. */
     566                 :             : template<bool RangeCheck>
     567                 :             : struct CompactSizeFormatter
     568                 :             : {
     569                 :             :     template<typename Stream, typename I>
     570                 :          82 :     void Unser(Stream& s, I& v)
     571                 :             :     {
     572                 :         153 :         uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
     573         [ -  + ]:          11 :         if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
     574         [ #  # ]:           0 :             throw std::ios_base::failure("CompactSize exceeds limit of type");
     575                 :             :         }
     576                 :          82 :         v = n;
     577                 :          11 :     }
     578                 :             : 
     579                 :             :     template<typename Stream, typename I>
     580                 :          44 :     void Ser(Stream& s, I v)
     581                 :             :     {
     582                 :             :         static_assert(std::is_unsigned_v<I>, "CompactSize only supported for unsigned integers");
     583                 :             :         static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
     584                 :             : 
     585                 :          44 :         WriteCompactSize<Stream>(s, v);
     586                 :             :     }
     587                 :             : };
     588                 :             : 
     589                 :             : template <typename U, bool LOSSY = false>
     590                 :             : struct ChronoFormatter {
     591                 :             :     template <typename Stream, typename Tp>
     592                 :          41 :     void Unser(Stream& s, Tp& tp)
     593                 :             :     {
     594                 :             :         U u;
     595                 :          41 :         s >> u;
     596                 :             :         // Lossy deserialization does not make sense, so force Wnarrowing
     597                 :          41 :         tp = Tp{typename Tp::duration{typename Tp::duration::rep{u}}};
     598                 :          41 :     }
     599                 :             :     template <typename Stream, typename Tp>
     600                 :          41 :     void Ser(Stream& s, Tp tp)
     601                 :             :     {
     602                 :             :         if constexpr (LOSSY) {
     603                 :          24 :             s << U(tp.time_since_epoch().count());
     604                 :             :         } else {
     605                 :          17 :             s << U{tp.time_since_epoch().count()};
     606                 :             :         }
     607                 :          41 :     }
     608                 :             : };
     609                 :             : template <typename U>
     610                 :             : using LossyChronoFormatter = ChronoFormatter<U, true>;
     611                 :             : 
     612                 :             : class CompactSizeWriter
     613                 :             : {
     614                 :             : protected:
     615                 :             :     uint64_t n;
     616                 :             : public:
     617                 :        3640 :     explicit CompactSizeWriter(uint64_t n_in) : n(n_in) { }
     618                 :             : 
     619                 :             :     template<typename Stream>
     620                 :        3655 :     void Serialize(Stream &s) const {
     621                 :        3655 :         WriteCompactSize<Stream>(s, n);
     622                 :             :     }
     623                 :             : };
     624                 :             : 
     625                 :             : template<size_t Limit>
     626                 :             : struct LimitedStringFormatter
     627                 :             : {
     628                 :             :     template<typename Stream>
     629                 :           5 :     void Unser(Stream& s, std::string& v)
     630                 :             :     {
     631                 :           5 :         size_t size = ReadCompactSize(s);
     632         [ -  + ]:           4 :         if (size > Limit) {
     633         [ #  # ]:           0 :             throw std::ios_base::failure("String length limit exceeded");
     634                 :             :         }
     635                 :           4 :         v.resize(size);
     636         [ +  + ]:           4 :         if (size != 0) s.read(MakeWritableByteSpan(v));
     637                 :           4 :     }
     638                 :             : 
     639                 :             :     template<typename Stream>
     640                 :           3 :     void Ser(Stream& s, const std::string& v)
     641                 :             :     {
     642                 :           2 :         s << v;
     643                 :             :     }
     644                 :             : };
     645                 :             : 
     646                 :             : /** Formatter to serialize/deserialize vector elements using another formatter
     647                 :             :  *
     648                 :             :  * Example:
     649                 :             :  *   struct X {
     650                 :             :  *     std::vector<uint64_t> v;
     651                 :             :  *     SERIALIZE_METHODS(X, obj) { READWRITE(Using<VectorFormatter<VarInt>>(obj.v)); }
     652                 :             :  *   };
     653                 :             :  * will define a struct that contains a vector of uint64_t, which is serialized
     654                 :             :  * as a vector of VarInt-encoded integers.
     655                 :             :  *
     656                 :             :  * V is not required to be an std::vector type. It works for any class that
     657                 :             :  * exposes a value_type, size, reserve, emplace_back, back, and const iterators.
     658                 :             :  */
     659                 :             : template<class Formatter>
     660                 :             : struct VectorFormatter
     661                 :             : {
     662                 :             :     template<typename Stream, typename V>
     663         [ +  + ]:     3869467 :     void Ser(Stream& s, const V& v)
     664                 :             :     {
     665                 :           2 :         Formatter formatter;
     666                 :     3879427 :         WriteCompactSize(s, v.size());
     667         [ +  + ]:    11293228 :         for (const typename V::value_type& elem : v) {
           [ +  +  +  + ]
     668                 :     7156921 :             formatter.Ser(s, elem);
     669                 :             :         }
     670                 :     3869467 :     }
     671                 :             : 
     672                 :             :     template<typename Stream, typename V>
     673         [ +  + ]:       17926 :     void Unser(Stream& s, V& v)
     674                 :             :     {
     675         [ -  + ]:           3 :         Formatter formatter;
     676                 :       17926 :         v.clear();
     677                 :       17926 :         size_t size = ReadCompactSize(s);
     678                 :       17921 :         size_t allocated = 0;
     679         [ +  + ]:       32839 :         while (allocated < size) {
     680                 :             :             // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
     681                 :             :             // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
     682                 :             :             // X MiB of data to make us allocate X+5 Mib.
     683                 :             :             static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
     684         [ +  - ]:       14919 :             allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
     685                 :       14919 :             v.reserve(allocated);
     686         [ +  + ]:       86477 :             while (v.size() < allocated) {
     687                 :       71559 :                 v.emplace_back();
     688                 :       71559 :                 formatter.Unser(s, v.back());
     689                 :             :             }
     690                 :             :         }
     691                 :       17920 :     };
     692                 :             : };
     693                 :             : 
     694                 :             : /**
     695                 :             :  * Forward declarations
     696                 :             :  */
     697                 :             : 
     698                 :             : /**
     699                 :             :  *  string
     700                 :             :  */
     701                 :             : template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
     702                 :             : template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
     703                 :             : 
     704                 :             : /**
     705                 :             :  * prevector
     706                 :             :  */
     707                 :             : template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
     708                 :             : template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
     709                 :             : 
     710                 :             : /**
     711                 :             :  * vector
     712                 :             :  */
     713                 :             : template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
     714                 :             : template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
     715                 :             : 
     716                 :             : /**
     717                 :             :  * pair
     718                 :             :  */
     719                 :             : template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
     720                 :             : template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
     721                 :             : 
     722                 :             : /**
     723                 :             :  * map
     724                 :             :  */
     725                 :             : template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
     726                 :             : template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
     727                 :             : 
     728                 :             : /**
     729                 :             :  * set
     730                 :             :  */
     731                 :             : template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
     732                 :             : template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
     733                 :             : 
     734                 :             : /**
     735                 :             :  * shared_ptr
     736                 :             :  */
     737                 :             : template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
     738                 :             : template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
     739                 :             : 
     740                 :             : /**
     741                 :             :  * unique_ptr
     742                 :             :  */
     743                 :             : template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
     744                 :             : template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
     745                 :             : 
     746                 :             : 
     747                 :             : /**
     748                 :             :  * If none of the specialized versions above matched, default to calling member function.
     749                 :             :  */
     750                 :             : template <class T, class Stream>
     751                 :             : concept Serializable = requires(T a, Stream s) { a.Serialize(s); };
     752                 :             : template <typename Stream, typename T>
     753                 :             :     requires Serializable<T, Stream>
     754                 :    96650509 : void Serialize(Stream& os, const T& a)
     755                 :             : {
     756                 :    96650508 :     a.Serialize(os);
     757                 :    96650508 : }
     758                 :             : 
     759                 :             : template <class T, class Stream>
     760                 :             : concept Unserializable = requires(T a, Stream s) { a.Unserialize(s); };
     761                 :             : template <typename Stream, typename T>
     762                 :             :     requires Unserializable<T, Stream>
     763                 :      774101 : void Unserialize(Stream& is, T&& a)
     764                 :             : {
     765                 :      774060 :     a.Unserialize(is);
     766                 :      774043 : }
     767                 :             : 
     768                 :             : /** Default formatter. Serializes objects as themselves.
     769                 :             :  *
     770                 :             :  * The vector/prevector serialization code passes this to VectorFormatter
     771                 :             :  * to enable reusing that logic. It shouldn't be needed elsewhere.
     772                 :             :  */
     773                 :             : struct DefaultFormatter
     774                 :             : {
     775                 :             :     template<typename Stream, typename T>
     776                 :     7156879 :     static void Ser(Stream& s, const T& t) { Serialize(s, t); }
     777                 :             : 
     778                 :             :     template<typename Stream, typename T>
     779                 :       71548 :     static void Unser(Stream& s, T& t) { Unserialize(s, t); }
     780                 :             : };
     781                 :             : 
     782                 :             : 
     783                 :             : 
     784                 :             : 
     785                 :             : 
     786                 :             : /**
     787                 :             :  * string
     788                 :             :  */
     789                 :             : template<typename Stream, typename C>
     790         [ -  + ]:       72491 : void Serialize(Stream& os, const std::basic_string<C>& str)
     791                 :             : {
     792         [ +  + ]:       72492 :     WriteCompactSize(os, str.size());
     793         [ +  + ]:       72490 :     if (!str.empty())
     794                 :       65819 :         os.write(MakeByteSpan(str));
     795                 :       72490 : }
     796                 :             : 
     797                 :             : template<typename Stream, typename C>
     798                 :         306 : void Unserialize(Stream& is, std::basic_string<C>& str)
     799                 :             : {
     800                 :         306 :     unsigned int nSize = ReadCompactSize(is);
     801                 :         306 :     str.resize(nSize);
     802         [ +  + ]:         306 :     if (nSize != 0)
     803                 :         278 :         is.read(MakeWritableByteSpan(str));
     804                 :         306 : }
     805                 :             : 
     806                 :             : 
     807                 :             : 
     808                 :             : /**
     809                 :             :  * prevector
     810                 :             :  */
     811                 :             : template <typename Stream, unsigned int N, typename T>
     812         [ +  + ]:    16835451 : void Serialize(Stream& os, const prevector<N, T>& v)
     813                 :             : {
     814                 :             :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     815         [ +  + ]:    16568848 :         WriteCompactSize(os, v.size());
     816         [ +  + ]:    16568611 :         if (!v.empty()) os.write(MakeByteSpan(v));
     817                 :             :     } else {
     818                 :      266840 :         Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
     819                 :             :     }
     820                 :    16835451 : }
     821                 :             : 
     822                 :             : 
     823                 :             : template <typename Stream, unsigned int N, typename T>
     824                 :       19830 : void Unserialize(Stream& is, prevector<N, T>& v)
     825                 :             : {
     826                 :             :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     827                 :             :         // Limit size per read so bogus size value won't cause out of memory
     828                 :       19830 :         v.clear();
     829                 :       19830 :         unsigned int nSize = ReadCompactSize(is);
     830                 :       19830 :         unsigned int i = 0;
     831         [ +  + ]:       34563 :         while (i < nSize) {
     832         [ +  - ]:       14733 :             unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
     833         [ +  + ]:       14733 :             v.resize_uninitialized(i + blk);
     834                 :       14733 :             is.read(std::as_writable_bytes(std::span{&v[i], blk}));
     835                 :       14733 :             i += blk;
     836                 :             :         }
     837                 :             :     } else {
     838                 :             :         Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
     839                 :             :     }
     840                 :       19830 : }
     841                 :             : 
     842                 :             : 
     843                 :             : /**
     844                 :             :  * vector
     845                 :             :  */
     846                 :             : template <typename Stream, typename T, typename A>
     847         [ +  + ]:     3784054 : void Serialize(Stream& os, const std::vector<T, A>& v)
     848                 :             : {
     849                 :             :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     850                 :      188667 :         WriteCompactSize(os, v.size());
     851         [ +  + ]:      185818 :         if (!v.empty()) os.write(MakeByteSpan(v));
     852                 :             :     } else if constexpr (std::is_same_v<T, bool>) {
     853                 :             :         // A special case for std::vector<bool>, as dereferencing
     854                 :             :         // std::vector<bool>::const_iterator does not result in a const bool&
     855                 :             :         // due to std::vector's special casing for bool arguments.
     856                 :           6 :         WriteCompactSize(os, v.size());
     857         [ -  + ]:        4780 :         for (bool elem : v) {
     858                 :        2387 :             ::Serialize(os, elem);
     859                 :             :         }
     860                 :             :     } else {
     861                 :     3602574 :         Serialize(os, Using<VectorFormatter<DefaultFormatter>>(v));
     862                 :             :     }
     863                 :     3784054 : }
     864                 :             : 
     865                 :             : 
     866                 :             : template <typename Stream, typename T, typename A>
     867         [ +  + ]:       29662 : void Unserialize(Stream& is, std::vector<T, A>& v)
     868                 :             : {
     869                 :             :     if constexpr (BasicByte<T>) { // Use optimized version for unformatted basic bytes
     870                 :             :         // Limit size per read so bogus size value won't cause out of memory
     871                 :       11748 :         v.clear();
     872                 :       11748 :         unsigned int nSize = ReadCompactSize(is);
     873                 :       11748 :         unsigned int i = 0;
     874         [ +  + ]:       23477 :         while (i < nSize) {
     875         [ +  - ]:       11729 :             unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
     876                 :       11729 :             v.resize(i + blk);
     877                 :       11729 :             is.read(std::as_writable_bytes(std::span{&v[i], blk}));
     878                 :       11729 :             i += blk;
     879                 :             :         }
     880                 :             :     } else {
     881                 :       17914 :         Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
     882                 :             :     }
     883                 :       29657 : }
     884                 :             : 
     885                 :             : 
     886                 :             : /**
     887                 :             :  * pair
     888                 :             :  */
     889                 :             : template<typename Stream, typename K, typename T>
     890                 :       36181 : void Serialize(Stream& os, const std::pair<K, T>& item)
     891                 :             : {
     892                 :       36181 :     Serialize(os, item.first);
     893                 :       36181 :     Serialize(os, item.second);
     894                 :       36181 : }
     895                 :             : 
     896                 :             : template<typename Stream, typename K, typename T>
     897                 :        1735 : void Unserialize(Stream& is, std::pair<K, T>& item)
     898                 :             : {
     899                 :        1735 :     Unserialize(is, item.first);
     900                 :        1735 :     Unserialize(is, item.second);
     901                 :        1731 : }
     902                 :             : 
     903                 :             : 
     904                 :             : 
     905                 :             : /**
     906                 :             :  * map
     907                 :             :  */
     908                 :             : template<typename Stream, typename K, typename T, typename Pred, typename A>
     909                 :         429 : void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
     910                 :             : {
     911                 :         429 :     WriteCompactSize(os, m.size());
     912         [ +  + ]:        1716 :     for (const auto& entry : m)
     913                 :        1287 :         Serialize(os, entry);
     914                 :         429 : }
     915                 :             : 
     916                 :             : template<typename Stream, typename K, typename T, typename Pred, typename A>
     917                 :           2 : void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
     918                 :             : {
     919                 :           2 :     m.clear();
     920                 :           2 :     unsigned int nSize = ReadCompactSize(is);
     921                 :           2 :     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
     922         [ +  + ]:           8 :     for (unsigned int i = 0; i < nSize; i++)
     923                 :             :     {
     924                 :           6 :         std::pair<K, T> item;
     925         [ +  - ]:           6 :         Unserialize(is, item);
     926         [ +  - ]:           6 :         mi = m.insert(mi, item);
     927                 :             :     }
     928                 :           2 : }
     929                 :             : 
     930                 :             : 
     931                 :             : 
     932                 :             : /**
     933                 :             :  * set
     934                 :             :  */
     935                 :             : template<typename Stream, typename K, typename Pred, typename A>
     936                 :           0 : void Serialize(Stream& os, const std::set<K, Pred, A>& m)
     937                 :             : {
     938                 :           0 :     WriteCompactSize(os, m.size());
     939         [ #  # ]:           0 :     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
     940                 :           0 :         Serialize(os, (*it));
     941                 :           0 : }
     942                 :             : 
     943                 :             : template<typename Stream, typename K, typename Pred, typename A>
     944                 :           0 : void Unserialize(Stream& is, std::set<K, Pred, A>& m)
     945                 :             : {
     946                 :           0 :     m.clear();
     947                 :           0 :     unsigned int nSize = ReadCompactSize(is);
     948                 :           0 :     typename std::set<K, Pred, A>::iterator it = m.begin();
     949         [ #  # ]:           0 :     for (unsigned int i = 0; i < nSize; i++)
     950                 :             :     {
     951                 :           0 :         K key;
     952                 :           0 :         Unserialize(is, key);
     953                 :           0 :         it = m.insert(it, key);
     954                 :             :     }
     955                 :           0 : }
     956                 :             : 
     957                 :             : 
     958                 :             : 
     959                 :             : /**
     960                 :             :  * unique_ptr
     961                 :             :  */
     962                 :             : template<typename Stream, typename T> void
     963                 :             : Serialize(Stream& os, const std::unique_ptr<const T>& p)
     964                 :             : {
     965                 :             :     Serialize(os, *p);
     966                 :             : }
     967                 :             : 
     968                 :             : template<typename Stream, typename T>
     969                 :             : void Unserialize(Stream& is, std::unique_ptr<const T>& p)
     970                 :             : {
     971                 :             :     p.reset(new T(deserialize, is));
     972                 :             : }
     973                 :             : 
     974                 :             : 
     975                 :             : 
     976                 :             : /**
     977                 :             :  * shared_ptr
     978                 :             :  */
     979                 :             : template<typename Stream, typename T> void
     980                 :       90228 : Serialize(Stream& os, const std::shared_ptr<const T>& p)
     981                 :             : {
     982                 :       90228 :     Serialize(os, *p);
     983                 :       90228 : }
     984                 :             : 
     985                 :             : template<typename Stream, typename T>
     986                 :        2787 : void Unserialize(Stream& is, std::shared_ptr<const T>& p)
     987                 :             : {
     988         [ -  + ]:        2787 :     p = std::make_shared<const T>(deserialize, is);
     989                 :        2787 : }
     990                 :             : 
     991                 :             : /**
     992                 :             :  * Support for (un)serializing many things at once
     993                 :             :  */
     994                 :             : 
     995                 :             : template <typename Stream, typename... Args>
     996                 :    58905829 : void SerializeMany(Stream& s, const Args&... args)
     997                 :             : {
     998                 :    58905829 :     (::Serialize(s, args), ...);
     999                 :    58905829 : }
    1000                 :             : 
    1001                 :             : template <typename Stream, typename... Args>
    1002                 :      150430 : inline void UnserializeMany(Stream& s, Args&&... args)
    1003                 :             : {
    1004                 :      118432 :     (::Unserialize(s, args), ...);
    1005                 :       21007 : }
    1006                 :             : 
    1007                 :             : /**
    1008                 :             :  * Support for all macros providing or using the ser_action parameter of the SerializationOps method.
    1009                 :             :  */
    1010                 :             : struct ActionSerialize {
    1011                 :             :     static constexpr bool ForRead() { return false; }
    1012                 :             : 
    1013                 :             :     template<typename Stream, typename... Args>
    1014                 :    58905685 :     static void SerReadWriteMany(Stream& s, const Args&... args)
    1015                 :             :     {
    1016 [ +  - ][ +  -  :    58903017 :         ::SerializeMany(s, args...);
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
    1017                 :       34181 :     }
    1018                 :             : 
    1019                 :             :     template<typename Stream, typename Type, typename Fn>
    1020                 :             :     static void SerRead(Stream& s, Type&&, Fn&&)
    1021                 :             :     {
    1022                 :             :     }
    1023                 :             : 
    1024                 :             :     template<typename Stream, typename Type, typename Fn>
    1025                 :       13614 :     static void SerWrite(Stream& s, Type&& obj, Fn&& fn)
    1026                 :             :     {
    1027         [ +  - ]:       13614 :         fn(s, std::forward<Type>(obj));
    1028                 :       13596 :     }
    1029                 :             : };
    1030                 :             : struct ActionUnserialize {
    1031                 :             :     static constexpr bool ForRead() { return true; }
    1032                 :             : 
    1033                 :             :     template<typename Stream, typename... Args>
    1034 [ +  - ][ +  -  :      126827 :     static void SerReadWriteMany(Stream& s, Args&&... args)
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
    1035                 :             :     {
    1036   [ +  +  +  + ]:      104305 :         ::UnserializeMany(s, args...);
         [ +  - ][ +  +  
          +  +  -  -  -  
          -  -  -  -  -  
          -  -  -  -  #  
          #  #  #  #  #  
             #  #  #  # ]
           [ +  -  +  -  
          +  -  +  -  +  
          -  +  +  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
    1037                 :       11163 :     }
    1038                 :             : 
    1039                 :             :     template<typename Stream, typename Type, typename Fn>
    1040         [ +  + ]:         207 :     static void SerRead(Stream& s, Type&& obj, Fn&& fn)
    1041                 :             :     {
    1042         [ +  - ]:         373 :         fn(s, std::forward<Type>(obj));
    1043                 :         205 :     }
    1044                 :             : 
    1045                 :             :     template<typename Stream, typename Type, typename Fn>
    1046                 :             :     static void SerWrite(Stream& s, Type&&, Fn&&)
    1047                 :             :     {
    1048                 :             :     }
    1049                 :             : };
    1050                 :             : 
    1051                 :             : /* ::GetSerializeSize implementations
    1052                 :             :  *
    1053                 :             :  * Computing the serialized size of objects is done through a special stream
    1054                 :             :  * object of type SizeComputer, which only records the number of bytes written
    1055                 :             :  * to it.
    1056                 :             :  *
    1057                 :             :  * If your Serialize or SerializationOp method has non-trivial overhead for
    1058                 :             :  * serialization, it may be worthwhile to implement a specialized version for
    1059                 :             :  * SizeComputer, which uses the s.seek() method to record bytes that would
    1060                 :             :  * be written instead.
    1061                 :             :  */
    1062                 :             : class SizeComputer
    1063                 :             : {
    1064                 :             : protected:
    1065                 :             :     size_t nSize{0};
    1066                 :             : 
    1067                 :             : public:
    1068                 :      371863 :     SizeComputer() = default;
    1069                 :             : 
    1070                 :     4761086 :     void write(std::span<const std::byte> src)
    1071                 :             :     {
    1072                 :     4760978 :         this->nSize += src.size();
    1073                 :        4960 :     }
    1074                 :             : 
    1075                 :             :     /** Pretend _nSize bytes are written, without specifying them. */
    1076                 :       18005 :     void seek(size_t _nSize)
    1077                 :             :     {
    1078                 :       18005 :         this->nSize += _nSize;
    1079                 :             :     }
    1080                 :             : 
    1081                 :             :     template<typename T>
    1082                 :      372021 :     SizeComputer& operator<<(const T& obj)
    1083                 :             :     {
    1084                 :      364684 :         ::Serialize(*this, obj);
    1085                 :             :         return (*this);
    1086                 :             :     }
    1087                 :             : 
    1088                 :      371880 :     size_t size() const {
    1089                 :      371880 :         return nSize;
    1090                 :             :     }
    1091                 :             : };
    1092                 :             : 
    1093                 :             : template<typename I>
    1094                 :             : inline void WriteVarInt(SizeComputer &s, I n)
    1095                 :             : {
    1096                 :             :     s.seek(GetSizeOfVarInt<I>(n));
    1097                 :             : }
    1098                 :             : 
    1099                 :       17391 : inline void WriteCompactSize(SizeComputer &s, uint64_t nSize)
    1100                 :             : {
    1101   [ +  +  +  +  :       18083 :     s.seek(GetSizeOfCompactSize(nSize));
           -  + ][ -  +  
          +  +  #  #  #  
           #  #  # ][ -  
          +  +  +  -  -  
             -  -  -  - ]
    1102                 :             : }
    1103                 :             : 
    1104                 :             : template <typename T>
    1105                 :      371863 : size_t GetSerializeSize(const T& t)
    1106                 :             : {
    1107                 :      371863 :     return (SizeComputer() << t).size();
    1108                 :             : }
    1109                 :             : 
    1110                 :             : //! Check if type contains a stream by seeing if has a GetStream() method.
    1111                 :             : template<typename T>
    1112                 :             : concept ContainsStream = requires(T t) { t.GetStream(); };
    1113                 :             : 
    1114                 :             : /** Wrapper that overrides the GetParams() function of a stream. */
    1115                 :             : template <typename SubStream, typename Params>
    1116                 :           1 : class ParamsStream
    1117                 :             : {
    1118                 :             :     const Params& m_params;
    1119                 :             :     // If ParamsStream constructor is passed an lvalue argument, Substream will
    1120                 :             :     // be a reference type, and m_substream will reference that argument.
    1121                 :             :     // Otherwise m_substream will be a substream instance and move from the
    1122                 :             :     // argument. Letting ParamsStream contain a substream instance instead of
    1123                 :             :     // just a reference is useful to make the ParamsStream object self contained
    1124                 :             :     // and let it do cleanup when destroyed, for example by closing files if
    1125                 :             :     // SubStream is a file stream.
    1126                 :             :     SubStream m_substream;
    1127                 :             : 
    1128                 :             : public:
    1129   [ +  -  +  -  :     1544991 :     ParamsStream(SubStream&& substream, const Params& params LIFETIMEBOUND) : m_params{params}, m_substream{std::forward<SubStream>(substream)} {}
          -  -  -  -  +  
                -  -  - ]
    1130                 :             : 
    1131                 :             :     template <typename NestedSubstream, typename Params1, typename Params2, typename... NestedParams>
    1132                 :           3 :     ParamsStream(NestedSubstream&& s, const Params1& params1 LIFETIMEBOUND, const Params2& params2 LIFETIMEBOUND, const NestedParams&... params LIFETIMEBOUND)
    1133         [ +  - ]:           3 :         : ParamsStream{::ParamsStream{std::forward<NestedSubstream>(s), params2, params...}, params1} {}
    1134                 :             : 
    1135   [ +  -  +  - ]:     5942907 :     template <typename U> ParamsStream& operator<<(const U& obj) { ::Serialize(*this, obj); return *this; }
           [ +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  +  
             -  +  -  +  
           - ][ +  -  +  
          -  -  -  -  -  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
           # ][ +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
                      - ]
    1136   [ +  -  -  -  :       22736 :     template <typename U> ParamsStream& operator>>(U&& obj) { ::Unserialize(*this, obj); return *this; }
          -  -  +  -  +  
           -  +  - ][ +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  -  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          +  +  -  +  -  
          +  -  +  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
             -  -  -  - ]
           [ #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
    1137                 :    27386464 :     void write(std::span<const std::byte> src) { GetStream().write(src); }
    1138                 :       81589 :     void read(std::span<std::byte> dst) { GetStream().read(dst); }
    1139                 :           3 :     void ignore(size_t num) { GetStream().ignore(num); }
    1140                 :           0 :     bool eof() const { return GetStream().eof(); }
    1141                 :             :     size_t size() const { return GetStream().size(); }
    1142                 :             : 
    1143                 :             :     //! Get reference to stream parameters.
    1144                 :             :     template <typename P>
    1145                 :     1555095 :     const auto& GetParams() const
    1146                 :             :     {
    1147                 :             :         if constexpr (std::is_convertible_v<Params, P>) {
    1148 [ +  + ][ -  -  :     1555093 :             return m_params;
          +  +  +  +  +  
          +  +  -  +  -  
             +  -  +  - ]
           [ +  +  +  +  
          +  +  #  #  #  
           # ][ +  +  -  
          +  +  +  +  +  
           -  - ][ #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
           [ +  +  -  -  
          -  -  -  -  -  
          -  -  -  +  -  
          -  -  -  -  -  
          -  -  -  -  -  
          +  +  -  -  -  
          -  -  -  -  -  
           -  - ][ -  +  
          -  -  -  +  -  
          -  -  -  -  -  
          -  +  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
    1149                 :             :         } else {
    1150                 :           2 :             return m_substream.template GetParams<P>();
    1151                 :             :         }
    1152                 :             :     }
    1153                 :             : 
    1154                 :             :     //! Get reference to underlying stream.
    1155                 :    16145160 :     auto& GetStream()
    1156                 :             :     {
    1157                 :             :         if constexpr (ContainsStream<SubStream>) {
    1158   [ +  -  +  -  :         173 :             return m_substream.GetStream();
                   +  - ]
    1159                 :             :         } else {
    1160                 :    12246616 :             return m_substream;
    1161                 :             :         }
    1162                 :             :     }
    1163                 :             :     const auto& GetStream() const
    1164                 :             :     {
    1165                 :             :         if constexpr (ContainsStream<SubStream>) {
    1166                 :             :             return m_substream.GetStream();
    1167                 :             :         } else {
    1168         [ #  # ]:           0 :             return m_substream;
    1169                 :             :         }
    1170                 :             :     }
    1171                 :             : };
    1172                 :             : 
    1173                 :             : /**
    1174                 :             :  * Explicit template deduction guide is required for single-parameter
    1175                 :             :  * constructor so Substream&& is treated as a forwarding reference, and
    1176                 :             :  * SubStream is deduced as reference type for lvalue arguments.
    1177                 :             :  */
    1178                 :             : template <typename Substream, typename Params>
    1179                 :             : ParamsStream(Substream&&, const Params&) -> ParamsStream<Substream, Params>;
    1180                 :             : 
    1181                 :             : /**
    1182                 :             :  * Template deduction guide for multiple params arguments that creates a nested
    1183                 :             :  * ParamsStream.
    1184                 :             :  */
    1185                 :             : template <typename Substream, typename Params1, typename Params2, typename... Params>
    1186                 :             : ParamsStream(Substream&& s, const Params1& params1, const Params2& params2, const Params&... params) ->
    1187                 :             :     ParamsStream<decltype(ParamsStream{std::forward<Substream>(s), params2, params...}), Params1>;
    1188                 :             : 
    1189                 :             : /** Wrapper that serializes objects with the specified parameters. */
    1190                 :             : template <typename Params, typename T>
    1191                 :             : class ParamsWrapper
    1192                 :             : {
    1193                 :             :     const Params& m_params;
    1194                 :             :     T& m_object;
    1195                 :             : 
    1196                 :             : public:
    1197   [ +  -  +  - ]:     1442692 :     explicit ParamsWrapper(const Params& params, T& obj) : m_params{params}, m_object{obj} {}
         [ +  - ][ +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
           [ +  -  +  -  
          +  -  -  +  -  
          +  -  +  +  -  
          +  -  -  +  +  
          -  +  -  +  -  
          +  -  -  +  +  
          -  -  +  +  -  
          +  -  -  +  -  
          +  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
           - ][ +  -  +  
             -  +  -  +  
           - ][ +  -  +  
          -  +  -  +  -  
          +  -  +  -  #  
          #  #  #  #  #  
          #  #  #  #  #  
           #  #  # ][ +  
             -  +  +  +  
           + ][ -  -  -  
          -  +  -  +  -  
          -  -  -  -  -  
          -  -  -  -  -  
          -  -  -  -  -  
             -  -  -  +  
                      - ]
    1198                 :             : 
    1199                 :             :     template <typename Stream>
    1200                 :     1542138 :     void Serialize(Stream& s) const
    1201                 :             :     {
    1202                 :     1542138 :         ParamsStream ss{s, m_params};
    1203                 :     1542138 :         ::Serialize(ss, m_object);
    1204                 :             :     }
    1205                 :             :     template <typename Stream>
    1206                 :        2838 :     void Unserialize(Stream& s)
    1207                 :             :     {
    1208                 :        2838 :         ParamsStream ss{s, m_params};
    1209                 :        2838 :         ::Unserialize(ss, m_object);
    1210                 :             :     }
    1211                 :             : };
    1212                 :             : 
    1213                 :             : /**
    1214                 :             :  * Helper macro for SerParams structs
    1215                 :             :  *
    1216                 :             :  * Allows you define SerParams instances and then apply them directly
    1217                 :             :  * to an object via function call syntax, eg:
    1218                 :             :  *
    1219                 :             :  *   constexpr SerParams FOO{....};
    1220                 :             :  *   ss << FOO(obj);
    1221                 :             :  */
    1222                 :             : #define SER_PARAMS_OPFUNC                                                                \
    1223                 :             :     /**                                                                                  \
    1224                 :             :      * Return a wrapper around t that (de)serializes it with specified parameter params. \
    1225                 :             :      *                                                                                   \
    1226                 :             :      * See SER_PARAMS for more information on serialization parameters.                  \
    1227                 :             :      */                                                                                  \
    1228                 :             :     template <typename T>                                                                \
    1229                 :             :     auto operator()(T&& t) const                                                         \
    1230                 :             :     {                                                                                    \
    1231                 :             :         return ParamsWrapper{*this, t};                                                  \
    1232                 :             :     }
    1233                 :             : 
    1234                 :             : #endif // BITCOIN_SERIALIZE_H
        

Generated by: LCOV version 2.0-1