File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 66#ifndef BITCOIN_HASH_H
77#define BITCOIN_HASH_H
88
9+ #include < attributes.h>
910#include < crypto/common.h>
1011#include < crypto/ripemd160.h>
1112#include < crypto/sha256.h>
@@ -199,6 +200,30 @@ class CHashVerifier : public CHashWriter
199200 }
200201};
201202
203+ /* * Writes data to an underlying source stream, while hashing the written data. */
204+ template <typename Source>
205+ class HashedSourceWriter : public CHashWriter
206+ {
207+ private:
208+ Source& m_source;
209+
210+ public:
211+ explicit HashedSourceWriter (Source& source LIFETIMEBOUND) : CHashWriter{source.GetType (), source.GetVersion ()}, m_source{source} {}
212+
213+ void write (Span<const std::byte> src)
214+ {
215+ m_source.write (src);
216+ CHashWriter::write (src);
217+ }
218+
219+ template <typename T>
220+ HashedSourceWriter& operator <<(const T& obj)
221+ {
222+ ::Serialize (*this , obj);
223+ return *this ;
224+ }
225+ };
226+
202227/* * Compute the 256-bit hash of an object's serialization. */
203228template <typename T>
204229uint256 SerializeHash (const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Original file line number Diff line number Diff line change @@ -500,4 +500,18 @@ BOOST_AUTO_TEST_CASE(streams_buffered_file_rand)
500500 fs::remove (streams_test_filename);
501501}
502502
503+ BOOST_AUTO_TEST_CASE (streams_hashed)
504+ {
505+ CDataStream stream (SER_NETWORK, INIT_PROTO_VERSION);
506+ HashedSourceWriter hash_writer{stream};
507+ const std::string data{" bitcoin" };
508+ hash_writer << data;
509+
510+ CHashVerifier hash_verifier{&stream};
511+ std::string result;
512+ hash_verifier >> result;
513+ BOOST_CHECK_EQUAL (data, result);
514+ BOOST_CHECK_EQUAL (hash_writer.GetHash (), hash_verifier.GetHash ());
515+ }
516+
503517BOOST_AUTO_TEST_SUITE_END ()
You can’t perform that action at this time.
0 commit comments