feat: add DecodeMessage and HandleMessage to HandshakeOpen

This commit is contained in:
Derrick Hammer 2024-01-07 09:08:23 -05:00
parent 00c8a081f6
commit cc2885f2b4
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 54 additions and 9 deletions

View File

@ -2,11 +2,14 @@ package protocol
import (
"errors"
"fmt"
"git.lumeweb.com/LumeWeb/libs5-go/interfaces"
"git.lumeweb.com/LumeWeb/libs5-go/net"
"git.lumeweb.com/LumeWeb/libs5-go/protocol/base"
"git.lumeweb.com/LumeWeb/libs5-go/protocol/signed"
"git.lumeweb.com/LumeWeb/libs5-go/types"
"github.com/vmihailenco/msgpack/v5"
"net/url"
)
var _ base.IncomingMessageTyped = (*HandshakeOpen)(nil)
@ -14,16 +17,17 @@ var _ base.IncomingMessageTyped = (*HandshakeOpen)(nil)
type HandshakeOpen struct {
challenge []byte
networkId string
handshake []byte
base.IncomingMessageTypedImpl
base.IncomingMessageHandler
}
func (m HandshakeOpen) Challenge() []byte {
return m.challenge
func (h HandshakeOpen) Challenge() []byte {
return h.challenge
}
func (m HandshakeOpen) NetworkId() string {
return m.networkId
func (h HandshakeOpen) NetworkId() string {
return h.networkId
}
var _ base.EncodeableMessage = (*HandshakeOpen)(nil)
@ -37,19 +41,19 @@ func NewHandshakeOpen(challenge []byte, networkId string) *HandshakeOpen {
networkId: networkId,
}
}
func (m HandshakeOpen) EncodeMsgpack(enc *msgpack.Encoder) error {
func (h HandshakeOpen) EncodeMsgpack(enc *msgpack.Encoder) error {
err := enc.EncodeUint(uint64(types.ProtocolMethodHandshakeOpen))
if err != nil {
return err
}
err = enc.EncodeBytes(m.challenge)
err = enc.EncodeBytes(h.challenge)
if err != nil {
return err
}
if m.networkId != "" {
err = enc.EncodeString(m.networkId)
if h.networkId != "" {
err = enc.EncodeString(h.networkId)
if err != nil {
return err
}
@ -58,7 +62,48 @@ func (m HandshakeOpen) EncodeMsgpack(enc *msgpack.Encoder) error {
return nil
}
func (m *HandshakeOpen) HandleMessage(node interfaces.Node, peer net.Peer, verifyId bool) error {
func (h *HandshakeOpen) DecodeMessage(dec *msgpack.Decoder) error {
handshake, err := dec.DecodeBytes()
if err != nil {
return err
}
h.handshake = handshake
networkId, err := dec.DecodeString()
if err != nil {
return err
}
h.networkId = networkId
return nil
}
func (h *HandshakeOpen) HandleMessage(node interfaces.Node, peer net.Peer, verifyId bool) error {
if h.networkId != node.NetworkId() {
return fmt.Errorf("Peer is in different network: %s", h.networkId)
}
handshake := signed.NewHandshakeDoneRequest(h.handshake, types.SupportedFeatures, []*url.URL{})
message, err := msgpack.Marshal(handshake)
if err != nil {
return err
}
secureMessage, err := node.Services().P2P().SignMessageSimple(message)
if err != nil {
return err
}
err = peer.SendMessage(secureMessage)
if err != nil {
return err
}
return nil
}