Message.go 1 KB
Newer Older
1 2
package dht

Jeromy's avatar
Jeromy committed
3 4 5 6
import (
	peer "github.com/jbenet/go-ipfs/peer"
)

7
// A helper struct to make working with protbuf types easier
8 9 10 11
type DHTMessage struct {
	Type     PBDHTMessage_MessageType
	Key      string
	Value    []byte
12
	Response bool
13 14
	Id       uint64
	Success  bool
Jeromy's avatar
Jeromy committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28
	Peers    []*peer.Peer
}

func peerInfo(p *peer.Peer) *PBDHTMessage_PBPeer {
	pbp := new(PBDHTMessage_PBPeer)
	addr, err := p.Addresses[0].String()
	if err != nil {
		//Temp: what situations could cause this?
		panic(err)
	}
	pbp.Addr = &addr
	pid := string(p.ID)
	pbp.Id = &pid
	return pbp
29 30
}

31 32
// TODO: building the protobuf message this way is a little wasteful
//		 Unused fields wont be omitted, find a better way to do this
33 34
func (m *DHTMessage) ToProtobuf() *PBDHTMessage {
	pmes := new(PBDHTMessage)
35 36 37 38 39 40 41 42
	if m.Value != nil {
		pmes.Value = m.Value
	}

	pmes.Type = &m.Type
	pmes.Key = &m.Key
	pmes.Response = &m.Response
	pmes.Id = &m.Id
43
	pmes.Success = &m.Success
Jeromy's avatar
Jeromy committed
44 45 46
	for _, p := range m.Peers {
		pmes.Peers = append(pmes.Peers, peerInfo(p))
	}
47 48 49

	return pmes
}