A writer stream (for serialization) that computes a 256-bit hash. */
| 98 | |
| 99 | /** A writer stream (for serialization) that computes a 256-bit hash. */ |
| 100 | class CHashWriter |
| 101 | { |
| 102 | private: |
| 103 | CSHA256 ctx; |
| 104 | |
| 105 | const int nType; |
| 106 | const int nVersion; |
| 107 | public: |
| 108 | |
| 109 | CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {} |
| 110 | |
| 111 | int GetType() const { return nType; } |
| 112 | int GetVersion() const { return nVersion; } |
| 113 | |
| 114 | void write(Span<const std::byte> src) |
| 115 | { |
| 116 | ctx.Write(UCharCast(src.data()), src.size()); |
| 117 | } |
| 118 | |
| 119 | /** Compute the double-SHA256 hash of all data written to this object. |
| 120 | * |
| 121 | * Invalidates this object. |
| 122 | */ |
| 123 | uint256 GetHash() { |
| 124 | uint256 result; |
| 125 | ctx.Finalize(result.begin()); |
| 126 | ctx.Reset().Write(result.begin(), CSHA256::OUTPUT_SIZE).Finalize(result.begin()); |
| 127 | return result; |
| 128 | } |
| 129 | |
| 130 | /** Compute the SHA256 hash of all data written to this object. |
| 131 | * |
| 132 | * Invalidates this object. |
| 133 | */ |
| 134 | uint256 GetSHA256() { |
| 135 | uint256 result; |
| 136 | ctx.Finalize(result.begin()); |
| 137 | return result; |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Returns the first 64 bits from the resulting hash. |
| 142 | */ |
| 143 | inline uint64_t GetCheapHash() { |
| 144 | uint256 result = GetHash(); |
| 145 | return ReadLE64(result.begin()); |
| 146 | } |
| 147 | |
| 148 | template<typename T> |
| 149 | CHashWriter& operator<<(const T& obj) { |
| 150 | // Serialize to this stream |
| 151 | ::Serialize(*this, obj); |
| 152 | return (*this); |
| 153 | } |
| 154 | }; |
| 155 | |
| 156 | /** Reads data from an underlying stream, while hashing the read data. */ |
| 157 | template<typename Source> |