libs5-go/protocol/signed/accounce_peers.go

102 lines
2.1 KiB
Go

package signed
import (
"git.lumeweb.com/LumeWeb/libs5-go/encoding"
"git.lumeweb.com/LumeWeb/libs5-go/interfaces"
"git.lumeweb.com/LumeWeb/libs5-go/net"
"git.lumeweb.com/LumeWeb/libs5-go/protocol/base"
"github.com/vmihailenco/msgpack/v5"
"net/url"
)
var (
_ base.IncomingMessageTyped = (*AnnouncePeers)(nil)
)
type AnnouncePeers struct {
connected bool
peer *encoding.NodeId
connectionUris []*url.URL
base.IncomingMessageTypedImpl
}
func NewAnnouncePeers() *AnnouncePeers {
return &AnnouncePeers{connected: false, peer: nil, connectionUris: nil}
}
func (a *AnnouncePeers) DecodeMessage(dec *msgpack.Decoder) error {
// Decode the number of peers.
numPeers, err := dec.DecodeInt()
if err != nil {
return err
}
// Initialize the slice for storing connection URIs.
var connectionURIs []*url.URL
// Loop through each peer.
for i := 0; i < numPeers; i++ {
// Decode peer ID.
peerIdBytes, err := dec.DecodeBytes()
if err != nil {
return err
}
peerId := encoding.NewNodeId(peerIdBytes)
// Skip decoding connection status as it is not used.
_, err = dec.DecodeBool() // Connection status, not used.
if err != nil {
return err
}
// Decode the number of connection URIs for this peer.
numUris, err := dec.DecodeInt()
if err != nil {
return err
}
// Decode each connection URI for this peer.
for j := 0; j < numUris; j++ {
uriStr, err := dec.DecodeString()
if err != nil {
return err
}
uri, err := url.Parse(uriStr)
if err != nil {
return err
}
pid, err := peerId.ToString()
if err != nil {
return err
}
passwd, empty := uri.User.Password()
if empty {
passwd = ""
}
// Incorporate the peer ID into the URI.
uri.User = url.UserPassword(pid, passwd)
connectionURIs = append(connectionURIs, uri)
}
}
a.connectionUris = connectionURIs
return nil
}
func (a AnnouncePeers) HandleMessage(node interfaces.Node, peer net.Peer, verifyId bool) error {
if len(a.connectionUris) > 0 {
err := node.Services().P2P().ConnectToNode([]*url.URL{a.connectionUris[0]}, false)
if err != nil {
return err
}
}
return nil
}