From 132dc81f7d0076e32e9364466624abe90cb28cf5 Mon Sep 17 00:00:00 2001 From: Ariel Date: Wed, 17 Jan 2018 12:47:08 +0200 Subject: [PATCH] add blake2b writer --- src/hash.h | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/hash.h b/src/hash.h index 077155562..06fcced0a 100644 --- a/src/hash.h +++ b/src/hash.h @@ -12,6 +12,8 @@ #include "uint256.h" #include "version.h" +#include "sodium.h" + #include typedef uint256 ChainCode; @@ -150,6 +152,47 @@ public: } }; + +/** A writer stream (for serialization) that computes a 256-bit BLAKE2b hash. */ +class CBLAKE2bWriter +{ +private: + crypto_generichash_blake2b_state state; + +public: + int nType; + int nVersion; + + CBLAKE2bWriter(int nTypeIn, int nVersionIn, const unsigned char* personal) : nType(nTypeIn), nVersion(nVersionIn) { + assert(crypto_generichash_blake2b_init_salt_personal( + &state, + NULL, 0, // No key. + 32, + NULL, // No salt. + personal) == 0); + } + + CBLAKE2bWriter& write(const char *pch, size_t size) { + crypto_generichash_blake2b_update(&state, (const unsigned char*)pch, size); + return (*this); + } + + // invalidates the object + uint256 GetHash() { + uint256 result; + crypto_generichash_blake2b_final(&state, (unsigned char*)&result, 32); + return result; + } + + template + CBLAKE2bWriter& operator<<(const T& obj) { + // Serialize to this stream + ::Serialize(*this, obj, nType, nVersion); + return (*this); + } +}; + + /** Compute the 256-bit hash of an object's serialization. */ template uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)