forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsNetwork.go
2565 lines (2271 loc) · 95.5 KB
/
wsNetwork.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package network
import (
"container/heap"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/textproto"
"net/url"
"path"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/algorand/go-deadlock"
"github.com/algorand/websocket"
"github.com/gorilla/mux"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/network/addr"
"github.com/algorand/go-algorand/network/limitcaller"
"github.com/algorand/go-algorand/network/limitlistener"
"github.com/algorand/go-algorand/network/p2p"
"github.com/algorand/go-algorand/network/phonebook"
"github.com/algorand/go-algorand/protocol"
tools_network "github.com/algorand/go-algorand/tools/network"
"github.com/algorand/go-algorand/tools/network/dnssec"
"github.com/algorand/go-algorand/util"
"github.com/algorand/go-algorand/util/metrics"
)
const incomingThreads = 20
const messageFilterSize = 5000 // messages greater than that size may be blocked by incoming/outgoing filter
// httpServerReadHeaderTimeout is the amount of time allowed to read
// request headers. The connection's read deadline is reset
// after reading the headers and the Handler can decide what
// is considered too slow for the body.
const httpServerReadHeaderTimeout = time.Second * 10
// httpServerWriteTimeout is the maximum duration before timing out
// writes of the response. It is reset whenever a new
// request's header is read.
const httpServerWriteTimeout = time.Second * 60
// httpServerIdleTimeout is the maximum amount of time to wait for the
// next request when keep-alives are enabled. If httpServerIdleTimeout
// is zero, the value of ReadTimeout is used. If both are
// zero, ReadHeaderTimeout is used.
const httpServerIdleTimeout = time.Second * 4
// MaxHeaderBytes controls the maximum number of bytes the
// server will read parsing the request header's keys and
// values, including the request line. It does not limit the
// size of the request body.
const httpServerMaxHeaderBytes = 4096
// connectionActivityMonitorInterval is the interval at which we check
// if any of the connected peers have been idle for a long while and
// need to be disconnected.
const connectionActivityMonitorInterval = 3 * time.Minute
// maxPeerInactivityDuration is the maximum allowed duration for a
// peer to remain completely idle (i.e. no inbound or outbound communication), before
// we discard the connection.
const maxPeerInactivityDuration = 5 * time.Minute
// maxMessageQueueDuration is the maximum amount of time a message is allowed to be waiting
// in the various queues before being sent. Once that deadline has reached, sending the message
// is pointless, as it's too stale to be of any value
const maxMessageQueueDuration = 25 * time.Second
// slowWritingPeerMonitorInterval is the interval at which we peek on the connected peers to
// verify that their current outgoing message is not being blocked for too long.
const slowWritingPeerMonitorInterval = 5 * time.Second
// unprintableCharacterGlyph is used to replace any non-ascii character when logging incoming network string directly
// to the log file. Note that the log file itself would also json-encode these before placing them in the log file.
const unprintableCharacterGlyph = "▯"
// testingPublicAddress is used in identity exchange tests for a predictable
// PublicAddress (which will match HTTP Listener's Address) in tests only.
const testingPublicAddress = "testing"
// Maximum number of bytes to read from a header when trying to establish a websocket connection.
const wsMaxHeaderBytes = 4096
// ReservedHealthServiceConnections reserves additional connections for the health check endpoint. This reserves
// capacity to query the health check service when a node is serving maximum peers. The file descriptors will be
// used from the ReservedFDs pool, as this pool is meant for short-lived usage (dns queries, disk i/o, etc.)
const ReservedHealthServiceConnections = 10
var networkIncomingConnections = metrics.MakeGauge(metrics.NetworkIncomingConnections)
var networkOutgoingConnections = metrics.MakeGauge(metrics.NetworkOutgoingConnections)
var networkIncomingBufferMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_buffer_micros_total", Description: "microseconds spent by incoming messages on the receive buffer"})
var networkHandleMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_handle_micros_total", Description: "microseconds spent by protocol handlers in the receive thread"})
var networkBroadcasts = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcasts_total", Description: "number of broadcast operations"})
var networkBroadcastQueueMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_micros_total", Description: "microseconds broadcast requests sit on queue"})
var networkBroadcastSendMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_send_micros_total", Description: "microseconds spent broadcasting"})
var networkBroadcastsDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_broadcasts_dropped_total", Description: "number of broadcast messages not sent to any peer"})
var networkPeerBroadcastDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_peer_broadcast_dropped_total", Description: "number of broadcast messages not sent to some peer"})
var networkPeerIdentityDisconnect = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_identity_duplicate", Description: "number of times identity challenge cause us to disconnect a peer"})
var networkPeerIdentityError = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_identity_error", Description: "number of times an error occurs (besides expected) when processing identity challenges"})
var networkPeerAlreadyClosed = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_peer_already_closed", Description: "number of times a peer would be added but the peer connection is already closed"})
var networkSlowPeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_slow_drops_total", Description: "number of peers dropped for being slow to send to"})
var networkIdlePeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_idle_drops_total", Description: "number of peers dropped due to idle connection"})
var networkBroadcastQueueFull = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_full_total", Description: "number of messages that were drops due to full broadcast queue"})
var minPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_min_ping_seconds", Description: "Network round trip time to fastest peer in seconds."})
var meanPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_mean_ping_seconds", Description: "Network round trip time to average peer in seconds."})
var medianPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_median_ping_seconds", Description: "Network round trip time to median peer in seconds."})
var maxPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_max_ping_seconds", Description: "Network round trip time to slowest peer in seconds."})
var peers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peers", Description: "Number of active peers."})
var incomingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_incoming_peers", Description: "Number of active incoming peers."})
var outgoingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_outgoing_peers", Description: "Number of active outgoing peers."})
var networkPrioBatchesPPWithCompression = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_prio_batches_wpp_comp_sent_total", Description: "number of prio compressed batches with PP"})
var networkPrioBatchesPPWithoutCompression = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_pp_prio_batches_wpp_non_comp_sent_total", Description: "number of prio non-compressed batches with PP"})
var networkPrioPPCompressedSize = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_prio_pp_compressed_size_total", Description: "cumulative size of all compressed PP"})
var networkPrioPPNonCompressedSize = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_prio_pp_non_compressed_size_total", Description: "cumulative size of all non-compressed PP"})
// peerDisconnectionAckDuration defines the time we would wait for the peer disconnection to complete.
const peerDisconnectionAckDuration = 5 * time.Second
// peerShutdownDisconnectionAckDuration defines the time we would wait for the peer disconnection to complete during shutdown.
const peerShutdownDisconnectionAckDuration = 50 * time.Millisecond
// GossipNetworkPath is the URL path to connect to the websocket gossip node at.
// Contains {genesisID} param to be handled by gorilla/mux
const GossipNetworkPath = "/v1/{genesisID}/gossip"
// HealthServiceStatusPath is the path to register HealthService as a handler for when using gorilla/mux
const HealthServiceStatusPath = "/status"
// NodeInfo helps the network get information about the node it is running on
type NodeInfo interface {
// IsParticipating returns true if this node has stake and may vote on blocks or propose blocks.
IsParticipating() bool
// Capabilities returns a list of capabilities this node has.
Capabilities() []p2p.Capability
}
type nopeNodeInfo struct {
}
func (nnni *nopeNodeInfo) IsParticipating() bool {
return false
}
func (nnni *nopeNodeInfo) Capabilities() []p2p.Capability {
return nil
}
// WebsocketNetwork implements GossipNode
type WebsocketNetwork struct {
listener net.Listener
server http.Server
router *mux.Router
scheme string // are we serving http or https ?
upgrader websocket.Upgrader
config config.Local
log logging.Logger
wg sync.WaitGroup
ctx context.Context
ctxCancel context.CancelFunc
peersLock deadlock.RWMutex
peers []*wsPeer
peersChangeCounter atomic.Int32 // peersChangeCounter is an atomic variable that increases on each change to the peers. It helps avoiding taking the peersLock when checking if the peers list was modified.
broadcaster msgBroadcaster
handler msgHandler
phonebook phonebook.Phonebook
GenesisID string
NetworkID protocol.NetworkID
RandomID string
peerID p2p.PeerID
peerIDSigner identityChallengeSigner
ready atomic.Int32
readyChan chan struct{}
meshUpdateRequests chan meshRequest
// Keep a record of pending outgoing connections so
// we don't start duplicates connection attempts.
// Needs to be locked because it's accessed from the
// meshThread and also threads started to run tryConnect()
tryConnectAddrs map[string]int64
tryConnectLock deadlock.Mutex
incomingMsgFilter *messageFilter // message filter to remove duplicate incoming messages from different peers
eventualReadyDelay time.Duration
relayMessages bool // True if we should relay messages from other nodes (nominally true for relays, false otherwise)
prioScheme NetPrioScheme
prioTracker *prioTracker
prioResponseChan chan *wsPeer
// identity challenge scheme for creating challenges and responding
identityScheme identityChallengeScheme
identityTracker identityTracker
// outgoingMessagesBufferSize is the size used for outgoing messages.
outgoingMessagesBufferSize int
// wsMaxHeaderBytes is the maximum accepted size of the header prior to upgrading to websocket connection.
wsMaxHeaderBytes int64
requestsTracker *RequestTracker
requestsLogger *RequestLogger
// peerStater collects and report peers connectivity telemetry
peerStater peerConnectionStater
// connPerfMonitor is used on outgoing connections to measure their relative message timing
connPerfMonitor *connectionPerformanceMonitor
// lastNetworkAdvanceMu synchronized the access to lastNetworkAdvance
lastNetworkAdvanceMu deadlock.Mutex
// lastNetworkAdvance contains the last timestamp where the agreement protocol was able to make a notable progress.
// it used as a watchdog to help us detect connectivity issues ( such as cliques )
lastNetworkAdvance time.Time
// number of throttled outgoing connections "slots" needed to be populated.
throttledOutgoingConnections atomic.Int32
// transport and dialer are customized to limit the number of
// connection in compliance with connectionsRateLimitingCount.
transport limitcaller.RateLimitingTransport
dialer limitcaller.Dialer
// messagesOfInterest specifies the message types that this node
// wants to receive. nil means default. non-nil causes this
// map to be sent to new peers as a MsgOfInterest message type.
messagesOfInterest map[protocol.Tag]bool
// messagesOfInterestEnc is the encoding of messagesOfInterest,
// to be sent to new peers. This is filled in at network start,
// at which point messagesOfInterestEncoded is set to prevent
// further changes.
messagesOfInterestEnc []byte
messagesOfInterestEncoded bool
messagesOfInterestGeneration atomic.Uint32
// messagesOfInterestMu protects messagesOfInterest and ensures
// that messagesOfInterestEnc does not change once it is set during
// network start.
messagesOfInterestMu deadlock.Mutex
messagesOfInterestRefresh chan struct{}
// peersConnectivityCheckTicker is the timer for testing that all the connected peers
// are still transmitting or receiving information. The channel produced by this ticker
// is consumed by any of the messageHandlerThread(s). The ticker itself is created during
// Start(), and being shut down when Stop() is called.
peersConnectivityCheckTicker *time.Ticker
nodeInfo NodeInfo
// atomic {0:unknown, 1:yes, 2:no}
wantTXGossip atomic.Uint32
// supportedProtocolVersions defines versions supported by this network.
// Should be used instead of a global network.SupportedProtocolVersions for network/peers configuration
supportedProtocolVersions []string
// protocolVersion is an actual version announced as ProtocolVersionHeader
protocolVersion string
// resolveSRVRecords is a function that resolves SRV records for a given service, protocol and name
resolveSRVRecords func(ctx context.Context, service string, protocol string, name string, fallbackDNSResolverAddress string, secure bool) (addrs []string, err error)
}
const (
wantTXGossipUnk = 0
wantTXGossipYes = 1
wantTXGossipNo = 2
)
type broadcastRequest struct {
tags []Tag
data [][]byte
except *wsPeer
done chan struct{}
enqueueTime time.Time
ctx context.Context
}
// msgBroadcaster contains the logic for preparing data for broadcast, managing broadcast priorities
// and queues. It provides a goroutine (broadcastThread) for reading from those queues and scheduling
// broadcasts to peers managed by networkPeerManager.
type msgBroadcaster struct {
ctx context.Context
log logging.Logger
config config.Local
broadcastQueueHighPrio chan broadcastRequest
broadcastQueueBulk chan broadcastRequest
// slowWritingPeerMonitorInterval defines the interval between two consecutive tests for slow peer writing
slowWritingPeerMonitorInterval time.Duration
}
// msgHandler contains the logic for handling incoming messages and managing a readBuffer. It provides
// a goroutine (messageHandlerThread) for reading incoming messages and calling handlers.
type msgHandler struct {
ctx context.Context
log logging.Logger
config config.Local
readBuffer chan IncomingMessage
Multiplexer
}
// networkPeerManager provides the network functionality needed by msgBroadcaster and msgHandler for managing
// peer connectivity, and also sending messages.
type networkPeerManager interface {
// used by msgBroadcaster
peerSnapshot(dest []*wsPeer) ([]*wsPeer, int32)
checkSlowWritingPeers()
getPeersChangeCounter() int32
// used by msgHandler
Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
disconnectThread(badnode DisconnectablePeer, reason disconnectReason)
checkPeersConnectivity()
}
// Address returns a string and whether that is a 'final' address or guessed.
// Part of GossipNode interface
func (wn *WebsocketNetwork) Address() (string, bool) {
parsedURL := url.URL{Scheme: wn.scheme}
var connected bool
if wn.listener == nil {
if wn.config.NetAddress == "" {
parsedURL.Scheme = ""
}
parsedURL.Host = wn.config.NetAddress
connected = false
} else {
parsedURL.Host = wn.listener.Addr().String()
connected = true
}
return parsedURL.String(), connected
}
// PublicAddress what we tell other nodes to connect to.
// Might be different than our locally perceived network address due to NAT/etc.
// Returns config "PublicAddress" if available, otherwise local addr.
func (wn *WebsocketNetwork) PublicAddress() string {
if len(wn.config.PublicAddress) > 0 {
return wn.config.PublicAddress
}
localAddr, _ := wn.Address()
return localAddr
}
// Broadcast sends a message.
// If except is not nil then we will not send it to that neighboring Peer.
// if wait is true then the call blocks until the packet has actually been sent to all neighbors.
func (wn *WebsocketNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error {
dataArray := make([][]byte, 1)
dataArray[0] = data
tagArray := make([]protocol.Tag, 1)
tagArray[0] = tag
return wn.broadcaster.BroadcastArray(ctx, tagArray, dataArray, wait, except)
}
// BroadcastArray sends an array of messages.
// If except is not nil then we will not send it to that neighboring Peer.
// if wait is true then the call blocks until the packet has actually been sent to all neighbors.
// TODO: add `priority` argument so that we don't have to guess it based on tag
func (wn *msgBroadcaster) BroadcastArray(ctx context.Context, tags []protocol.Tag, data [][]byte, wait bool, except Peer) error {
if wn.config.DisableNetworking {
return nil
}
if len(tags) != len(data) {
return errBcastInvalidArray
}
request := broadcastRequest{tags: tags, data: data, enqueueTime: time.Now(), ctx: ctx}
if except != nil {
request.except = except.(*wsPeer)
}
broadcastQueue := wn.broadcastQueueBulk
if highPriorityTag(tags) {
broadcastQueue = wn.broadcastQueueHighPrio
}
if wait {
request.done = make(chan struct{})
select {
case broadcastQueue <- request:
// ok, enqueued
//wn.log.Debugf("broadcast enqueued")
case <-wn.ctx.Done():
return errNetworkClosing
case <-ctx.Done():
return errBcastCallerCancel
}
select {
case <-request.done:
//wn.log.Debugf("broadcast done")
return nil
case <-wn.ctx.Done():
return errNetworkClosing
case <-ctx.Done():
return errBcastCallerCancel
}
}
// no wait
select {
case broadcastQueue <- request:
//wn.log.Debugf("broadcast enqueued nowait")
return nil
default:
wn.log.Debugf("broadcast queue full")
// broadcastQueue full, and we're not going to wait for it.
networkBroadcastQueueFull.Inc(nil)
return errBcastQFull
}
}
// Relay message
func (wn *WebsocketNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error {
if wn.relayMessages {
return wn.Broadcast(ctx, tag, data, wait, except)
}
return nil
}
// RelayArray relays array of messages
func (wn *WebsocketNetwork) RelayArray(ctx context.Context, tags []protocol.Tag, data [][]byte, wait bool, except Peer) error {
if wn.relayMessages {
return wn.broadcaster.BroadcastArray(ctx, tags, data, wait, except)
}
return nil
}
func (wn *WebsocketNetwork) disconnectThread(badnode DisconnectablePeer, reason disconnectReason) {
defer wn.wg.Done()
wn.disconnect(badnode, reason)
}
// Disconnect from a peer, probably due to protocol errors.
func (wn *WebsocketNetwork) Disconnect(node DisconnectablePeer) {
wn.disconnect(node, disconnectBadData)
}
// Disconnect from a peer, probably due to protocol errors.
func (wn *WebsocketNetwork) disconnect(badnode Peer, reason disconnectReason) {
if badnode == nil {
return
}
peer := badnode.(*wsPeer)
peer.CloseAndWait(time.Now().Add(peerDisconnectionAckDuration))
wn.removePeer(peer, reason)
}
func closeWaiter(wg *sync.WaitGroup, peer *wsPeer, deadline time.Time) {
defer wg.Done()
peer.CloseAndWait(deadline)
}
// DisconnectPeers shuts down all connections
func (wn *WebsocketNetwork) DisconnectPeers() {
wn.peersLock.Lock()
defer wn.peersLock.Unlock()
closeGroup := sync.WaitGroup{}
closeGroup.Add(len(wn.peers))
deadline := time.Now().Add(peerDisconnectionAckDuration)
for _, peer := range wn.peers {
go closeWaiter(&closeGroup, peer, deadline)
}
wn.peers = wn.peers[:0]
closeGroup.Wait()
}
// Ready returns a chan that will be closed when we have a minimum number of peer connections active
func (wn *WebsocketNetwork) Ready() chan struct{} {
return wn.readyChan
}
// RegisterHTTPHandler path accepts gorilla/mux path annotations
func (wn *WebsocketNetwork) RegisterHTTPHandler(path string, handler http.Handler) {
wn.router.Handle(path, handler)
}
// RequestConnectOutgoing tries to actually do the connect to new peers.
// `replace` drop all connections first and find new peers.
func (wn *WebsocketNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{}) {
request := meshRequest{disconnect: false}
if quit != nil {
request.done = make(chan struct{})
}
select {
case wn.meshUpdateRequests <- request:
case <-quit:
return
}
if request.done != nil {
select {
case <-request.done:
case <-quit:
}
}
}
// GetPeers returns a snapshot of our Peer list, according to the specified options.
// Peers may be duplicated and refer to the same underlying node.
func (wn *WebsocketNetwork) GetPeers(options ...PeerOption) []Peer {
outPeers := make([]Peer, 0)
for _, option := range options {
switch option {
case PeersConnectedOut:
wn.peersLock.RLock()
for _, peer := range wn.peers {
if peer.outgoing {
outPeers = append(outPeers, Peer(peer))
}
}
wn.peersLock.RUnlock()
case PeersPhonebookRelays:
// return copy of phonebook, which probably also contains peers we're connected to, but if it doesn't maybe we shouldn't be making new connections to those peers (because they disappeared from the directory)
var addrs []string
addrs = wn.phonebook.GetAddresses(1000, phonebook.PhoneBookEntryRelayRole)
for _, addr := range addrs {
client, _ := wn.GetHTTPClient(addr)
peerCore := makePeerCore(wn.ctx, wn, wn.log, wn.handler.readBuffer, addr, client, "" /*origin address*/)
outPeers = append(outPeers, &peerCore)
}
case PeersPhonebookArchivalNodes:
var addrs []string
addrs = wn.phonebook.GetAddresses(1000, phonebook.PhoneBookEntryArchivalRole)
for _, addr := range addrs {
client, _ := wn.GetHTTPClient(addr)
peerCore := makePeerCore(wn.ctx, wn, wn.log, wn.handler.readBuffer, addr, client, "" /*origin address*/)
outPeers = append(outPeers, &peerCore)
}
case PeersConnectedIn:
wn.peersLock.RLock()
for _, peer := range wn.peers {
if !peer.outgoing {
outPeers = append(outPeers, Peer(peer))
}
}
wn.peersLock.RUnlock()
}
}
return outPeers
}
func (wn *WebsocketNetwork) setup() {
var preferredResolver dnssec.ResolverIf
if wn.config.DNSSecurityRelayAddrEnforced() {
preferredResolver = dnssec.MakeDefaultDnssecResolver(wn.config.FallbackDNSResolverAddress, wn.log)
}
if wn.nodeInfo == nil {
wn.nodeInfo = &nopeNodeInfo{}
}
maxIdleConnsPerHost := int(wn.config.ConnectionsRateLimitingCount)
wn.dialer = limitcaller.MakeRateLimitingDialer(wn.phonebook, preferredResolver)
wn.transport = limitcaller.MakeRateLimitingTransport(wn.phonebook, limitcaller.DefaultQueueingTimeout, &wn.dialer, maxIdleConnsPerHost)
wn.upgrader.ReadBufferSize = 4096
wn.upgrader.WriteBufferSize = 4096
wn.upgrader.EnableCompression = false
wn.router = mux.NewRouter()
if wn.config.EnableGossipService {
wn.router.Handle(GossipNetworkPath, wn)
}
wn.requestsTracker = makeRequestsTracker(wn.router, wn.log, wn.config)
if wn.config.EnableRequestLogger {
wn.requestsLogger = makeRequestLogger(wn.requestsTracker, wn.log)
wn.server.Handler = wn.requestsLogger
} else {
wn.server.Handler = wn.requestsTracker
}
wn.server.ReadHeaderTimeout = httpServerReadHeaderTimeout
wn.server.WriteTimeout = httpServerWriteTimeout
wn.server.IdleTimeout = httpServerIdleTimeout
wn.server.MaxHeaderBytes = httpServerMaxHeaderBytes
wn.ctx, wn.ctxCancel = context.WithCancel(context.Background())
wn.relayMessages = wn.config.IsGossipServer() || wn.config.ForceRelayMessages
if wn.relayMessages || wn.config.ForceFetchTransactions {
wn.wantTXGossip.Store(wantTXGossipYes)
}
// roughly estimate the number of messages that could be seen at any given moment.
// For the late/redo/down committee, which happen in parallel, we need to allocate
// extra space there.
wn.outgoingMessagesBufferSize = outgoingMessagesBufferSize
wn.wsMaxHeaderBytes = wsMaxHeaderBytes
wn.identityTracker = NewIdentityTracker()
wn.broadcaster = msgBroadcaster{
ctx: wn.ctx,
log: wn.log,
config: wn.config,
broadcastQueueHighPrio: make(chan broadcastRequest, wn.outgoingMessagesBufferSize),
broadcastQueueBulk: make(chan broadcastRequest, 100),
}
if wn.broadcaster.slowWritingPeerMonitorInterval == 0 {
wn.broadcaster.slowWritingPeerMonitorInterval = slowWritingPeerMonitorInterval
}
wn.meshUpdateRequests = make(chan meshRequest, 5)
wn.readyChan = make(chan struct{})
wn.tryConnectAddrs = make(map[string]int64)
wn.eventualReadyDelay = time.Minute
wn.prioTracker = newPrioTracker(wn)
readBufferLen := wn.config.IncomingConnectionsLimit + wn.config.GossipFanout
if readBufferLen < 100 {
readBufferLen = 100
}
if readBufferLen > 10000 {
readBufferLen = 10000
}
wn.handler = msgHandler{
ctx: wn.ctx,
log: wn.log,
config: wn.config,
readBuffer: make(chan IncomingMessage, readBufferLen),
}
var rbytes [10]byte
crypto.RandBytes(rbytes[:])
wn.RandomID = base64.StdEncoding.EncodeToString(rbytes[:])
if wn.config.EnableIncomingMessageFilter {
wn.incomingMsgFilter = makeMessageFilter(wn.config.IncomingMessageFilterBucketCount, wn.config.IncomingMessageFilterBucketSize)
}
wn.connPerfMonitor = makeConnectionPerformanceMonitor([]Tag{protocol.AgreementVoteTag, protocol.TxnTag})
wn.lastNetworkAdvance = time.Now().UTC()
// set our supported versions
if wn.config.NetworkProtocolVersion != "" {
wn.supportedProtocolVersions = []string{wn.config.NetworkProtocolVersion}
} else {
wn.supportedProtocolVersions = SupportedProtocolVersions
}
// set our actual version
wn.protocolVersion = ProtocolVersion
wn.messagesOfInterestRefresh = make(chan struct{}, 2)
wn.messagesOfInterestGeneration.Store(1) // something nonzero so that any new wsPeer needs updating
if wn.relayMessages {
wn.registerMessageInterest(protocol.StateProofSigTag)
}
}
// Start makes network connections and threads
func (wn *WebsocketNetwork) Start() error {
wn.messagesOfInterestMu.Lock()
defer wn.messagesOfInterestMu.Unlock()
wn.messagesOfInterestEncoded = true
if wn.messagesOfInterest != nil {
wn.messagesOfInterestEnc = MarshallMessageOfInterestMap(wn.messagesOfInterest)
}
if wn.config.IsGossipServer() {
listener, err := net.Listen("tcp", wn.config.NetAddress)
if err != nil {
wn.log.Errorf("network could not listen %v: %s", wn.config.NetAddress, err)
return err
}
// wrap the original listener with a limited connection listener
listener = limitlistener.RejectingLimitListener(
listener, uint64(wn.config.IncomingConnectionsLimit)+ReservedHealthServiceConnections, wn.log)
// wrap the limited connection listener with a requests tracker listener
wn.listener = wn.requestsTracker.Listener(listener)
wn.log.Debugf("listening on %s", wn.listener.Addr().String())
wn.throttledOutgoingConnections.Store(int32(wn.config.GossipFanout / 2))
} else {
// on non-relay, all the outgoing connections are throttled.
wn.throttledOutgoingConnections.Store(int32(wn.config.GossipFanout))
}
if wn.config.DisableOutgoingConnectionThrottling {
wn.throttledOutgoingConnections.Store(0)
}
if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" {
wn.scheme = "https"
} else {
wn.scheme = "http"
}
// if PublicAddress set to testing, pull the name from Address()
if wn.config.PublicAddress == testingPublicAddress {
addr, ok := wn.Address()
if ok {
url, err := url.Parse(addr)
if err == nil {
wn.config.PublicAddress = fmt.Sprintf("%s:%s", url.Hostname(), url.Port())
}
}
}
// if the network has a public address or a libp2p peer ID, use that as the name for connection deduplication
if wn.config.PublicAddress != "" || (wn.peerID != "" && wn.peerIDSigner != nil) {
wn.RegisterHandlers(identityHandlers)
}
if wn.identityScheme == nil {
if wn.peerID != "" && wn.peerIDSigner != nil {
wn.identityScheme = NewIdentityChallengeSchemeWithSigner(string(wn.peerID), wn.peerIDSigner)
}
if wn.config.PublicAddress != "" {
wn.identityScheme = NewIdentityChallengeScheme(wn.config.PublicAddress)
}
}
wn.meshUpdateRequests <- meshRequest{false, nil}
if wn.prioScheme != nil {
wn.RegisterHandlers(prioHandlers)
}
if wn.listener != nil {
wn.wg.Add(1)
go wn.httpdThread()
}
wn.wg.Add(1)
go wn.meshThread()
// we shouldn't have any ticker here.. but in case we do - just stop it.
if wn.peersConnectivityCheckTicker != nil {
wn.peersConnectivityCheckTicker.Stop()
}
wn.peersConnectivityCheckTicker = time.NewTicker(connectionActivityMonitorInterval)
for i := 0; i < incomingThreads; i++ {
wn.wg.Add(1)
// We pass the peersConnectivityCheckTicker.C here so that we don't need to syncronize the access to the ticker's data structure.
go wn.handler.messageHandlerThread(&wn.wg, wn.peersConnectivityCheckTicker.C, wn, "network", "WebsocketNetwork")
}
wn.wg.Add(1)
go wn.broadcaster.broadcastThread(&wn.wg, wn, "network", "WebsocketNetwork")
if wn.prioScheme != nil {
wn.wg.Add(1)
go wn.prioWeightRefresh()
}
go wn.postMessagesOfInterestThread()
wn.log.Infof("serving genesisID=%s on %#v with RandomID=%s", wn.GenesisID, wn.PublicAddress(), wn.RandomID)
return nil
}
func (wn *WebsocketNetwork) httpdThread() {
defer wn.wg.Done()
var err error
if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" {
err = wn.server.ServeTLS(wn.listener, wn.config.TLSCertFile, wn.config.TLSKeyFile)
} else {
err = wn.server.Serve(wn.listener)
}
if err == http.ErrServerClosed {
} else if err != nil {
wn.log.Info("ws net http server exited ", err)
}
}
// innerStop context for shutting down peers
func (wn *WebsocketNetwork) innerStop() {
wn.peersLock.Lock()
defer wn.peersLock.Unlock()
wn.wg.Add(len(wn.peers))
// this method is called only during node shutdown. In this case, we want to send the
// shutdown message, but we don't want to wait for a long time - since we might not be lucky
// to get a response.
deadline := time.Now().Add(peerShutdownDisconnectionAckDuration)
for _, peer := range wn.peers {
go closeWaiter(&wn.wg, peer, deadline)
}
wn.peers = wn.peers[:0]
}
// Stop closes network connections and stops threads.
// Stop blocks until all activity on this node is done.
func (wn *WebsocketNetwork) Stop() {
wn.log.Debug("network is stopping")
defer wn.log.Debug("network has stopped")
wn.handler.ClearHandlers([]Tag{})
// if we have a working ticker, just stop it and clear it out. The access to this variable is safe since the Start()/Stop() are synced by the
// caller, and the WebsocketNetwork doesn't access wn.peersConnectivityCheckTicker directly.
if wn.peersConnectivityCheckTicker != nil {
wn.peersConnectivityCheckTicker.Stop()
wn.peersConnectivityCheckTicker = nil
}
wn.innerStop()
var listenAddr string
if wn.listener != nil {
listenAddr = wn.listener.Addr().String()
}
wn.ctxCancel()
ctx, timeoutCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer timeoutCancel()
err := wn.server.Shutdown(ctx)
if err != nil {
wn.log.Warnf("problem shutting down %s: %v", listenAddr, err)
}
wn.wg.Wait()
if wn.listener != nil {
wn.log.Debugf("closed %s", listenAddr)
}
// Wait for the requestsTracker to finish up to avoid potential race condition
<-wn.requestsTracker.getWaitUntilNoConnectionsChannel(5 * time.Millisecond)
wn.messagesOfInterestMu.Lock()
defer wn.messagesOfInterestMu.Unlock()
wn.messagesOfInterestEncoded = false
wn.messagesOfInterestEnc = nil
wn.messagesOfInterest = nil
}
// RegisterHandlers registers the set of given message handlers.
func (wn *WebsocketNetwork) RegisterHandlers(dispatch []TaggedMessageHandler) {
wn.handler.RegisterHandlers(dispatch)
}
// ClearHandlers deregisters all the existing message handlers.
func (wn *WebsocketNetwork) ClearHandlers() {
// exclude the internal handlers. These would get cleared out when Stop is called.
wn.handler.ClearHandlers([]Tag{protocol.PingTag, protocol.PingReplyTag, protocol.NetPrioResponseTag})
}
// RegisterProcessors registers the set of given message handlers.
func (wn *WebsocketNetwork) RegisterProcessors(dispatch []TaggedMessageProcessor) {
}
// ClearProcessors deregisters all the existing message handlers.
func (wn *WebsocketNetwork) ClearProcessors() {
}
func (wn *WebsocketNetwork) setHeaders(header http.Header) {
localTelemetryGUID := wn.log.GetTelemetryGUID()
localInstanceName := wn.log.GetInstanceName()
header.Set(TelemetryIDHeader, localTelemetryGUID)
header.Set(InstanceNameHeader, localInstanceName)
header.Set(AddressHeader, wn.PublicAddress())
header.Set(NodeRandomHeader, wn.RandomID)
}
// checkServerResponseVariables check that the version and random-id in the request headers matches the server ones.
// it returns true if it's a match, and false otherwise.
func (wn *WebsocketNetwork) checkServerResponseVariables(otherHeader http.Header, addr string) (bool, string) {
matchingVersion, otherVersion := wn.checkProtocolVersionMatch(otherHeader)
if matchingVersion == "" {
wn.log.Info(filterASCII(fmt.Sprintf("new peer %s version mismatch, mine=%v theirs=%s, headers %#v", addr, wn.supportedProtocolVersions, otherVersion, otherHeader)))
return false, ""
}
otherRandom := otherHeader.Get(NodeRandomHeader)
if otherRandom == wn.RandomID || otherRandom == "" {
// This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out.
if otherRandom == "" {
// missing header.
wn.log.Warn(filterASCII(fmt.Sprintf("new peer %s did not include random ID header in request. mine=%s headers %#v", addr, wn.RandomID, otherHeader)))
} else {
wn.log.Debugf("new peer %s has same node random id, am I talking to myself? %s", addr, wn.RandomID)
}
return false, ""
}
otherGenesisID := otherHeader.Get(GenesisHeader)
if wn.GenesisID != otherGenesisID {
if otherGenesisID != "" {
wn.log.Warn(filterASCII(fmt.Sprintf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", addr, wn.GenesisID, otherGenesisID, otherHeader)))
} else {
wn.log.Warnf("new peer %#v did not include genesis header in response. mine=%#v headers %#v", addr, wn.GenesisID, otherHeader)
}
return false, ""
}
return true, matchingVersion
}
// getCommonHeaders retreives the common headers for both incoming and outgoing connections from the provided headers.
func getCommonHeaders(headers http.Header) (otherTelemetryGUID, otherInstanceName, otherPublicAddr string) {
otherTelemetryGUID = logging.SanitizeTelemetryString(headers.Get(TelemetryIDHeader), 1)
otherInstanceName = logging.SanitizeTelemetryString(headers.Get(InstanceNameHeader), 2)
otherPublicAddr = logging.SanitizeTelemetryString(headers.Get(AddressHeader), 1)
return
}
// checkIncomingConnectionLimits perform the connection limits counting for the incoming connections.
func (wn *WebsocketNetwork) checkIncomingConnectionLimits(response http.ResponseWriter, request *http.Request, remoteHost, otherTelemetryGUID, otherInstanceName string) int {
if wn.numIncomingPeers() >= wn.config.IncomingConnectionsLimit {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_limit"})
wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent,
telemetryspec.ConnectPeerFailEventDetails{
Address: remoteHost,
TelemetryGUID: otherTelemetryGUID,
Incoming: true,
InstanceName: otherInstanceName,
Reason: "Connection Limit",
})
response.WriteHeader(http.StatusServiceUnavailable)
return http.StatusServiceUnavailable
}
totalConnections := wn.connectedForIP(remoteHost)
if totalConnections >= wn.config.MaxConnectionsPerIP {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_per_ip_limit"})
wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent,
telemetryspec.ConnectPeerFailEventDetails{
Address: remoteHost,
TelemetryGUID: otherTelemetryGUID,
Incoming: true,
InstanceName: otherInstanceName,
Reason: "Remote IP Connection Limit",
})
response.WriteHeader(http.StatusServiceUnavailable)
return http.StatusServiceUnavailable
}
return http.StatusOK
}
// checkProtocolVersionMatch test ProtocolAcceptVersionHeader and ProtocolVersionHeader headers from the request/response and see if it can find a match.
func (wn *WebsocketNetwork) checkProtocolVersionMatch(otherHeaders http.Header) (matchingVersion string, otherVersion string) {
otherAcceptedVersions := otherHeaders[textproto.CanonicalMIMEHeaderKey(ProtocolAcceptVersionHeader)]
for _, otherAcceptedVersion := range otherAcceptedVersions {
// do we have a matching version ?
for _, supportedProtocolVersion := range wn.supportedProtocolVersions {
if supportedProtocolVersion == otherAcceptedVersion {
matchingVersion = supportedProtocolVersion
return matchingVersion, ""
}
}
}
otherVersion = otherHeaders.Get(ProtocolVersionHeader)
for _, supportedProtocolVersion := range wn.supportedProtocolVersions {
if supportedProtocolVersion == otherVersion {
return supportedProtocolVersion, otherVersion
}
}
return "", filterASCII(otherVersion)
}
// checkIncomingConnectionVariables checks the variables that were provided on the request, and compares them to the
// local server supported parameters. If all good, it returns http.StatusOK; otherwise, it write the error to the ResponseWriter
// and returns the http status.
func (wn *WebsocketNetwork) checkIncomingConnectionVariables(response http.ResponseWriter, request *http.Request, remoteAddrForLogging string) int {
// check to see that the genesisID in the request URI is valid and matches the supported one.
pathVars := mux.Vars(request)
otherGenesisID, hasGenesisID := pathVars["genesisID"]
if !hasGenesisID || otherGenesisID == "" {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "missing genesis-id"})
response.WriteHeader(http.StatusNotFound)
return http.StatusNotFound
}
if wn.GenesisID != otherGenesisID {
wn.log.Warn(filterASCII(fmt.Sprintf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", remoteAddrForLogging, wn.GenesisID, otherGenesisID, request.Header)))
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "mismatching genesis-id"})
response.WriteHeader(http.StatusPreconditionFailed)
n, err := response.Write([]byte("mismatching genesis ID"))
if err != nil {
wn.log.Warnf("ws failed to write mismatching genesis ID response '%s' : n = %d err = %v", otherGenesisID, n, err)
}