forked from perlin-network/noise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
252 lines (194 loc) · 6.55 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
package noise
import (
"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"
"strconv"
"sync"
)
type Node struct {
ID identity.Manager
nat nat.Provider
transport transport.Layer
listener net.Listener
port uint16
maxMessageSize uint64
onListenerErrorCallbacks *callbacks.SequentialCallbackManager
onPeerConnectedCallbacks *callbacks.SequentialCallbackManager
onPeerDialedCallbacks *callbacks.SequentialCallbackManager
onPeerInitCallbacks *callbacks.SequentialCallbackManager
metadata sync.Map
kill chan struct{}
killOnce sync.Once
}
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.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{
ID: params.ID,
nat: params.NAT,
transport: params.Transport,
listener: listener,
port: params.Port,
maxMessageSize: params.MaxMessageSize,
onListenerErrorCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerConnectedCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerDialedCallbacks: callbacks.NewSequentialCallbackManager(),
onPeerInitCallbacks: callbacks.NewSequentialCallbackManager(),
kill: make(chan struct{}, 1),
}
for key, val := range params.Metadata {
node.Set(key, val)
}
return &node, nil
}
func (n *Node) Port() uint16 {
return n.port
}
// Listen makes our node start listening for peers.
func (n *Node) Listen() {
for {
select {
case <-n.kill:
n.listener = nil
return
default:
}
conn, err := n.listener.Accept()
if err != nil {
n.onListenerErrorCallbacks.RunCallbacks(err)
}
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))
})
}
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() {
n.killOnce.Do(func() {
n.kill <- struct{}{}
if err := n.listener.Close(); err != nil {
n.onListenerErrorCallbacks.RunCallbacks(err)
}
})
}
func (n *Node) ExternalAddress() string {
//return n.nat.ExternalIP().String() + ":" + strconv.Itoa(int(n.port))
return "127.0.0.1" + ":" + strconv.Itoa(int(n.port))
}