libs5-go/protocol/handshake_open.go

121 lines
2.2 KiB
Go
Raw Normal View History

2024-01-06 11:33:46 +00:00
package protocol
import (
"fmt"
"git.lumeweb.com/LumeWeb/libs5-go/protocol/signed"
2024-01-06 11:33:46 +00:00
"git.lumeweb.com/LumeWeb/libs5-go/types"
"github.com/vmihailenco/msgpack/v5"
)
2024-01-30 03:25:21 +00:00
var _ EncodeableMessage = (*HandshakeOpen)(nil)
var _ IncomingMessage = (*HandshakeOpen)(nil)
2024-01-07 12:59:14 +00:00
2024-01-06 11:33:46 +00:00
type HandshakeOpen struct {
challenge []byte
networkId string
handshake []byte
2024-01-30 03:25:21 +00:00
HandshakeRequirement
2024-01-06 11:33:46 +00:00
}
2024-01-08 12:14:25 +00:00
func (h *HandshakeOpen) SetHandshake(handshake []byte) {
h.handshake = handshake
}
func (h HandshakeOpen) Challenge() []byte {
return h.challenge
2024-01-06 11:33:46 +00:00
}
func (h HandshakeOpen) NetworkId() string {
return h.networkId
2024-01-06 11:33:46 +00:00
}
func NewHandshakeOpen(challenge []byte, networkId string) *HandshakeOpen {
ho := &HandshakeOpen{
2024-01-06 11:33:46 +00:00
challenge: challenge,
networkId: networkId,
}
ho.SetRequiresHandshake(false)
return ho
2024-01-06 11:33:46 +00:00
}
func (h HandshakeOpen) EncodeMsgpack(enc *msgpack.Encoder) error {
2024-01-06 11:33:46 +00:00
err := enc.EncodeUint(uint64(types.ProtocolMethodHandshakeOpen))
if err != nil {
return err
}
err = enc.EncodeBytes(h.challenge)
2024-01-06 11:33:46 +00:00
if err != nil {
return err
}
if h.networkId != "" {
err = enc.EncodeString(h.networkId)
if err != nil {
return err
}
2024-01-06 11:33:46 +00:00
}
return nil
}
2024-01-30 03:25:21 +00:00
func (h *HandshakeOpen) DecodeMessage(dec *msgpack.Decoder, message IncomingMessageData) error {
handshake, err := dec.DecodeBytes()
if err != nil {
return err
}
h.handshake = handshake
2024-01-07 15:54:26 +00:00
_, err = dec.PeekCode()
2024-01-07 15:54:26 +00:00
networkId := ""
if err != nil {
if err.Error() != "EOF" {
return err
}
h.networkId = networkId
return nil
}
networkId, err = dec.DecodeString()
if err != nil {
return err
}
h.networkId = networkId
return nil
}
2024-01-30 03:25:21 +00:00
func (h *HandshakeOpen) HandleMessage(message IncomingMessageData) error {
peer := message.Peer
services := message.Services
if h.networkId != services.P2P().NetworkId() {
return fmt.Errorf("Peer is in different network: %s", h.networkId)
}
handshake := signed.NewHandshakeDoneRequest(h.handshake, types.SupportedFeatures, services.P2P().SelfConnectionUris())
hsMessage, err := msgpack.Marshal(handshake)
if err != nil {
return err
}
secureMessage, err := services.P2P().SignMessageSimple(hsMessage)
if err != nil {
return err
}
err = peer.SendMessage(secureMessage)
if err != nil {
return err
}
2024-01-06 11:33:46 +00:00
return nil
}