I am using the libp2p Go library to make a p2p networking stack.
I need to unicast messages to other peers on my network. I want to store the AddrInfo struct on my message I unicast so I can send a response back.
The below is libp2p library code:
The AddrInfo struct contains
type ID string
// AddrInfo is a small struct used to pass around a peer with
// a set of addresses (and later, keys?).
type AddrInfo struct {
ID ID
Addrs []ma.Multiaddr
}
Multiaddr is as follows
type Multiaddr interface {
json.Marshaler
json.Unmarshaler
encoding.TextMarshaler
encoding.TextUnmarshaler
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
}
This is my code using the libp2p library:
I include this in my message struct like so
func init() {
gob.Register(&Message{})
}
// Message stores a type of message and a body.
// The message is the data that gets passed between nodes when they communicate.
type Message struct {
ID string `json:"id"`
Body []byte `json:"body"` // the actual payload.
OriginNode peer.AddrInfo `json:"origin_node"` // the node that sent the message
}
// NewMessage builds up a new message.
func NewMessage(b []byte, o peer.AddrInfo) Message {
return Message{
ID: uuid.New().String(),
Body: b,
OriginNode: o,
}
}
// Marshal takes a node message and marshals it into an array of bytes.
func (m Message) Marshal() []byte {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(m); err != nil {
zap.S().Fatal(err)
}
return buf.Bytes()
}
// UnmarshalMessage takes a slice of bytes and a returns a message struct.
func UnmarshalMessage(input []byte) (Message, error) {
msg := Message{}
buf := bytes.NewBuffer(input)
dec := gob.NewDecoder(buf)
if err := dec.Decode(&msg); err != nil {
return Message{}, err
}
return msg, nil
}
When I marshal my message struct and then attempt to unmarshal I receive the following error:
panic: interface conversion: interface is nil, not encoding.BinaryUnmarshaler [recovered] panic: interface conversion: interface is nil, not encoding.BinaryUnmarshaler UnmarshalMessage(0xc0001c7200, 0x454, 0x480, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
I can't edit the libp2p source code but need the AddrInfo within my struct.