summaryrefslogtreecommitdiff
path: root/pkg/p2p/network.go
blob: 13c99b042226d912b13789ae35e8964fbe116224 (plain)
1
2
3
4
5
6
7
8
9
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package p2p

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"sync"
	"time"

	"go.uber.org/zap"
)

// `Message` represents a structured message on this network.
type Message struct {
	Type      []byte    `json:"type"`
	Timestamp int64     `json:"timestamp"`
	Source    NetworkID `json:"source"`
	Payload   []byte    `json:"payload"`
}

// A network ID is represented by a string
type NetworkID string

// Default empty network' ID
const EmptyNetworkID NetworkID = NetworkID("")

// This type represents the function that is called every time a new message
// arrives to the server.
type NetworkMessageReceiveFunc func(msg Message)

// This type represent the callback function invokes every new handshake between
// two peers
type NetworkHandshakeFunc func(conn net.Conn) error

func DefaultHandshake(conn net.Conn) error {
	return nil
}

// Network options to define on new `TCPNetwork`
type TCPNetworkOpts struct {
	ListenAddr  string
	RetryDelay  time.Duration
	HandshakeFn NetworkHandshakeFunc
	OnReceiveFn NetworkMessageReceiveFunc
	Logger      *zap.Logger
}

// PeerConnection holds the connection and address of a peer.
type PeerConnection struct {
	Conn    net.Conn
	Address string
}

// TCPNetwork represents a TCP peer capable to send and receive messages
type TCPNetwork struct {
	sync.Mutex
	TCPNetworkOpts

	id          NetworkID
	listener    net.Listener
	connections map[NetworkID]PeerConnection
	isClosed    bool
}

// Initiliaze a new TCP network
func NewTCPNetwork(localID NetworkID, opts TCPNetworkOpts) *TCPNetwork {
	n := &TCPNetwork{
		TCPNetworkOpts: opts,
		id:             localID,
		connections:    make(map[NetworkID]PeerConnection),
	}

	go n.startServer()

	return n
}

// Close listener' connection
func (n *TCPNetwork) Close() error {
	n.isClosed = true
	if n.listener != nil {
		err := n.listener.Close()
		if err != nil {
			return err
		}
	}
	n.Lock()
	for _, pc := range n.connections {
		if pc.Conn != nil {
			pc.Conn.Close()
		}
	}
	n.connections = nil
	n.Unlock()
	return nil
}

// Add a new peer connection to the local peer
func (n *TCPNetwork) AddPeer(remoteID NetworkID, addr string) {
	n.Lock()
	if _, exists := n.connections[remoteID]; !exists {
		n.connections[remoteID] = PeerConnection{Address: addr}
		go n.retryConnect(remoteID, addr)
	}
	n.Unlock()
}

// Send methods is used to send a message to a specified remote peer
func (n *TCPNetwork) Send(remoteID NetworkID, messageType []byte, payload []byte) error {
	n.Lock()
	peerConn, exists := n.connections[remoteID]
	n.Unlock()

	if !exists {
		return fmt.Errorf("not connected to peer %s", remoteID)
	}

	if peerConn.Conn == nil {
		n.Logger.Sugar().Warnf("connection to peer %s is nil, attempting reconnect", remoteID)
		go n.retryConnect(remoteID, peerConn.Address)
		return fmt.Errorf("connection to peer %s is nil", remoteID)
	}

	message := Message{
		Type:      messageType,
		Payload:   payload,
		Source:    n.id,
		Timestamp: time.Now().Unix(),
	}

	data, err := json.Marshal(message)
	if err != nil {
		return fmt.Errorf("failed to marshal message: %v", err)
	}

	_, err = peerConn.Conn.Write(append(data, '\n'))

	if err != nil {
		n.Logger.Sugar().Errorf("failed to send message to %s: %v. Reconnecting...", remoteID, err)
		n.removeConnection(remoteID)
		go n.retryConnect(remoteID, peerConn.Address)
		return fmt.Errorf("failed to send message: %v", err)
	} else {
		n.Logger.Sugar().Infof("sent message to '%s' (%s): %s", remoteID, peerConn.Address, string(message.Payload))
	}

	return nil
}

// RegisterHandler registers a callback for a message type.
func (n *TCPNetwork) RegisterHandler(callback NetworkMessageReceiveFunc) {
	n.OnReceiveFn = callback
}

