-
Notifications
You must be signed in to change notification settings - Fork 11
/
tuna.go
1779 lines (1550 loc) · 46.4 KB
/
tuna.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
package tuna
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nknorg/nkn-sdk-go"
"github.com/nknorg/nkn/v2/common"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/crypto/ed25519"
"github.com/nknorg/nkn/v2/transaction"
"github.com/nknorg/nkn/v2/util"
"github.com/nknorg/nkn/v2/util/address"
"github.com/nknorg/nkn/v2/vault"
"github.com/nknorg/tuna/filter"
"github.com/nknorg/tuna/geo"
"github.com/nknorg/tuna/pb"
"github.com/nknorg/tuna/storage"
"github.com/nknorg/tuna/types"
tunaUtil "github.com/nknorg/tuna/util"
"github.com/xtaci/smux"
"golang.org/x/crypto/nacl/box"
"google.golang.org/protobuf/proto"
// blank import to prevent gomobile from being removed by go mod tidy and
// causing gomobile compile error
_ "golang.org/x/mobile/asset"
)
const (
TrafficUnit = 1024 * 1024
tcp4 = "tcp"
udp4 = "udp"
trafficPaymentThreshold = 32
maxTrafficUnpaid = 1
minTrafficCoverage = 0.9
trafficDelay = 10 * time.Second
maxNanoPayDelay = 30 * time.Second
subscribeDurationRandomFactor = 0.1
measureBandwidthTopCount = 8
measureDelayTopDelayCount = 32
pipeBufferSize = 4096 // should be <= 4096 to be compatible with c++ smux
maxConnMetadataSize = 1024
maxStreamMetadataSize = 1024
maxServiceMetadataSize = 4096
maxNanoPayTxnSize = 4096
numRPCClients = 4
maxRPCRequests = 8
)
var (
// This lock makes sure that only one measurement can run at the same time if
// measurement storage is set so that later measurement can take use of the
// previous measurement results.
measureStorageMutex sync.Mutex
)
type ServiceInfo struct {
MaxPrice string `json:"maxPrice"`
ListenIP string `json:"listenIP"`
IPFilter *geo.IPFilter `json:"ipFilter"`
NknFilter *filter.NknFilter `json:"nknFilter"`
}
type Service struct {
Name string `json:"name"`
TCP []uint32 `json:"tcp"`
UDP []uint32 `json:"udp"`
UDPBufferSize int `json:"udpBufferSize"`
Encryption string `json:"encryption"`
}
type Common struct {
Service *Service
ServiceInfo *ServiceInfo
Wallet *nkn.Wallet
Client *nkn.MultiClient
DialTimeout int32
SubscriptionPrefix string
Reverse bool
ReverseMetadata *pb.ServiceMetadata
OnConnect *OnConnect
IsServer bool
GeoDBPath string
DownloadGeoDB bool
GetSubscribersBatchSize int
MeasureBandwidth bool
MeasureBandwidthTimeout time.Duration
MeasureBandwidthWorkersTimeout time.Duration
MeasurementBytesDownLink int32
MeasureStoragePath string
MaxPoolSize int32
TcpDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
HttpDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
WsDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
udpReadChan chan []byte
udpWriteChan chan []byte
udpCloseChan chan struct{}
tcpListener *net.TCPListener
curveSecretKey *[sharedKeySize]byte
encryptionAlgo pb.EncryptionAlgo
closeChan chan struct{}
measureStorage *storage.MeasureStorage
sortMeasuredNodes func(types.Nodes)
measureDelayConcurrentWorkers int
measureBandwidthConcurrentWorkers int
sessionsWaitGroup *sync.WaitGroup
sync.RWMutex
udpReadWriteChanLock sync.RWMutex
paymentReceiver string
entryToExitPrice common.Fixed64
exitToEntryPrice common.Fixed64
metadata *pb.ServiceMetadata
connected bool
tcpConn net.Conn
udpConn *EncryptUDPConn
isClosed bool
sharedKeys map[string]*[sharedKeySize]byte
encryptKeys sync.Map
remoteNknAddress string
activeSessions int
linger time.Duration
presetNode *types.Node
connReadyChan sync.Map
reverseBytesExitToEntry map[string][]uint64
reverseBytesEntryToExit map[string][]uint64
minBalance common.Fixed64 // minimum wallet balance requirement for connecting
}
func NewCommon(
service *Service,
serviceInfo *ServiceInfo,
wallet *nkn.Wallet,
client *nkn.MultiClient,
seedRPCServerAddr []string,
dialTimeout int32,
subscriptionPrefix string,
reverse, isServer bool,
geoDBPath string,
downloadGeoDB bool,
getSubscribersBatchSize int32,
measureBandwidth bool,
measureBandwidthTimeout int32,
measureBandwidthWorkersTimeout int32,
measurementBytes int32,
measureStoragePath string,
maxPoolSize int32,
tcpDialContext func(ctx context.Context, network, addr string) (net.Conn, error),
httpDialContext func(ctx context.Context, network, addr string) (net.Conn, error),
wsDialContext func(ctx context.Context, network, addr string) (net.Conn, error),
sortMeasuredNodes func(types.Nodes),
reverseMetadata *pb.ServiceMetadata,
minBalance string,
) (*Common, error) {
encryptionAlgo := defaultEncryptionAlgo
var err error
if service != nil && len(service.Encryption) > 0 {
encryptionAlgo, err = ParseEncryptionAlgo(service.Encryption)
if err != nil {
return nil, err
}
}
if client == nil {
clientConfig := &nkn.ClientConfig{
HttpDialContext: httpDialContext,
WsDialContext: wsDialContext,
}
if len(seedRPCServerAddr) > 0 {
clientConfig.SeedRPCServerAddr = nkn.NewStringArray(seedRPCServerAddr...)
}
client, err = nkn.NewMultiClient(wallet.Account(), randomIdentifier(), numRPCClients, false, clientConfig)
if err != nil {
return nil, err
}
}
var sk [ed25519.PrivateKeySize]byte
copy(sk[:], ed25519.GetPrivateKeyFromSeed(wallet.Seed()))
curveSecretKey := ed25519.PrivateKeyToCurve25519PrivateKey(&sk)
measureDelayConcurrentWorkers := defaultMeasureDelayConcurrentWorkers
if measureDelayConcurrentWorkers > int(maxPoolSize) {
measureDelayConcurrentWorkers = int(maxPoolSize)
}
measureBandwidthConcurrentWorkers := defaultMeasureBandwidthConcurrentWorkers
if measureBandwidthConcurrentWorkers > int(maxPoolSize) {
measureBandwidthConcurrentWorkers = int(maxPoolSize)
}
var wg sync.WaitGroup
c := &Common{
Service: service,
ServiceInfo: serviceInfo,
Wallet: wallet,
Client: client,
DialTimeout: dialTimeout,
SubscriptionPrefix: subscriptionPrefix,
Reverse: reverse,
ReverseMetadata: reverseMetadata,
OnConnect: NewOnConnect(1, nil),
IsServer: isServer,
GeoDBPath: geoDBPath,
DownloadGeoDB: downloadGeoDB,
GetSubscribersBatchSize: int(getSubscribersBatchSize),
MeasureBandwidth: measureBandwidth,
MeasureBandwidthTimeout: time.Duration(measureBandwidthTimeout) * time.Second,
MeasureBandwidthWorkersTimeout: time.Duration(measureBandwidthWorkersTimeout) * time.Second,
MeasurementBytesDownLink: measurementBytes,
MeasureStoragePath: measureStoragePath,
MaxPoolSize: maxPoolSize,
TcpDialContext: tcpDialContext,
HttpDialContext: httpDialContext,
WsDialContext: wsDialContext,
curveSecretKey: curveSecretKey,
encryptionAlgo: encryptionAlgo,
closeChan: make(chan struct{}),
udpCloseChan: make(chan struct{}),
sharedKeys: make(map[string]*[sharedKeySize]byte),
measureDelayConcurrentWorkers: measureDelayConcurrentWorkers,
measureBandwidthConcurrentWorkers: measureBandwidthConcurrentWorkers,
sortMeasuredNodes: sortMeasuredNodes,
sessionsWaitGroup: &wg,
reverseBytesEntryToExit: make(map[string][]uint64),
reverseBytesExitToEntry: make(map[string][]uint64),
udpReadChan: make(chan []byte, 64),
udpWriteChan: make(chan []byte, 64),
}
c.minBalance, err = common.StringToFixed64(minBalance)
if err != nil {
return nil, err
}
if !c.IsServer && c.ServiceInfo.IPFilter.NeedGeoInfo() {
c.ServiceInfo.IPFilter.AddProvider(c.DownloadGeoDB, c.GeoDBPath)
}
if !c.IsServer && c.MeasureStoragePath != "" {
c.measureStorage = storage.NewMeasureStorage(c.MeasureStoragePath, c.SubscriptionPrefix+c.Service.Name)
}
return c, nil
}
func (c *Common) GetTCPConn() net.Conn {
c.RLock()
defer c.RUnlock()
return c.tcpConn
}
func (c *Common) SetServerTCPConn(conn net.Conn) {
c.Lock()
defer c.Unlock()
c.tcpConn = conn
}
func (c *Common) GetUDPConn() *EncryptUDPConn {
c.RLock()
defer c.RUnlock()
return c.udpConn
}
func (c *Common) SetServerUDPConn(conn *EncryptUDPConn) {
c.Lock()
defer c.Unlock()
c.udpConn = conn
}
func (c *Common) GetConnected() bool {
c.RLock()
defer c.RUnlock()
return c.connected
}
func (c *Common) SetConnected(connected bool) {
c.Lock()
defer c.Unlock()
c.connected = connected
}
func (c *Common) GetServerTCPConn(force bool) (net.Conn, error) {
err := c.CreateServerConn(force)
if err != nil {
return nil, err
}
conn := c.GetTCPConn()
if conn == nil {
return nil, errors.New("nil tcp connection")
}
return conn, nil
}
func (c *Common) GetServerUDPConn(force bool) (UDPConn, error) {
err := c.CreateServerConn(force)
if err != nil {
return nil, err
}
return c.GetUDPConn(), nil
}
func (c *Common) SetServerUDPReadChan(udpReadChan chan []byte) {
c.udpReadChan = udpReadChan
}
func (c *Common) SetServerUDPWriteChan(udpWriteChan chan []byte) {
c.udpWriteChan = udpWriteChan
}
func (c *Common) GetServerUDPReadChan(force bool) (chan []byte, error) {
c.udpReadWriteChanLock.Lock()
defer c.udpReadWriteChanLock.Unlock()
err := c.CreateServerConn(force)
if err != nil {
return nil, err
}
return c.udpReadChan, nil
}
func (c *Common) GetServerUDPWriteChan(force bool) (chan []byte, error) {
c.udpReadWriteChanLock.Lock()
defer c.udpReadWriteChanLock.Unlock()
err := c.CreateServerConn(force)
if err != nil {
return nil, err
}
return c.udpWriteChan, nil
}
func (c *Common) GetMetadata() *pb.ServiceMetadata {
c.RLock()
defer c.RUnlock()
return c.metadata
}
func (c *Common) SetMetadata(metadata *pb.ServiceMetadata) {
c.Lock()
defer c.Unlock()
c.metadata = metadata
}
func (c *Common) GetRemoteNknAddress() string {
c.RLock()
defer c.RUnlock()
return c.remoteNknAddress
}
func (c *Common) SetRemoteNknAddress(nknAddr string) {
c.Lock()
c.remoteNknAddress = nknAddr
c.Unlock()
}
func (c *Common) GetPaymentReceiver() string {
c.RLock()
defer c.RUnlock()
return c.paymentReceiver
}
func (c *Common) SetPaymentReceiver(paymentReceiver string) error {
if len(paymentReceiver) > 0 {
if err := nkn.VerifyWalletAddress(paymentReceiver); err != nil {
return err
}
}
c.Lock()
defer c.Unlock()
c.paymentReceiver = paymentReceiver
return nil
}
func (c *Common) GetPrice() (common.Fixed64, common.Fixed64) {
c.Lock()
defer c.Unlock()
return c.entryToExitPrice, c.exitToEntryPrice
}
func (c *Common) startUDPReaderWriter(conn *EncryptUDPConn, toAddr *net.UDPAddr, in *uint64, out *uint64) {
from := new(net.UDPAddr)
n := 0
encrypted := false
var err error
addrToKey := new(sync.Map)
go func() {
buffer := make([]byte, MaxUDPBufferSize)
for {
if c.isClosed {
return
}
n, from, encrypted, err = conn.ReadFromUDPEncrypted(buffer)
if err != nil {
log.Println("Couldn't receive data:", err)
if errors.Is(err, io.ErrClosedPipe) {
return
}
}
if bytes.Equal(buffer[:PrefixLen], []byte{PrefixLen - 1: 0}) && c.IsServer && n > PrefixLen {
connMetadata, err := parseUDPConnMetadata(buffer[PrefixLen:n])
if err != nil {
log.Println("Couldn't read udp metadata from client:", err)
continue
}
if connMetadata.IsPing || encrypted {
continue
}
connKey := string(append(connMetadata.PublicKey, connMetadata.Nonce...))
readyChan, _ := c.connReadyChan.LoadOrStore(connKey, make(chan struct{}, 1))
<-readyChan.(chan struct{})
encryptKey, ok := c.encryptKeys.Load(connKey)
if !ok {
log.Println("no encrypt key found")
continue
}
k := encryptKey.(*[encryptKeySize]byte)
err = conn.AddCodec(from, k, connMetadata.EncryptionAlgo, false)
if err != nil {
log.Println(err)
continue
}
if in == nil && out == nil {
k := string(append(connMetadata.PublicKey, connMetadata.Nonce...))
addrToKey.Store(from.String(), k)
}
continue
}
if !encrypted {
log.Println("Unencrypted udp packet received")
continue
}
if n > 0 {
b := make([]byte, n)
copy(b, buffer[:n])
c.udpReadChan <- b
if in != nil {
atomic.AddUint64(in, uint64(n))
} else {
k, ok := addrToKey.Load(from.String())
if ok {
atomic.AddUint64(&c.reverseBytesEntryToExit[k.(string)][b[2]], uint64(n))
}
}
}
}
}()
go func() {
for {
if c.isClosed {
return
}
to := toAddr
select {
case data := <-c.udpWriteChan:
if conn.RemoteAddr() == nil && from != nil && toAddr == nil {
to = from
}
n, _, err := conn.WriteMsgUDP(data, nil, to)
if err != nil {
log.Println("Couldn't send data to server:", err)
continue
}
if out != nil {
atomic.AddUint64(out, uint64(n))
} else {
k, ok := addrToKey.Load(from.String())
if ok {
atomic.AddUint64(&c.reverseBytesExitToEntry[k.(string)][data[2]], uint64(n))
}
}
case <-c.udpCloseChan:
return
}
}
}()
}
func (c *Common) getOrComputeSharedKey(remotePublicKey []byte) (*[sharedKeySize]byte, error) {
c.RLock()
sharedKey, ok := c.sharedKeys[string(remotePublicKey)]
c.RUnlock()
if ok && sharedKey != nil {
return sharedKey, nil
}
var pk [ed25519.PublicKeySize]byte
copy(pk[:], remotePublicKey)
curve25519PublicKey, ok := ed25519.PublicKeyToCurve25519PublicKey(&pk)
if !ok {
return nil, errors.New("invalid public key")
}
sharedKey = new([sharedKeySize]byte)
box.Precompute(sharedKey, curve25519PublicKey, c.curveSecretKey)
c.Lock()
c.sharedKeys[string(remotePublicKey)] = sharedKey
c.Unlock()
return sharedKey, nil
}
func (c *Common) wrapConn(conn net.Conn, remotePublicKey []byte, localConnMetadata *pb.ConnectionMetadata) (net.Conn, *pb.ConnectionMetadata, error) {
var connNonce []byte
var encryptionAlgo pb.EncryptionAlgo
var remoteConnMetadata *pb.ConnectionMetadata
if localConnMetadata == nil {
localConnMetadata = &pb.ConnectionMetadata{}
} else {
connMetadataCopy := *localConnMetadata
localConnMetadata = &connMetadataCopy
}
err := conn.SetDeadline(time.Now().Add(10 * time.Second))
if err != nil {
return nil, nil, err
}
defer conn.SetDeadline(time.Time{})
if len(remotePublicKey) > 0 {
encryptionAlgo = c.encryptionAlgo
localConnMetadata.EncryptionAlgo = encryptionAlgo
localConnMetadata.PublicKey = c.Wallet.PubKey()
err := writeConnMetadata(conn, localConnMetadata)
if err != nil {
return nil, nil, err
}
remoteConnMetadata, err = readConnMetadata(conn)
if err != nil {
return nil, nil, err
}
if !bytes.Equal(remoteConnMetadata.PublicKey, remotePublicKey) {
return nil, nil, fmt.Errorf("public key mismatch")
}
connNonce = remoteConnMetadata.Nonce
} else {
connNonce = util.RandomBytes(connNonceSize)
localConnMetadata.Nonce = connNonce
localConnMetadata.PublicKey = c.Wallet.PubKey()
err := writeConnMetadata(conn, localConnMetadata)
if err != nil {
return nil, nil, err
}
remoteConnMetadata, err = readConnMetadata(conn)
if err != nil {
return nil, nil, err
}
remoteConnMetadata.Nonce = connNonce
if len(remoteConnMetadata.PublicKey) != ed25519.PublicKeySize {
return nil, nil, fmt.Errorf("invalid pubkey size %d", len(remoteConnMetadata.PublicKey))
}
encryptionAlgo = remoteConnMetadata.EncryptionAlgo
remotePublicKey = remoteConnMetadata.PublicKey
}
k := string(append(remotePublicKey, connNonce...))
encryptKey := new([encryptKeySize]byte)
if encryptionAlgo != pb.EncryptionAlgo_ENCRYPTION_NONE {
sharedKey, err := c.getOrComputeSharedKey(remotePublicKey)
if err != nil {
return nil, nil, err
}
encryptKey = computeEncryptKey(connNonce, sharedKey[:])
}
c.encryptKeys.Store(k, encryptKey)
if c.IsServer {
readyChan, _ := c.connReadyChan.LoadOrStore(k, make(chan struct{}, 1))
select {
case readyChan.(chan struct{}) <- struct{}{}:
default:
}
}
if encryptionAlgo == pb.EncryptionAlgo_ENCRYPTION_NONE {
return conn, remoteConnMetadata, nil
}
encryptedConn, err := encryptConn(conn, encryptKey, encryptionAlgo, len(remotePublicKey) > 0)
if err != nil {
return nil, nil, err
}
return encryptedConn, remoteConnMetadata, nil
}
func (c *Common) wrapUDPConn(conn UDPConn, addr *net.UDPAddr, remotePublicKey []byte, connNonce []byte) (*EncryptUDPConn, error) {
localConnMetadata := new(pb.ConnectionMetadata)
var err error
var encryptionAlgo pb.EncryptionAlgo
encConn := new(EncryptUDPConn)
encryptionAlgo = c.encryptionAlgo
conn.SetWriteBuffer(MaxUDPBufferSize)
conn.SetReadBuffer(MaxUDPBufferSize)
if c.IsServer {
encConn = conn.(*EncryptUDPConn)
} else {
encConn = NewEncryptUDPConn(conn.(*net.UDPConn))
}
if len(remotePublicKey) > 0 {
localConnMetadata.EncryptionAlgo = c.encryptionAlgo
localConnMetadata.PublicKey = c.Wallet.PubKey()
localConnMetadata.Nonce = connNonce
for i := 0; i < 3; i++ {
err = writeUDPConnMetadata(conn, nil, localConnMetadata)
if err != nil {
return nil, err
}
}
encryptKey, ok := c.encryptKeys.Load(string(append(remotePublicKey, connNonce...)))
if !ok || encryptKey == nil {
return nil, fmt.Errorf("encrypted key for UDP conn not found")
}
k := encryptKey.(*[encryptKeySize]byte)
err = encConn.AddCodec(addr, k, encryptionAlgo, true)
if err != nil {
return nil, err
}
}
return encConn, nil
}
func (c *Common) UpdateServerConn(remotePublicKey []byte) error {
hasUDP := len(c.Service.UDP) > 0 || (c.ReverseMetadata != nil && len(c.ReverseMetadata.ServiceUdp) > 0)
metadata := c.GetMetadata()
Close(c.GetTCPConn())
addr := metadata.Ip + ":" + strconv.Itoa(int(metadata.TcpPort))
var tcpConn net.Conn
var err error
if c.TcpDialContext != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.DialTimeout)*time.Second)
defer cancel()
tcpConn, err = c.TcpDialContext(ctx, tcp4, addr)
} else {
tcpConn, err = net.DialTimeout(
tcp4,
addr,
time.Duration(c.DialTimeout)*time.Second,
)
}
if err != nil {
return err
}
encryptedConn, remoteMetadata, err := c.wrapConn(tcpConn, remotePublicKey, nil)
if err != nil {
Close(tcpConn)
return err
}
c.SetServerTCPConn(encryptedConn)
log.Println("Connected to TCP at", addr)
if hasUDP {
oldConn := c.GetUDPConn()
Close(oldConn)
addr := &net.UDPAddr{IP: net.ParseIP(metadata.Ip), Port: int(metadata.UdpPort)}
udpConn, err := net.DialUDP(
udp4,
nil,
addr,
)
if err != nil {
return err
}
uConn, err := c.wrapUDPConn(udpConn, addr, remotePublicKey, remoteMetadata.Nonce)
if err != nil {
return err
}
c.SetServerUDPConn(uConn)
log.Println("Connected to UDP at", addr.String())
}
c.SetConnected(true)
c.OnConnect.receive()
return nil
}
func (c *Common) CreateServerConn(force bool) error {
if !c.IsServer && (!c.GetConnected() || force) {
for {
if c.isClosed {
return ErrClosed
}
err := c.SetPaymentReceiver("")
if err != nil {
return err
}
if c.minBalance > 0 {
entryToExitMaxPrice, exitToEntryMaxPrice, err := ParsePrice(c.ServiceInfo.MaxPrice)
if err != nil {
return err
}
if entryToExitMaxPrice > 0 || exitToEntryMaxPrice > 0 {
balance, err := c.Client.BalanceByAddress(c.Wallet.Address())
if err != nil {
log.Println("tuna.CreateServerConn BalanceByAddress error:", err)
} else {
if balance.ToFixed64() < c.minBalance {
return nkn.ErrInsufficientBalance
}
}
}
}
candidateSubs, err := c.GetTopPerformanceNodes(c.MeasureBandwidth, measureBandwidthTopCount)
if err != nil {
log.Println(err)
time.Sleep(time.Second)
continue
}
for _, subscriber := range candidateSubs {
metadata := subscriber.Metadata
if c.presetNode == nil {
subscription, err := c.Client.GetSubscription(c.SubscriptionPrefix+c.Service.Name, subscriber.Address)
if err == nil {
latestMeta, err := ReadMetadata(subscription.Meta)
if err == nil {
metadata = latestMeta
} else {
log.Println(err)
}
} else {
log.Println(err)
}
}
c.SetMetadata(metadata)
log.Printf("IP: %s, address: %s, delay: %.3f ms, bandwidth: %f KB/s", metadata.Ip, subscriber.Address, subscriber.Delay, subscriber.Bandwidth/1024)
entryToExitPrice, exitToEntryPrice, err := ParsePrice(metadata.Price)
if err != nil {
log.Println(err)
continue
}
if len(metadata.BeneficiaryAddr) > 0 {
err = c.SetPaymentReceiver(metadata.BeneficiaryAddr)
if err != nil {
log.Println(err)
continue
}
} else {
addr, err := nkn.ClientAddrToWalletAddr(subscriber.Address)
if err != nil {
log.Println(err)
continue
}
err = c.SetPaymentReceiver(addr)
if err != nil {
log.Println(err)
continue
}
}
c.Lock()
c.remoteNknAddress = subscriber.Address
c.entryToExitPrice = entryToExitPrice
c.exitToEntryPrice = exitToEntryPrice
if c.ReverseMetadata != nil {
c.metadata.ServiceTcp = c.ReverseMetadata.ServiceTcp
c.metadata.ServiceUdp = c.ReverseMetadata.ServiceUdp
}
c.Unlock()
remotePublicKey, err := nkn.ClientAddrToPubKey(subscriber.Address)
if err != nil {
log.Println(err)
continue
}
err = c.UpdateServerConn(remotePublicKey)
if err != nil {
log.Println(err)
time.Sleep(time.Second)
continue
}
return nil
}
}
}
return nil
}
func (c *Common) GetTopPerformanceNodes(measureBandwidth bool, n int) (types.Nodes, error) {
if c.presetNode != nil {
return types.Nodes{c.presetNode}, nil
}
return c.GetTopPerformanceNodesContext(context.Background(), measureBandwidth, n)
}
func (c *Common) GetTopPerformanceNodesContext(ctx context.Context, measureBandwidth bool, n int) (types.Nodes, error) {
if c.ServiceInfo.IPFilter != nil && len(c.ServiceInfo.IPFilter.GetProviders()) > 0 {
c.ServiceInfo.IPFilter.UpdateDataFileContext(ctx)
}
if c.measureStorage != nil {
measureStorageMutex.Lock()
defer measureStorageMutex.Unlock()
err := c.measureStorage.Load()
if err != nil {
return nil, err
}
}
var filterSubs types.Nodes
allSubscribers, subscriberRaw, err := c.nknFilterContext(ctx)
if err != nil {
return nil, err
}
filterSubs = c.filterSubscribers(allSubscribers, subscriberRaw)
var candidateSubs types.Nodes
if len(filterSubs) == 0 {
return nil, nil
} else if len(filterSubs) == 1 {
candidateSubs = filterSubs
} else {
delayMeasuredSubs := measureDelay(ctx, filterSubs, c.measureDelayConcurrentWorkers, measureDelayTopDelayCount, defaultMeasureDelayTimeout, c.TcpDialContext)
if measureBandwidth {
candidateSubs = c.measureBandwidth(ctx, delayMeasuredSubs, n, c.MeasureBandwidthWorkersTimeout)
} else {
length := n
if length > len(delayMeasuredSubs) {
length = len(delayMeasuredSubs)
}
candidateSubs = delayMeasuredSubs[:length]
}
}
if c.sortMeasuredNodes != nil {
c.sortMeasuredNodes(candidateSubs)
}
return candidateSubs, nil
}
func (c *Common) nknFilter() ([]string, map[string]string, error) {
return c.nknFilterContext(context.Background())
}
func (c *Common) nknFilterContext(ctx context.Context) ([]string, map[string]string, error) {
topic := c.SubscriptionPrefix + c.Service.Name
var allSubscribers []string
var subscriberRaw map[string]string
if c.ServiceInfo.NknFilter != nil && len(c.ServiceInfo.NknFilter.Allow) > 0 {
nknFilterLength := len(c.ServiceInfo.NknFilter.Allow)
subscriberRaw = make(map[string]string, nknFilterLength)
allSubscribers = make([]string, 0, nknFilterLength)
for _, f := range c.ServiceInfo.NknFilter.Allow {
if len(f.Metadata) > 0 {
subscriberRaw[f.Address] = f.Metadata
} else {
subscription, err := c.Client.GetSubscriptionContext(ctx, topic, f.Address)
if err != nil {
log.Println(err)
continue
}
subscriberRaw[f.Address] = subscription.Meta
}
allSubscribers = append(allSubscribers, f.Address)
}
if len(allSubscribers) == 0 {
return nil, nil, errors.New("none of the NKN address whitelist can provide service")
}
} else {
// check if there is at least one service provider with low cost
subscribers, err := c.Client.GetSubscribersContext(ctx, topic, 0, c.GetSubscribersBatchSize, false, false, nil)
if err != nil {
return nil, nil, err
}
if subscribers.Subscribers.Len() == 0 {
return nil, nil, errors.New("there is no service providers for " + c.Service.Name)
}
var allPrefix [][]byte
if subscribers.Subscribers.Len() < c.GetSubscribersBatchSize {
allPrefix = make([][]byte, 1)
} else {
allPrefix = make([][]byte, 256)
for i := 0; i < 256; i++ {
allPrefix[i] = []byte{byte(i)}
}
}
rand.Shuffle(len(allPrefix), func(i, j int) {
allPrefix[i], allPrefix[j] = allPrefix[j], allPrefix[i]
})
subscriberRaw = make(map[string]string)
subscriberCount := 0
for i := 0; i < len(allPrefix); i++ {
count, err := c.Client.GetSubscribersCountContext(ctx, topic, allPrefix[i])
if err != nil {
return nil, nil, err
}
if count > 0 {
offset := rand.Intn((count-1)/c.GetSubscribersBatchSize + 1)
subscribers, err := c.Client.GetSubscribersContext(ctx, topic, offset*c.GetSubscribersBatchSize, c.GetSubscribersBatchSize, true, false, allPrefix[i])
if err != nil {
return nil, nil, err
}
for subscriber, meta := range subscribers.Subscribers.Map() {
if _, ok := subscriberRaw[subscriber]; !ok {
subscriberRaw[subscriber] = meta
subscriberCount++
}
}
if subscriberCount >= c.GetSubscribersBatchSize {
break
}
}
if i+maxRPCRequests < len(allPrefix) {
estimatedRemainingRequests := float64(c.GetSubscribersBatchSize-subscriberCount) / (float64(subscriberCount+1) / float64(i+1))
if estimatedRemainingRequests > maxRPCRequests {
i = len(allPrefix) - 1
allPrefix = append(allPrefix, nil)
}
}
}
if c.measureStorage != nil {
nodes := c.measureStorage.FavoriteNodes.GetData()
for _, v := range nodes {
item := v.(*storage.FavoriteNode)
subscriberRaw[item.Address] = item.Metadata
log.Printf("Use favorite node: %s", item.IP)
}
}
allSubscribers = make([]string, 0, len(subscriberRaw))
for subscriber := range subscriberRaw {
allSubscribers = append(allSubscribers, subscriber)
}
}
return allSubscribers, subscriberRaw, nil
}
func (c *Common) filterSubscribers(allSubscribers []string, subscriberRaw map[string]string) types.Nodes {