Skip to content

Commit da6c7ae

Browse files
committed
hash: add HashedSourceWriter
This class is the counterpart to CHashVerifier, in that it writes data to an underlying source stream, while keeping a hash of the written data.
1 parent 3283403 commit da6c7ae

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/hash.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
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. */
203228
template<typename T>
204229
uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)

src/test/streams_tests.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
503517
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)