protocol.go 1.47 KB
Newer Older
Aviv Eyal's avatar
Aviv Eyal committed
1
2
3
4
package main

import (
	"bufio"
Aviv Eyal's avatar
Aviv Eyal committed
5
	p2p "github.com/avive/go-libp2p/examples/multipro/pb"
Aviv Eyal's avatar
Aviv Eyal committed
6
	"github.com/gogo/protobuf/proto"
Aviv Eyal's avatar
Aviv Eyal committed
7
	protobufCodec "github.com/multiformats/go-multicodec/protobuf"
Aviv Eyal's avatar
Aviv Eyal committed
8
	"gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
Aviv Eyal's avatar
Aviv Eyal committed
9
10
11
12
13
14
15
16
17
18
19
	inet "gx/ipfs/QmbD5yKbXahNvoMqzeuNyKQA9vAs9fUvJg2GXeWU1fVqY5/go-libp2p-net"
	"log"
	"time"
)

// node version
const clientVersion = "go-p2p-node/0.0.1"

// helper method - writes a protobuf go data object to a network stream
// data - reference of protobuf go data object to send (not the object itself)
// s - network stream to write the data to
Aviv Eyal's avatar
Aviv Eyal committed
20
func sendProtoMessage(data proto.Message, s inet.Stream) bool {
Aviv Eyal's avatar
Aviv Eyal committed
21
22
23
24
	writer := bufio.NewWriter(s)
	enc := protobufCodec.Multicodec(nil).Encoder(writer)
	err := enc.Encode(data)
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
25
		log.Println(err)
Aviv Eyal's avatar
Aviv Eyal committed
26
27
28
29
30
31
32
33
		return false
	}
	writer.Flush()
	return true
}

// helper method - generate message data shared between all node's p2p protocols
// messageId - unique for requests, copied from request for responses
Aviv Eyal's avatar
Aviv Eyal committed
34
35
func NewMessageData(node *Node, messageId string, gossip bool) *p2p.MessageData {

Aviv Eyal's avatar
Aviv Eyal committed
36
	// Create protobufs bin data for a public key
Aviv Eyal's avatar
Aviv Eyal committed
37
38
39
	nodePubKey, err := node.Peerstore().PubKey(node.ID()).Bytes()

	if err != nil {
40
		panic("Failed to get public key for sender from local peer store.")
Aviv Eyal's avatar
Aviv Eyal committed
41
42
	}

Aviv Eyal's avatar
Aviv Eyal committed
43
	return &p2p.MessageData{ClientVersion: clientVersion,
Aviv Eyal's avatar
Aviv Eyal committed
44
		NodeId:     peer.IDB58Encode(node.ID()),
Aviv Eyal's avatar
Aviv Eyal committed
45
		NodePubKey: nodePubKey,
Aviv Eyal's avatar
Aviv Eyal committed
46
47
48
		Timestamp:  time.Now().Unix(),
		Id:         messageId,
		Gossip:     gossip}
Aviv Eyal's avatar
Aviv Eyal committed
49
}