ping.go 4.17 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
package main

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

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

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

// 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
23
	node     *Node                       // local host
24
	requests map[string]*p2p.PingRequest // used to access request data from response handlers
Aviv Eyal's avatar
Aviv Eyal committed
25
	done     chan bool                   // only for demo purposes to stop main from terminating
26
27
}

Aviv Eyal's avatar
Aviv Eyal committed
28
29
30
31
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
32
	return p
33
34
35
}

// remote peer requests handler
36
func (p *PingProtocol) onPingRequest(s inet.Stream) {
37
38
39
40
41
42

	// get request data
	data := &p2p.PingRequest{}
	decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
	err := decoder.Decode(data)
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
43
		log.Println(err)
44
45
46
47
48
		return
	}

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

49
50
51
	valid := p.node.authenticateMessage(data, data.MessageData)

	if !valid {
Aviv Eyal's avatar
Aviv Eyal committed
52
		log.Println("Failed to authenticate message")
53
54
55
		return
	}

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

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

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

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

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

Aviv Eyal's avatar
Aviv Eyal committed
79
	ok := sendProtoMessage(resp, s)
80
81
82
83
84
85
86

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

// remote ping response handler
87
func (p *PingProtocol) onPingResponse(s inet.Stream) {
88
89
90
91
92
93
94
	data := &p2p.PingResponse{}
	decoder := protobufCodec.Multicodec(nil).Decoder(bufio.NewReader(s))
	err := decoder.Decode(data)
	if err != nil {
		return
	}

95
96
97
	valid := p.node.authenticateMessage(data, data.MessageData)

	if !valid {
Aviv Eyal's avatar
Aviv Eyal committed
98
		log.Println("Failed to authenticate message")
99
100
101
		return
	}

102
103
104
105
106
107
	// 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 {
Aviv Eyal's avatar
Aviv Eyal committed
108
		log.Println("Failed to locate request data boject for response")
109
110
111
112
113
114
115
		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
}

116
func (p *PingProtocol) Ping(host host.Host) bool {
Aviv Eyal's avatar
Aviv Eyal committed
117
	log.Printf("%s: Sending ping to: %s....", p.node.ID(), host.ID())
118
119

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

Aviv Eyal's avatar
Aviv Eyal committed
123
124
125
	// sign the data
	signature, err := p.node.signProtoMessage(req)
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
126
		log.Println("failed to sign pb data")
Aviv Eyal's avatar
Aviv Eyal committed
127
128
129
130
131
132
133
		return false
	}

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

	s, err := p.node.NewStream(context.Background(), host.ID(), pingRequest)
134
	if err != nil {
Aviv Eyal's avatar
Aviv Eyal committed
135
		log.Println(err)
136
137
138
		return false
	}

Aviv Eyal's avatar
Aviv Eyal committed
139
	ok := sendProtoMessage(req, s)
140
141
142
143
144

	if !ok {
		return false
	}

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