From 8466467a35e2b5ce14693103fd37bfe0ae67c3ce Mon Sep 17 00:00:00 2001 From: Sean Bowe Date: Thu, 31 Mar 2016 14:23:56 -0600 Subject: [PATCH] Added SHA256Compress to Bitcoin's SHA256 implementation. --- src/Makefile.test.include | 3 ++- src/crypto/sha256.cpp | 10 +++++++++ src/crypto/sha256.h | 1 + src/test/sha256compress_tests.cpp | 35 +++++++++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/test/sha256compress_tests.cpp diff --git a/src/Makefile.test.include b/src/Makefile.test.include index 825e7130d..e87b2238a 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -76,7 +76,8 @@ BITCOIN_TESTS =\ test/transaction_tests.cpp \ test/uint256_tests.cpp \ test/univalue_tests.cpp \ - test/util_tests.cpp + test/util_tests.cpp \ + test/sha256compress_tests.cpp if ENABLE_WALLET BITCOIN_TESTS += \ diff --git a/src/crypto/sha256.cpp b/src/crypto/sha256.cpp index 5b9f00a0a..39583c26a 100644 --- a/src/crypto/sha256.cpp +++ b/src/crypto/sha256.cpp @@ -7,6 +7,7 @@ #include "crypto/common.h" #include +#include // Internal implementation code. namespace @@ -171,6 +172,15 @@ void CSHA256::Finalize(unsigned char hash[OUTPUT_SIZE]) WriteBE64(sizedesc, bytes << 3); Write(pad, 1 + ((119 - (bytes % 64)) % 64)); Write(sizedesc, 8); + FinalizeNoPadding(hash, false); +} + +void CSHA256::FinalizeNoPadding(unsigned char hash[OUTPUT_SIZE], bool enforce_compression) +{ + if (enforce_compression && bytes != 64) { + throw std::length_error("SHA256Compress should be invoked with a 512-bit block"); + } + WriteBE32(hash, s[0]); WriteBE32(hash + 4, s[1]); WriteBE32(hash + 8, s[2]); diff --git a/src/crypto/sha256.h b/src/crypto/sha256.h index 85cf33739..1c449b834 100644 --- a/src/crypto/sha256.h +++ b/src/crypto/sha256.h @@ -22,6 +22,7 @@ public: CSHA256(); CSHA256& Write(const unsigned char* data, size_t len); void Finalize(unsigned char hash[OUTPUT_SIZE]); + void FinalizeNoPadding(unsigned char hash[OUTPUT_SIZE], bool enforce_compression = true); CSHA256& Reset(); }; diff --git a/src/test/sha256compress_tests.cpp b/src/test/sha256compress_tests.cpp new file mode 100644 index 000000000..aec36f073 --- /dev/null +++ b/src/test/sha256compress_tests.cpp @@ -0,0 +1,35 @@ +#include "test/test_bitcoin.h" +#include "crypto/sha256.h" +#include "uint256.h" + +#include + +#include + +BOOST_FIXTURE_TEST_SUITE(sha256compress_tests, BasicTestingSetup) + +BOOST_AUTO_TEST_CASE(compression) +{ + { + unsigned char preimage[64] = {}; + CSHA256 hasher; + hasher.Write(&preimage[0], 64); + + uint256 digest; + + hasher.FinalizeNoPadding(digest.begin()); + + BOOST_CHECK_MESSAGE(digest == uint256S("d8a93718eaf9feba4362d2c091d4e58ccabe9f779957336269b4b917be9856da"), + digest.GetHex()); + } + + { + unsigned char preimage[63] = {}; + CSHA256 hasher; + hasher.Write(&preimage[0], 63); + uint256 digest; + BOOST_CHECK_THROW(hasher.FinalizeNoPadding(digest.begin()), std::length_error); + } +} + +BOOST_AUTO_TEST_SUITE_END()