From b9b089108ad65263fd2cfcc8d11e20cd04ce0bcc Mon Sep 17 00:00:00 2001 From: Sjors Provoost Date: Fri, 21 Jun 2024 11:56:22 +0200 Subject: [PATCH] Convert between Sv2NetMsg and CSerializedNetMsg This allows us to subclass Transport. --- src/common/sv2_messages.h | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/common/sv2_messages.h b/src/common/sv2_messages.h index 4581eba38a463..d2709b7f297ae 100644 --- a/src/common/sv2_messages.h +++ b/src/common/sv2_messages.h @@ -5,9 +5,12 @@ #ifndef BITCOIN_COMMON_SV2_MESSAGES_H #define BITCOIN_COMMON_SV2_MESSAGES_H +#include // for CSerializedNetMsg and CNetMessage #include #include #include +#include + namespace node { /** * A type used as the message length field in stratum v2 messages. @@ -124,6 +127,40 @@ class Sv2NetMsg explicit Sv2NetMsg(const Sv2MsgType msg_type, const std::vector&& msg) : m_msg_type{msg_type}, m_msg{msg} {}; + // Unwrap CSerializedNetMsg + Sv2NetMsg(CSerializedNetMsg&& net_msg) + { + Assume(net_msg.m_type == ""); + DataStream ss(MakeByteSpan(net_msg.data)); + Unserialize(ss); + }; + + // Unwrap CNetMsg + Sv2NetMsg(CNetMessage net_msg) + { + Unserialize(net_msg.m_recv); + }; + + operator CSerializedNetMsg() + { + CSerializedNetMsg net_msg; + net_msg.m_type = ""; + DataStream ser; + Serialize(ser); + net_msg.data.resize(ser.size()); + std::transform(ser.begin(), ser.end(), net_msg.data.begin(), + [](std::byte b) { return static_cast(b); }); + return net_msg; + } + + operator CNetMessage() + { + DataStream msg; + Serialize(msg); + CNetMessage ret{std::move(msg)}; + return ret; + } + /** * Serializes the message M and sets an Sv2 network header. * @throws std::ios_base or std::out_of_range errors. @@ -154,6 +191,7 @@ class Sv2NetMsg uint8_t msg_type; s >> msg_type; m_msg_type = static_cast(msg_type); + m_msg.resize(s.size()); s.read(MakeWritableByteSpan(m_msg)); }