Skip to content

Commit 6dfc4d2

Browse files
committed
Add blake2b writer.
1 parent d903ccb commit 6dfc4d2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/hash.h

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
#include <sstream>
2929
#include <vector>
3030

31+
#include <sodium.h>
32+
3133

3234
typedef uint256 ChainCode;
3335

@@ -311,6 +313,45 @@ class CHashWriter
311313
}
312314
};
313315

316+
/** A writer stream (for serialization) that computes a 256-bit BLAKE2b hash. */
317+
class CBLAKE2bWriter
318+
{
319+
private:
320+
crypto_generichash_blake2b_state state;
321+
322+
public:
323+
int nType;
324+
int nVersion;
325+
326+
CBLAKE2bWriter(int nTypeIn, int nVersionIn, const unsigned char* personal) : nType(nTypeIn), nVersion(nVersionIn) {
327+
assert(crypto_generichash_blake2b_init_salt_personal(
328+
&state,
329+
NULL, 0, // No key.
330+
32,
331+
NULL, // No salt.
332+
personal) == 0);
333+
}
334+
335+
CBLAKE2bWriter& write(const char *pch, size_t size) {
336+
crypto_generichash_blake2b_update(&state, (const unsigned char*)pch, size);
337+
return (*this);
338+
}
339+
340+
// invalidates the object
341+
uint256 GetHash() {
342+
uint256 result;
343+
crypto_generichash_blake2b_final(&state, (unsigned char*)&result, 32);
344+
return result;
345+
}
346+
347+
template<typename T>
348+
CBLAKE2bWriter& operator<<(const T& obj) {
349+
// Serialize to this stream
350+
::Serialize(*this, obj, nType, nVersion);
351+
return (*this);
352+
}
353+
};
354+
314355
/** Compute the 256-bit hash of an object's serialization. */
315356
template <typename T>
316357
uint256 SerializeHash(const T& obj, int nType = SER_GETHASH, int nVersion = PROTOCOL_VERSION)

0 commit comments

Comments
 (0)