node.go 1.66 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"bufio"
	"log"
	"time"

	host "gx/ipfs/QmRS46AyqtpJBsf1zmQdeizSDEzo1qkWR7rdEuPFAv8237/go-libp2p-host"
	inet "gx/ipfs/QmbD5yKbXahNvoMqzeuNyKQA9vAs9fUvJg2GXeWU1fVqY5/go-libp2p-net"

	protobufCodec "github.com/multiformats/go-multicodec/protobuf"

	p2p "github.com/libp2p/go-libp2p/examples/multipro/pb"
)

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

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

// helper method - generate message data shared between all node's p2p protocols
// nodeId - message author id
Aviv Eyal's avatar
Aviv Eyal committed
36
// messageId - unique for requests, copied from request for responses
37
func NewMessageData(nodeId string, messageId string, gossip bool) *p2p.MessageData {
Aviv Eyal's avatar
Aviv Eyal committed
38
39
40
41
42
	return &p2p.MessageData{ClientVersion: clientVersion,
		NodeId:    nodeId,
		Timestamp: time.Now().Unix(),
		Id:        messageId,
		Gossip:    gossip}
43
44
45
46
47
48
49
50
51
}

// Node type - implements one or more p2p protocols
type Node struct {
	host         host.Host     // lib-p2p host
	pingProtocol *PingProtocol // ping protocol impl
	echoProtocol *EchoProtocol // echp protocl imp
}

Aviv Eyal's avatar
Aviv Eyal committed
52
// create a new node with its implemented protocols
53
54
func NewNode(host host.Host, done chan bool) *Node {
	return &Node{host: host,
Aviv Eyal's avatar
Aviv Eyal committed
55
56
		pingProtocol: NewPingProtocol(host, done),
		echoProtocol: NewEchoProtocol(host, done)}
57
}