ping.go 4.44 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"bufio"
	"context"
	"fmt"
	"log"

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

	uuid "github.com/google/uuid"
	p2p "github.com/libp2p/go-libp2p/examples/multipro/pb"
	protobufCodec "github.com/multiformats/go-multicodec/protobuf"
Aviv Eyal's avatar
Aviv Eyal committed
14
	"gx/ipfs/QmRS46AyqtpJBsf1zmQdeizSDEzo1qkWR7rdEuPFAv8237/go-libp2p-host"
15
	"gx/ipfs/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB/go-libp2p-peer"
16
17
18
19
20
21
22
23
)

// pattern: /protocol-name/request-or-response-message/version
const pingRequest = "/ping/pingreq/0.0.1"
const pingResponse = "/ping/pingresp/0.0.1"

// PingProtocol type
type PingProtocol struct {
Aviv Eyal's avatar
Aviv Eyal committed
24
	node     *Node                       // local host
25
	requests map[string]*p2p.PingRequest // used to access request data from response handlers
Aviv Eyal's avatar
Aviv Eyal committed
26
	done     chan bool                   // only for demo purposes to stop main from terminating
27
28
}

Aviv Eyal's avatar
Aviv Eyal committed
29
30
31
32
func NewPingProtocol(node *Node, done chan bool) *PingProtocol {
	p := &PingProtocol{node: node, requests: make(map[string]*p2p.PingRequest), done: done}
	node.SetStreamHandler(pingRequest, p.onPingRequest)
	node.SetStreamHandler(pingResponse, p.onPingResponse)
Aviv Eyal's avatar
Aviv Eyal committed
33
	return p
34
35
36
}

// remote peer requests handler
Aviv Eyal's avatar
Aviv Eyal committed
37
func (p PingProtocol) onPingRequest(s inet.Stream) {
38
39
40
41
42
43
44
45
46
47
48
49

	// get request data
	data := &p2p.PingRequest{}
	decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
	err := decoder.Decode(data)
	if err != nil {
		log.Fatal(err)
		return
	}

	log.Printf("%s: Received ping request from %s. Message: %s", s.Conn().LocalPeer(), s.Conn().RemotePeer(), data.Message)

50
51
52
53
54
55
56
57
58
	valid := p.node.authenticateMessage(data, data.MessageData)

	if !valid {
		log.Fatal("Failed to authenticate message")
		return
	} else {
		log.Print("Authenticated request content was generated by claimed node :-)")
	}

Aviv Eyal's avatar
Aviv Eyal committed
59
	// generate response message
60
	log.Printf("%s: Sending ping response to %s. Message id: %s...", s.Conn().LocalPeer(), s.Conn().RemotePeer(), data.MessageData.Id)
61
62

	resp := &p2p.PingResponse{MessageData: NewMessageData(peer.IDB58Encode(p.node.ID()), data.MessageData.Id, false),
Aviv Eyal's avatar
Aviv Eyal committed
63
		Message: fmt.Sprintf("Ping response from %s", p.node.ID())}
64

Aviv Eyal's avatar
Aviv Eyal committed
65
66
67
68
69
70
71
72
73
74
75
	// sign the data
	signature, err := p.node.signProtoMessage(resp)
	if err != nil {
		log.Fatal("failed to sign response")
		return
	}

	// add the signature to the message
	resp.MessageData.Sign = string(signature)

	// send the response
Aviv Eyal's avatar
Aviv Eyal committed
76
	s, respErr := p.node.NewStream(context.Background(), s.Conn().RemotePeer(), pingResponse)
77
78
79
80
81
	if respErr != nil {
		log.Fatal(respErr)
		return
	}

Aviv Eyal's avatar
Aviv Eyal committed
82
	ok := sendProtoMessage(resp, s)
83
84
85
86
87
88
89

	if ok {
		log.Printf("%s: Ping response to %s sent.", s.Conn().LocalPeer().String(), s.Conn().RemotePeer().String())
	}
}

// remote ping response handler
Aviv Eyal's avatar
Aviv Eyal committed
90
func (p PingProtocol) onPingResponse(s inet.Stream) {
91
92
93
94
95
96
97
	data := &p2p.PingResponse{}
	decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
	err := decoder.Decode(data)
	if err != nil {
		return
	}

98
99
100
101
102
103
104
105
106
	valid := p.node.authenticateMessage(data, data.MessageData)

	if !valid {
		log.Fatal("Failed to authenticate message")
		return
	} else {
		log.Print("Authenticated response content generated by claimed node :-)")
	}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
	// locate request data and remove it if found
	_, ok := p.requests[data.MessageData.Id]
	if ok {
		// remove request from map as we have processed it here
		delete(p.requests, data.MessageData.Id)
	} else {
		log.Print("Failed to locate request data boject for response")
		return
	}

	log.Printf("%s: Received ping response from %s. Message id:%s. Message: %s.", s.Conn().LocalPeer(), s.Conn().RemotePeer(), data.MessageData.Id, data.Message)
	p.done <- true
}

Aviv Eyal's avatar
Aviv Eyal committed
121
122
func (p PingProtocol) Ping(host host.Host) bool {
	log.Printf("%s: Sending ping to: %s....", p.node.ID(), host.ID())
123
124

	// create message data
125
	req := &p2p.PingRequest{MessageData: NewMessageData(peer.IDB58Encode(p.node.ID()), uuid.New().String(), false),
Aviv Eyal's avatar
Aviv Eyal committed
126
		Message: fmt.Sprintf("Ping from %s", p.node.ID())}
127

Aviv Eyal's avatar
Aviv Eyal committed
128
129
130
131
132
133
134
135
136
137
138
	// sign the data
	signature, err := p.node.signProtoMessage(req)
	if err != nil {
		log.Fatal("failed to sign pb data")
		return false
	}

	// add the signature to the message
	req.MessageData.Sign = string(signature)

	s, err := p.node.NewStream(context.Background(), host.ID(), pingRequest)
139
140
141
142
143
	if err != nil {
		log.Fatal(err)
		return false
	}

Aviv Eyal's avatar
Aviv Eyal committed
144
	ok := sendProtoMessage(req, s)
145
146
147
148
149

	if !ok {
		return false
	}

Aviv Eyal's avatar
Aviv Eyal committed
150
	// store ref request so response handler has access to it
151
	p.requests[req.MessageData.Id] = req
Aviv Eyal's avatar
Aviv Eyal committed
152
	log.Printf("%s: Ping to: %s was sent. Message Id: %s, Message: %s", p.node.ID(), host.ID(), req.MessageData.Id, req.Message)
153
154
	return true
}