// startServer starts a TCP server to accept connections.
func (n *TCPNetwork) startServer() {
	var err error

	n.listener, err = net.Listen("tcp", n.ListenAddr)
	if err != nil {
		n.Logger.Sugar().Errorf("failed to start server: %v", err)
		return
	}

	n.isClosed = false

	n.Logger.Sugar().Infof("server started on %s\n", n.ListenAddr)

	for {
		conn, err := n.listener.Accept()
		if n.isClosed {
			n.Logger.Info("server listener closed")
			return
		}
		if err != nil {
			n.Logger.Sugar().Errorf("failed to accept connection: %v\n", err)
			continue
		}
		go n.handleConnection(conn)
	}
}

func (n *TCPNetwork) handleConnection(conn net.Conn) {
	remoteAddr := conn.RemoteAddr().String()
	remoteID := NetworkID(remoteAddr)

	n.Lock()
	n.connections[remoteID] = PeerConnection{Conn: conn, Address: remoteAddr}
	n.Unlock()

	if n.HandshakeFn != nil {
		if err := n.HandshakeFn(conn); err != nil {
			n.Logger.Sugar().Errorf("error on handshaking with %s: %v\n", remoteAddr, err)
			conn.Close()
			n.removeConnection(remoteID)
			return
		}
	}

	n.Logger.Sugar().Infof("connected to remote peer %s (%s)\n", remoteID, remoteAddr)

	n.listenForMessages(conn, remoteID)

	n.removeConnection(remoteID)
	conn.Close()
	n.Logger.Sugar().Infof("connection to %s closed\n", remoteAddr)
}

func (n *TCPNetwork) removeConnection(id NetworkID) {
	n.Lock()
	delete(n.connections, id)
	n.Unlock()
}

// listenForMessages listens for incoming messages on a specific connection.
func (n *TCPNetwork) listenForMessages(conn net.Conn, remoteID NetworkID) {
	reader := bufio.NewReader(conn)
	remoteAddr := conn.RemoteAddr().String()

	for {
		data, err := reader.ReadBytes('\n')
		if err != nil {
			if errors.Is(err, net.ErrClosed) {
				n.Logger.Sugar().Debugf("connection to %s closed by remote peer", remoteAddr)
			} else {
				n.Logger.Sugar().Warnf("error reading from connection %s: %v", remoteAddr, err)
			}

			n.Lock()
			peerConn, exists := n.connections[remoteID]
			n.Unlock()
			if exists {
				go n.retryConnect(remoteID, peerConn.Address)
			} else {
				n.Logger.Sugar().Warnf("no address to reconnect to peer %s", remoteID)
			}
			return
		}

		var message Message
		if err := json.Unmarshal(data, &message); err != nil {
			n.Logger.Sugar().Errorf("failed to unmarshal message from %s: %v\n", remoteAddr, err)
			continue
		}

		n.Logger.Sugar().Infof("received message from '%s' (%s): %s", message.Source, remoteAddr, string(message.Payload))

		if n.OnReceiveFn != nil {
			n.OnReceiveFn(message)
		}
	}
}

// retryConnect attempts to connect to a remote peer.
func (n *TCPNetwork) retryConnect(remoteID NetworkID, addr string) {
	if addr == "" {
		n.Logger.Sugar().Warnf("no address to reconnect to peer %s", remoteID)
		n.removeConnection(remoteID)
		return
	}

	retryDelay := n.RetryDelay
	for !n.isClosed {
		n.Lock()
		_, connected := n.connections[remoteID]
		n.Unlock()

		if connected {
			if n.connections[remoteID].Conn != nil {
				time.Sleep(5 * time.Second)
				continue
			}
		}

		conn, err := net.Dial("tcp", addr)

		if err == nil {
			n.Logger.Sugar().Infof("successfully connected to peer %s (%s)!", remoteID, addr)
			n.Lock()
			n.connections[remoteID] = PeerConnection{Conn: conn, Address: addr}
			n.Unlock()
			go n.handleConnection(conn)
			return
		} else {
			n.Logger.Sugar().Errorf("failed to connect to %s (%s): %v. Retrying in %v...", remoteID, addr, err, retryDelay)
			select {
			case <-time.After(retryDelay):
				if retryDelay < 2*time.Minute {
					retryDelay *= 2
				}
			case <-n.closed():
				n.Logger.Info("retryConnect stopped due to network closure (inner for)")
				return
			}
		}
	}
	n.Logger.Info("retryConnect stopped due to network closure")
}

func (n *TCPNetwork) closed() <-chan struct{} {
	ch := make(chan struct{})
	go func() {
		<-n.listenerClosed()
		close(ch)
	}()
	return ch
}

func (n *TCPNetwork) listenerClosed() <-chan struct{} {
	if n.listener == nil {
		ch := make(chan struct{})
		close(ch)
		return ch
	}
	done := make(chan struct{})
	go func() {
		n.listener.Accept() // This will block until closed
		close(done)
	}()
	return done
}