diff --git a/src/hash.h b/src/hash.h --- a/src/hash.h +++ b/src/hash.h @@ -6,6 +6,7 @@ #ifndef BITCOIN_HASH_H #define BITCOIN_HASH_H +#include #include #include #include @@ -98,7 +99,7 @@ /** A writer stream (for serialization) that computes a 256-bit hash. */ class CHashWriter { private: - CHash256 ctx; + CSHA256 ctx; const int nType; const int nVersion; @@ -111,13 +112,31 @@ int GetVersion() const { return nVersion; } void write(const char *pch, size_t size) { - ctx.Write({(const uint8_t *)pch, size}); + ctx.Write((const uint8_t *)pch, size); } - // invalidates the object + /** + * Compute the double-SHA256 hash of all data written to this object. + * + * Invalidates this object. + */ uint256 GetHash() { uint256 result; - ctx.Finalize(result); + ctx.Finalize(result.begin()); + ctx.Reset() + .Write(result.begin(), CSHA256::OUTPUT_SIZE) + .Finalize(result.begin()); + return result; + } + + /** + * Compute the SHA256 hash of all data written to this object. + * + * Invalidates this object. + */ + uint256 GetSHA256() { + uint256 result; + ctx.Finalize(result.begin()); return result; } @@ -125,9 +144,8 @@ * Returns the first 64 bits from the resulting hash. */ inline uint64_t GetCheapHash() { - uint8_t result[CHash256::OUTPUT_SIZE]; - ctx.Finalize(result); - return ReadLE64(result); + uint256 result = GetHash(); + return ReadLE64(result.begin()); } template CHashWriter &operator<<(const T &obj) { diff --git a/src/test/hash_tests.cpp b/src/test/hash_tests.cpp --- a/src/test/hash_tests.cpp +++ b/src/test/hash_tests.cpp @@ -201,4 +201,24 @@ BOOST_CHECK(h1.GetHash() != checksum); } +BOOST_AUTO_TEST_CASE(sh256_tests) { + CHashWriter h0(SER_DISK, CLIENT_VERSION); + h0.write("abc", 3); + BOOST_CHECK_EQUAL( + h0.GetSHA256().GetHex(), + "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"); + + CHashWriter h1(SER_DISK, CLIENT_VERSION); + h1.write("", 0); + BOOST_CHECK_EQUAL( + h1.GetSHA256().GetHex(), + "55b852781b9995a44c939b64e441ae2724b96f99c8f4fb9a141cfc9842c4b0e3"); + + CHashWriter h2(SER_DISK, CLIENT_VERSION); + h2.write("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56); + BOOST_CHECK_EQUAL( + h2.GetSHA256().GetHex(), + "c106db19d4edecf66721ff6459e43ca339603e0c9326c0e5b83806d2616a8d24"); +} + BOOST_AUTO_TEST_SUITE_END()