node.go 4.46 KB
Newer Older
1
2
3
package main

import (
Aviv Eyal's avatar
Aviv Eyal committed
4
	"bufio"
Aviv Eyal's avatar
Aviv Eyal committed
5
6
7
	"log"
	"time"

Aviv Eyal's avatar
Aviv Eyal committed
8
	"github.com/gogo/protobuf/proto"
Steven Allen's avatar
Steven Allen committed
9
10
11
12
	crypto "github.com/libp2p/go-libp2p-crypto"
	host "github.com/libp2p/go-libp2p-host"
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
Steven Allen's avatar
Steven Allen committed
13
	p2p "github.com/libp2p/go-libp2p/examples/multipro/pb"
Aviv Eyal's avatar
Aviv Eyal committed
14
	protobufCodec "github.com/multiformats/go-multicodec/protobuf"
15
16
)

Aviv Eyal's avatar
Aviv Eyal committed
17
18
19
// node client version
const clientVersion = "go-p2p-node/0.0.1"

Aviv Eyal's avatar
Aviv Eyal committed
20
21
22
23
24
25
26
27
// Node type - a p2p host implementing one or more p2p protocols
type Node struct {
	host.Host     // lib-p2p host
	*PingProtocol // ping protocol impl
	*EchoProtocol // echo protocol impl
	// add other protocols here...
}

Aviv Eyal's avatar
Aviv Eyal committed
28
// Create a new node with its implemented protocols
Aviv Eyal's avatar
Aviv Eyal committed
29
30
31
32
33
34
35
func NewNode(host host.Host, done chan bool) *Node {
	node := &Node{Host: host}
	node.PingProtocol = NewPingProtocol(node, done)
	node.EchoProtocol = NewEchoProtocol(node, done)
	return node
}

Aviv Eyal's avatar
Aviv Eyal committed
36
37
38
// Authenticate incoming p2p message
// message: a protobufs go data object
// data: common p2p message data
39
func (n *Node) authenticateMessage(message proto.Message, data *p2p.MessageData) bool {
Aviv Eyal's avatar
Aviv Eyal committed
40
	// store a temp ref to signature and remove it from message data
Aviv Eyal's avatar
Aviv Eyal committed
41
	// sign is a string to allow easy reset to zero-value (empty string)
42
43
44
	sign := data.Sign
	data.Sign = ""

Aviv Eyal's avatar
Aviv Eyal committed
45
	// marshall data without the signature to protobufs3 binary format
46
47
	bin, err := proto.Marshal(message)
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
48
		log.Println(err, "failed to marshal pb message")
49
50
51
52
53
54
		return false
	}

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

Aviv Eyal's avatar
Aviv Eyal committed
55
	// restore peer id binary format from base58 encoded node id data
56
57
	peerId, err := peer.IDB58Decode(data.NodeId)
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
58
		log.Println(err, "Failed to decode node id from base58")
59
60
61
		return false
	}

Aviv Eyal's avatar
Aviv Eyal committed
62
63
	// verify the data was authored by the signing peer identified by the public key
	// and signature included in the message
64
	return n.verifyData(bin, []byte(sign), peerId, data.NodePubKey)
65
66
}

Aviv Eyal's avatar
Aviv Eyal committed
67
// sign an outgoing p2p message payload
68
func (n *Node) signProtoMessage(message proto.Message) ([]byte, error) {
Aviv Eyal's avatar
Aviv Eyal committed
69
70
71
72
73
74
75
	data, err := proto.Marshal(message)
	if err != nil {
		return nil, err
	}
	return n.signData(data)
}

Aviv Eyal's avatar
Aviv Eyal committed
76
// sign binary data using the local node's private key
77
func (n *Node) signData(data []byte) ([]byte, error) {
Aviv Eyal's avatar
Aviv Eyal committed
78
79
80
	key := n.Peerstore().PrivKey(n.ID())
	res, err := key.Sign(data)
	return res, err
81
82
}

Aviv Eyal's avatar
Aviv Eyal committed
83
84
85
86
87
// Verify incoming p2p message data integrity
// data: data to verify
// signature: author signature provided in the message payload
// peerId: author peer id from the message payload
// pubKeyData: author public key from the message payload
88
func (n *Node) verifyData(data []byte, signature []byte, peerId peer.ID, pubKeyData []byte) bool {
89
90
91
92
93
94
95
96
	key, err := crypto.UnmarshalPublicKey(pubKeyData)
	if err != nil {
		log.Println(err, "Failed to extract key from message key data")
		return false
	}

	// extract node id from the provided public key
	idFromKey, err := peer.IDFromPublicKey(key)
97

98
99
100
101
	if err != nil {
		log.Println(err, "Failed to extract peer id from public key")
		return false
	}
102

Aviv Eyal's avatar
Aviv Eyal committed
103
	// verify that message author node id matches the provided node public key
104
105
	if idFromKey != peerId {
		log.Println(err, "Node id and provided public key mismatch")
Aviv Eyal's avatar
Aviv Eyal committed
106
107
108
109
110
		return false
	}

	res, err := key.Verify(data, signature)
	if err != nil {
111
		log.Println(err, "Error authenticating data")
Aviv Eyal's avatar
Aviv Eyal committed
112
113
114
115
		return false
	}

	return res
116
}
Aviv Eyal's avatar
Aviv Eyal committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

// helper method - generate message data shared between all node's p2p protocols
// messageId: unique for requests, copied from request for responses
func (n *Node) NewMessageData(messageId string, gossip bool) *p2p.MessageData {
	// Add protobufs bin data for message author public key
	// this is useful for authenticating  messages forwarded by a node authored by another node
	nodePubKey, err := n.Peerstore().PubKey(n.ID()).Bytes()

	if err != nil {
		panic("Failed to get public key for sender from local peer store.")
	}

	return &p2p.MessageData{ClientVersion: clientVersion,
		NodeId:     peer.IDB58Encode(n.ID()),
		NodePubKey: nodePubKey,
		Timestamp:  time.Now().Unix(),
		Id:         messageId,
		Gossip:     gossip}
}
Aviv Eyal's avatar
Aviv Eyal committed
136
137
138
139

// 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
140
func (n *Node) sendProtoMessage(data proto.Message, s inet.Stream) bool {
Aviv Eyal's avatar
Aviv Eyal committed
141
142
143
144
145
146
147
148
149
150
	writer := bufio.NewWriter(s)
	enc := protobufCodec.Multicodec(nil).Encoder(writer)
	err := enc.Encode(data)
	if err != nil {
		log.Println(err)
		return false
	}
	writer.Flush()
	return true
}