hash.h raw

   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_HASH_H
   7  #define BITCOIN_HASH_H
   8  
   9  #include <attributes.h>
  10  #include <crypto/common.h>
  11  #include <crypto/ripemd160.h>
  12  #include <crypto/sha256.h>
  13  #include <prevector.h>
  14  #include <serialize.h>
  15  #include <span.h>
  16  #include <support/cleanse.h>
  17  #include <uint256.h>
  18  
  19  #include <string>
  20  #include <vector>
  21  
  22  /** A BIP32 chain code. Cleansed on destruction. */
  23  class ChainCode : public base_blob<256> {
  24  public:
  25      constexpr ChainCode() = default;
  26      constexpr explicit ChainCode(std::span<const unsigned char> vch) : base_blob<256>(vch) {}
  27      constexpr explicit ChainCode(const base_blob<256>& b) : base_blob<256>(b) {}
  28      ~ChainCode() { memory_cleanse(data(), size()); }
  29  };
  30  
  31  /** A hasher class for Bitcoin's 256-bit hash (double SHA-256). */
  32  class CHash256 {
  33  private:
  34      CSHA256 sha;
  35  public:
  36      static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE;
  37  
  38      void Finalize(std::span<unsigned char> output) {
  39          assert(output.size() == OUTPUT_SIZE);
  40          unsigned char buf[CSHA256::OUTPUT_SIZE];
  41          sha.Finalize(buf);
  42          sha.Reset().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(output.data());
  43      }
  44  
  45      CHash256& Write(std::span<const unsigned char> input) {
  46          sha.Write(input.data(), input.size());
  47          return *this;
  48      }
  49  
  50      CHash256& Reset() {
  51          sha.Reset();
  52          return *this;
  53      }
  54  };
  55  
  56  /** A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160). */
  57  class CHash160 {
  58  private:
  59      CSHA256 sha;
  60  public:
  61      static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE;
  62  
  63      void Finalize(std::span<unsigned char> output) {
  64          assert(output.size() == OUTPUT_SIZE);
  65          unsigned char buf[CSHA256::OUTPUT_SIZE];
  66          sha.Finalize(buf);
  67          CRIPEMD160().Write(buf, CSHA256::OUTPUT_SIZE).Finalize(output.data());
  68      }
  69  
  70      CHash160& Write(std::span<const unsigned char> input) {
  71          sha.Write(input.data(), input.size());
  72          return *this;
  73      }
  74  
  75      CHash160& Reset() {
  76          sha.Reset();
  77          return *this;
  78      }
  79  };
  80  
  81  /** Compute the 256-bit hash of an object. */
  82  template<typename T>
  83  inline uint256 Hash(const T& in1)
  84  {
  85      uint256 result;
  86      CHash256().Write(MakeUCharSpan(in1)).Finalize(result);
  87      return result;
  88  }
  89  
  90  /** Compute the 256-bit hash of the concatenation of two objects. */
  91  template<typename T1, typename T2>
  92  inline uint256 Hash(const T1& in1, const T2& in2) {
  93      uint256 result;
  94      CHash256().Write(MakeUCharSpan(in1)).Write(MakeUCharSpan(in2)).Finalize(result);
  95      return result;
  96  }
  97  
  98  /** Compute the 160-bit hash an object. */
  99  template<typename T1>
 100  inline uint160 Hash160(const T1& in1)
 101  {
 102      uint160 result;
 103      CHash160().Write(MakeUCharSpan(in1)).Finalize(result);
 104      return result;
 105  }
 106  
 107  /** A writer stream (for serialization) that computes a 256-bit hash. */
 108  class HashWriter
 109  {
 110  private:
 111      CSHA256 ctx;
 112  
 113  public:
 114      void write(std::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      HashWriter& operator<<(const T& obj)
 150      {
 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>
 158  class HashVerifier : public HashWriter
 159  {
 160  private:
 161      Source& m_source;
 162  
 163  public:
 164      explicit HashVerifier(Source& source LIFETIMEBOUND) : m_source{source} {}
 165  
 166      void read(std::span<std::byte> dst)
 167      {
 168          m_source.read(dst);
 169          this->write(dst);
 170      }
 171  
 172      void ignore(size_t num_bytes)
 173      {
 174          std::byte data[1024];
 175          while (num_bytes > 0) {
 176              size_t now = std::min<size_t>(num_bytes, 1024);
 177              read({data, now});
 178              num_bytes -= now;
 179          }
 180      }
 181  
 182      template <typename T>
 183      HashVerifier<Source>& operator>>(T&& obj)
 184      {
 185          ::Unserialize(*this, obj);
 186          return *this;
 187      }
 188  };
 189  
 190  /** Writes data to an underlying source stream, while hashing the written data. */
 191  template <typename Source>
 192  class HashedSourceWriter : public HashWriter
 193  {
 194  private:
 195      Source& m_source;
 196  
 197  public:
 198      explicit HashedSourceWriter(Source& source LIFETIMEBOUND) : HashWriter{}, m_source{source} {}
 199  
 200      void write(std::span<const std::byte> src)
 201      {
 202          m_source.write(src);
 203          HashWriter::write(src);
 204      }
 205  
 206      template <typename T>
 207      HashedSourceWriter& operator<<(const T& obj)
 208      {
 209          ::Serialize(*this, obj);
 210          return *this;
 211      }
 212  };
 213  
 214  /** Single-SHA256 a 32-byte input (represented as uint256). */
 215  [[nodiscard]] uint256 SHA256Uint256(const uint256& input);
 216  
 217  unsigned int MurmurHash3(unsigned int nHashSeed, std::span<const unsigned char> vDataToHash);
 218  
 219  void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]);
 220  
 221  /** Return a HashWriter primed for tagged hashes (as specified in BIP 340).
 222   *
 223   * The returned object will have SHA256(tag) written to it twice (= 64 bytes).
 224   * A tagged hash can be computed by feeding the message into this object, and
 225   * then calling HashWriter::GetSHA256().
 226   */
 227  HashWriter TaggedHash(const std::string& tag);
 228  
 229  /** Compute the 160-bit RIPEMD-160 hash of an array. */
 230  inline uint160 RIPEMD160(std::span<const unsigned char> data)
 231  {
 232      uint160 result;
 233      CRIPEMD160().Write(data.data(), data.size()).Finalize(result.begin());
 234      return result;
 235  }
 236  
 237  #endif // BITCOIN_HASH_H
 238