From fe1dc62cef88280d2490a619beded052f313c6fc Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Sun, 30 Oct 2016 18:02:16 -0400 Subject: [PATCH] Hash P2P messages as they are received instead of at process-time --- src/main.cpp | 2 +- src/net.cpp | 9 +++++++++ src/net.h | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 5e17ec6251..56c24d93b8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6350,7 +6350,7 @@ bool ProcessMessages(CNode* pfrom, CConnman& connman) // Checksum CDataStream& vRecv = msg.vRecv; - uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); + const uint256& hash = msg.GetMessageHash(); if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) { LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__, diff --git a/src/net.cpp b/src/net.cpp index 48ba9588d9..a2414acf46 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -758,12 +758,21 @@ int CNetMessage::readData(const char *pch, unsigned int nBytes) vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } + hasher.Write((const unsigned char*)pch, nCopy); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } +const uint256& CNetMessage::GetMessageHash() const +{ + assert(complete()); + if (data_hash.IsNull()) + hasher.Finalize(data_hash.begin()); + return data_hash; +} + diff --git a/src/net.h b/src/net.h index 58b492e592..955bad488a 100644 --- a/src/net.h +++ b/src/net.h @@ -512,6 +512,9 @@ public: class CNetMessage { +private: + mutable CHash256 hasher; + mutable uint256 data_hash; public: bool in_data; // parsing header (false) or data (true) @@ -539,6 +542,8 @@ public: return (hdr.nMessageSize == nDataPos); } + const uint256& GetMessageHash() const; + void SetVersion(int nVersionIn) { hdrbuf.SetVersion(nVersionIn);