message.go 1.73 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
package message

import (
	"errors"

	netmsg "github.com/jbenet/go-ipfs/net/message"

	blocks "github.com/jbenet/go-ipfs/blocks"
	nm "github.com/jbenet/go-ipfs/net/message"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

type BitSwapMessage interface {
	Wantlist() []u.Key
	Blocks() []blocks.Block
	AppendWanted(k u.Key)
	AppendBlock(b blocks.Block)
	Exportable
}

type Exportable interface {
	ToProto() *PBMessage
	ToNet(p *peer.Peer) (nm.NetMessage, error)
}

// message wraps a proto message for convenience
type message struct {
29 30
	wantlist []u.Key
	blocks   []blocks.Block
31 32 33 34 35 36
}

func New() *message {
	return new(message)
}

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
func newMessageFromProto(pbm PBMessage) (BitSwapMessage, error) {
	m := New()
	for _, s := range pbm.GetWantlist() {
		m.AppendWanted(u.Key(s))
	}
	for _, d := range pbm.GetBlocks() {
		b, err := blocks.NewBlock(d)
		if err != nil {
			return nil, err
		}
		m.AppendBlock(*b)
	}
	return m, nil
}

52 53
// TODO(brian): convert these into keys
func (m *message) Wantlist() []u.Key {
54
	return m.wantlist
55 56 57 58
}

// TODO(brian): convert these into blocks
func (m *message) Blocks() []blocks.Block {
59
	return m.blocks
60 61 62
}

func (m *message) AppendWanted(k u.Key) {
63
	m.wantlist = append(m.wantlist, k)
64 65 66
}

func (m *message) AppendBlock(b blocks.Block) {
67
	m.blocks = append(m.blocks, b)
68 69 70 71 72 73 74
}

func FromNet(nmsg netmsg.NetMessage) (BitSwapMessage, error) {
	return nil, errors.New("TODO implement")
}

func (m *message) ToProto() *PBMessage {
75 76 77 78 79 80 81 82
	pb := new(PBMessage)
	for _, k := range m.Wantlist() {
		pb.Wantlist = append(pb.Wantlist, string(k))
	}
	for _, b := range m.Blocks() {
		pb.Blocks = append(pb.Blocks, b.Data)
	}
	return pb
83 84 85 86 87
}

func (m *message) ToNet(p *peer.Peer) (nm.NetMessage, error) {
	return nm.FromObject(p, m.ToProto())
}