微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试编组和解组 libp2p AddrInfo

如何解决尝试编组和解组 libp2p AddrInfo

我正在使用 libp2p Go 库来制作 p2p 网络堆栈。

我需要向网络上的其他对等点单播消息。我想将 AddrInfo 结构存储在我单播的消息中,以便我可以发回响应。

以下是libp2p库代码

AddrInfo 结构包含

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如下

type Multiaddr interface {
    json.Marshaler
    json.Unmarshaler
    encoding.TextMarshaler
    encoding.TextUnmarshaler
    encoding.BinaryMarshaler
    encoding.BinaryUnmarshaler
}

这是我使用 libp2p 库的代码

我像这样将其包含在我的消息结构中

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
}

当我编组我的消息结构然后尝试解组时,我收到以下错误

panic: interface conversion: interface is nil,not encoding.BinaryUnmarshaler [recovered]
        panic: interface conversion: interface is nil,not encoding.BinaryUnmarshaler
UnmarshalMessage(0xc0001c7200,0x454,0x480,0x0,...)

我无法编辑 libp2p 源代码,但需要在我的结构中添加 AddrInfo。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。