forked from perlin-network/noise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
312 lines (240 loc) · 8.04 KB
/
node.go
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
package noise
import (
"fmt"
"github.com/perlin-network/noise/callbacks"
"github.com/perlin-network/noise/identity"
"github.com/perlin-network/noise/log"
"github.com/perlin-network/noise/nat"
"github.com/perlin-network/noise/transport"
"github.com/pkg/errors"
"net"
"sync"
"sync/atomic"
"time"
)
type Node struct {
Keys identity.Keypair
nat nat.Provider
transport transport.Layer
listener net.Listener
host string
internalPort, externalPort uint16
maxMessageSize uint64
sendMessageTimeout time.Duration
receiveMessageTimeout time.Duration
sendWorkerBusyTimeout time.Duration
onListenerErrorCallbacks *callbacks.SequentialCallbackManager
onPeerConnectedCallbacks *callbacks.SequentialCallbackManager
onPeerDialedCallbacks *callbacks.SequentialCallbackManager
onPeerInitCallbacks *callbacks.SequentialCallbackManager
metadata sync.Map
kill chan chan struct{}
killOnce uint32
}
func NewNode(params parameters) (*Node, error) {
if params.Port != 0 && (params.Port < 1024 || params.Port > 65535) {
return nil, errors.Errorf("port must be either 0 or between [1024, 65535]; port specified was %d", params.Port)
}
if params.Transport == nil {
return nil, errors.New("no transport layer was registered; try set params.Transport to transport.NewTCP()")
}
listener, err := params.Transport.Listen(params.Host, params.Port)
if err != nil {
return nil, errors.Wrapf(err, "failed to start listening for peers on port %d", params.Port)
}
params.Port = params.Transport.Port(listener.Addr())
node := Node{
Keys: params.Keys,
nat: params.NAT,
transport: params.Transport,
listener: listener,
host: params.Host,
internalPort: params.Port,
maxMessageSize: params.MaxMessageSize,
sendMessageTimeout: params.SendMessageTimeout,
receiveMessageTimeout: params.ReceiveMessageTimeout,
sendWorkerBusyTimeout: params.SendWorkerBusyTimeout,
onListenerErrorCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerConnectedCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerDialedCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerInitCallbacks: callbacks.NewSequentialCallbackManager(),
kill: make(chan chan struct{}, 1),
}
if params.ExternalPort > 0 {
node.externalPort = params.ExternalPort
} else {
node.externalPort = params.Port
}
for key, val := range params.Metadata {
node.Set(key, val)
}
if node.nat != nil {
err = node.nat.AddMapping(node.transport.String(), node.internalPort, node.externalPort, 1*time.Hour)
if err != nil {
return nil, errors.Wrap(err, "nat: failed to port-forward")
}
}
return &node, nil
}
func (n *Node) InternalPort() uint16 {
return n.internalPort
}
func (n *Node) ExternalPort() uint16 {
return n.externalPort
}
// Listen makes our node start listening for peers.
func (n *Node) Listen() {
for {
select {
case signal := <-n.kill:
close(signal)
return
default:
}
conn, err := n.listener.Accept()
if err != nil {
n.onListenerErrorCallbacks.RunCallbacks(err)
continue
}
peer := newPeer(n, conn)
peer.init()
if errs := n.onPeerConnectedCallbacks.RunCallbacks(peer); len(errs) > 0 {
log.Warn().Errs("errors", errs).Msg("Got errors running OnPeerConnected callbacks.")
}
if errs := n.onPeerInitCallbacks.RunCallbacks(peer); len(errs) > 0 {
log.Warn().Errs("errors", errs).Msg("Got errors running OnPeerInit callbacks.")
}
}
}
// Dial has our node attempt to dial and establish a connection with a remote peer.
func (n *Node) Dial(address string) (*Peer, error) {
if n.ExternalAddress() == address {
return nil, errors.New("noise: node attempted to dial itself")
}
conn, err := n.transport.Dial(address)
if err != nil {
return nil, errors.Wrapf(err, "failed to connect to peer %s", conn)
}
peer := newPeer(n, conn)
peer.init()
if errs := n.onPeerDialedCallbacks.RunCallbacks(peer); len(errs) > 0 {
log.Error().Errs("errors", errs).Msg("Got errors running OnPeerConnected callbacks.")
}
if errs := n.onPeerInitCallbacks.RunCallbacks(peer); len(errs) > 0 {
log.Error().Errs("errors", errs).Msg("Got errors running OnPeerInit callbacks.")
}
return peer, nil
}
// OnListenerError registers a callback for whenever our nodes listener fails to accept an incoming peer.
func (n *Node) OnListenerError(c OnErrorCallback) {
n.onListenerErrorCallbacks.RegisterCallback(func(params ...interface{}) error {
if len(params) != 1 {
panic(errors.Errorf("noise: OnListenerError received unexpected args %v", params))
}
err, ok := params[0].(error)
if !ok {
return nil
}
return c(n, errors.Wrap(err, "failed to accept an incoming peer"))
})
}
// OnPeerConnected registers a callback for whenever a peer has successfully been accepted by our node.
func (n *Node) OnPeerConnected(c OnPeerInitCallback) {
n.onPeerConnectedCallbacks.RegisterCallback(func(params ...interface{}) error {
if len(params) != 1 {
panic(errors.Errorf("noise: OnPeerConnected received unexpected args %v", params))
}
return c(n, params[0].(*Peer))
})
}
// OnPeerDisconnected registers a callback whenever a peer has been disconnected.
func (n *Node) OnPeerDisconnected(srcCallbacks ...OnPeerDisconnectCallback) {
n.onPeerInitCallbacks.RegisterCallback(func(params ...interface{}) error {
if len(params) != 1 {
panic(errors.Errorf("noise: OnPeerDisconnected received unexpected args %v", params))
}
peer := params[0].(*Peer)
peer.OnDisconnect(srcCallbacks...)
return nil
})
}
// OnPeerDialed registers a callback for whenever a peer has been successfully dialed.
func (n *Node) OnPeerDialed(c OnPeerInitCallback) {
n.onPeerDialedCallbacks.RegisterCallback(func(params ...interface{}) error {
if len(params) != 1 {
panic(errors.Errorf("noise: OnPeerDialed received unexpected args %v", params))
}
return c(n, params[0].(*Peer))
})
}
// OnPeerInit registers a callback for whenever a peer has either been successfully
// dialed, or otherwise accepted by our node.
//
// In essence a helper function that registers callbacks for both `OnPeerConnected`
// and `OnPeerDialed` at once.
func (n *Node) OnPeerInit(srcCallbacks ...OnPeerInitCallback) {
targetCallbacks := make([]callbacks.Callback, 0, len(srcCallbacks))
for _, c := range srcCallbacks {
c := c
targetCallbacks = append(targetCallbacks, func(params ...interface{}) error {
if len(params) != 1 {
panic(errors.Errorf("noise: OnPeerInit received unexpected args %v", params))
}
return c(n, params[0].(*Peer))
})
}
n.onPeerInitCallbacks.RegisterCallback(targetCallbacks...)
}
// Set sets a metadata entry given a key-value pair on our node.
func (n *Node) Set(key string, val interface{}) {
n.metadata.Store(key, val)
}
// Get returns the value to a metadata key from our node, or otherwise returns nil should
// there be no corresponding value to a provided key.
func (n *Node) Get(key string) interface{} {
val, _ := n.metadata.Load(key)
return val
}
func (n *Node) LoadOrStore(key string, val interface{}) interface{} {
val, _ = n.metadata.LoadOrStore(key, val)
return val
}
func (n *Node) Has(key string) bool {
_, exists := n.metadata.Load(key)
return exists
}
func (n *Node) Delete(key string) {
n.metadata.Delete(key)
}
// Fence blocks the current goroutine until the node stops listening for peers.
func (n *Node) Fence() {
<-n.kill
}
func (n *Node) Kill() {
if !atomic.CompareAndSwapUint32(&n.killOnce, 0, 1) {
return
}
signal := make(chan struct{})
n.kill <- signal
if err := n.listener.Close(); err != nil {
n.onListenerErrorCallbacks.RunCallbacks(err)
}
<-signal
close(n.kill)
if n.nat != nil {
err := n.nat.DeleteMapping(n.transport.String(), n.internalPort, n.externalPort)
if err != nil {
panic(errors.Wrap(err, "nat: failed to remove port-forward"))
}
}
}
func (n *Node) ExternalAddress() string {
if n.nat != nil && nat.IsPrivateIP(net.ParseIP(n.host)) {
externalIP, err := n.nat.ExternalIP()
if err != nil {
panic(err)
}
return fmt.Sprintf("%s:%d", externalIP.String(), n.externalPort)
}
return fmt.Sprintf("%s:%d", n.host, n.externalPort)
}