node.go 1.96 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
9

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

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
func (n Node) authenticateMessage(message proto.Message, data *p2p.MessageData) bool {

	// store a temp ref to sig and remove it from data
	sign := data.Sign
	data.Sign = ""

	//log.Print("Signature: %s", []byte(sign))

	// marshall data without the sig to binary format
	bin, err := proto.Marshal(message)
	if err != nil {
		// todo: log
		return false
	}

	// restore sig in message data (for possible future use)
	data.Sign = sign

	peerId, err := peer.IDB58Decode(data.NodeId)

	if err != nil {
		log.Fatal(err, "Failed to decode node id")
		return false
	}

	return n.verifyData(bin, []byte(sign), peerId)
}

Aviv Eyal's avatar
Aviv Eyal committed
40
41
42
43
44
45
46
47
func (n Node) signProtoMessage(message proto.Message) ([]byte, error) {
	data, err := proto.Marshal(message)
	if err != nil {
		return nil, err
	}
	return n.signData(data)
}

Aviv Eyal's avatar
Aviv Eyal committed
48
49
50
51
func (n Node) signData(data []byte) ([]byte, error) {
	key := n.Peerstore().PrivKey(n.ID())
	res, err := key.Sign(data)
	return res, err
52
53
}

54
55
56
57
// precondition: we have info about the signer peer in the local peer store
func (n Node) verifyData(data []byte, signature []byte, peerId peer.ID) bool {
	key := n.Peerstore().PubKey(peerId)
	//log.Print ("%s %s %s", peerId, key, peerId.String())
Aviv Eyal's avatar
Aviv Eyal committed
58
59
	res, err := key.Verify(data, signature)
	return res == true && err == nil
60
61
}

Aviv Eyal's avatar
Aviv Eyal committed
62
// Node type - a host with one or more implemented p2p protocols
63
type Node struct {
Aviv Eyal's avatar
Aviv Eyal committed
64
65
66
	host.Host     // lib-p2p host
	*PingProtocol // ping protocol impl
	*EchoProtocol // echo protocol impl
Aviv Eyal's avatar
Aviv Eyal committed
67
	// add other protocols here...
68
69
}

Aviv Eyal's avatar
Aviv Eyal committed
70
// create a new node with its implemented protocols
71
func NewNode(host host.Host, done chan bool) *Node {
Aviv Eyal's avatar
Aviv Eyal committed
72
73
74
75
	node := &Node{Host: host}
	node.PingProtocol = NewPingProtocol(node, done)
	node.EchoProtocol = NewEchoProtocol(node, done)
	return node
76
}