node.go 1.2 KB
Newer Older
1
2
3
4
package main

import (
	host "gx/ipfs/QmRS46AyqtpJBsf1zmQdeizSDEzo1qkWR7rdEuPFAv8237/go-libp2p-host"
Aviv Eyal's avatar
Aviv Eyal committed
5
	peer "gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
Aviv Eyal's avatar
Aviv Eyal committed
6
	"github.com/gogo/protobuf/proto"
7
8
)

Aviv Eyal's avatar
Aviv Eyal committed
9
10
11
12
13
14
15
16
17
18
func (n Node) signProtoMessage(message proto.Message) ([]byte, error) {
	// sign the data
	data, err := proto.Marshal(message)
	if err != nil {
		return nil, err
	}

	return n.signData(data)
}

Aviv Eyal's avatar
Aviv Eyal committed
19
20
21
22
func (n Node) signData(data []byte) ([]byte, error) {
	key := n.Peerstore().PrivKey(n.ID())
	res, err := key.Sign(data)
	return res, err
23
24
}

Aviv Eyal's avatar
Aviv Eyal committed
25
26
27
28
func (n Node) verifyData(data []byte, signature []byte, signerHostId peer.ID) bool {
	key := n.Peerstore().PubKey(signerHostId)
	res, err := key.Verify(data, signature)
	return res == true && err == nil
29
30
}

Aviv Eyal's avatar
Aviv Eyal committed
31
// Node type - a host with one or more implemented p2p protocols
32
type Node struct {
Aviv Eyal's avatar
Aviv Eyal committed
33
34
35
	host.Host     // lib-p2p host
	*PingProtocol // ping protocol impl
	*EchoProtocol // echo protocol impl
Aviv Eyal's avatar
Aviv Eyal committed
36
	// add other protocols here...
37
38
}

Aviv Eyal's avatar
Aviv Eyal committed
39
// create a new node with its implemented protocols
40
func NewNode(host host.Host, done chan bool) *Node {
Aviv Eyal's avatar
Aviv Eyal committed
41
42
43
44
	node := &Node{Host: host}
	node.PingProtocol = NewPingProtocol(node, done)
	node.EchoProtocol = NewEchoProtocol(node, done)
	return node
45
}