-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathclient.go
1551 lines (1340 loc) · 42.9 KB
/
client.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 nkn
import (
"bytes"
"compress/zlib"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/nknorg/nkngomobile"
"github.com/gorilla/websocket"
"github.com/nknorg/nkn-sdk-go/nogomobile"
"github.com/nknorg/nkn-sdk-go/payloads"
"github.com/nknorg/nkn/v2/api/common/errcode"
"github.com/nknorg/nkn/v2/api/webrtc"
"github.com/nknorg/nkn/v2/config"
"github.com/nknorg/nkn/v2/crypto"
"github.com/nknorg/nkn/v2/crypto/ed25519"
"github.com/nknorg/nkn/v2/pb"
"github.com/nknorg/nkn/v2/transaction"
"github.com/nknorg/nkn/v2/util/address"
"github.com/patrickmn/go-cache"
"golang.org/x/crypto/nacl/box"
"google.golang.org/protobuf/proto"
)
const (
// MessageIDSize is the default message id size in bytes
MessageIDSize = 8
// Max client message size in bytes. NKN node is using 4*1024*1024 as limit
// (config.MaxClientMessageSize), we give some additional space for
// serialization overhead.
maxClientMessageSize = 4000000
// WebSocket ping interval.
pingInterval = 8 * time.Second
// WebSocket ping response timeout. Should be greater than pingInterval.
pongTimeout = 10 * time.Second
// Should match the setClient action string on node side.
setClientAction = "setClient"
// client authorization challenge
authChallengeAction = "authChallenge"
// duration waiting for challenge from node after connecting
waitForChallengeTimeout = 5 * time.Second
)
// Client sends and receives data between any NKN clients regardless their
// network condition without setting up a server or relying on any third party
// services. Data are end-to-end encrypted by default. Typically, you might want
// to use multiclient instead of using client directly.
type Client struct {
OnConnect *OnConnect // Event emitting channel when client connects to node and becomes ready to send messages. One should only use the first event of the channel.
OnMessage *OnMessage // Event emitting channel when client receives a message (not including reply or ACK).
config *ClientConfig
account *Account
publicKey []byte
curveSecretKey *[sharedKeySize]byte
address string
addressID []byte
sigChainBlockHash string
reconnectChan chan *Node
responseChannels *cache.Cache
resolvers []Resolver
lock sync.RWMutex
isClosed bool
conn nogomobile.WsConn
node *Node
sharedKeys map[string]*[sharedKeySize]byte
wallet *Wallet
// client auth
chChallengeSignature chan *stSaltAndSignature
peer *webrtc.Peer
}
// client auth
type stSaltAndSignature struct {
ClientSalt []byte
Signature []byte
}
// clientInterface is the common interface of client and multiclient.
type clientInterface interface {
getConfig() *ClientConfig
send(dests []string, payload *payloads.Payload, encrypted bool, maxHoldingSeconds int32) error
GetSubscribers(topic string, offset, limit int, meta, txPool bool, subscriberHashPrefix []byte) (*Subscribers, error)
}
type setClientResult struct {
Node *Node `json:"node"`
SigChainBlockHash string `json:"sigChainBlockHash"`
}
// NewClient creates a client with an account, an optional identifier, and a
// optional client config. For any zero value field in config, the default
// client config value will be used. If config is nil, the default client config
// will be used.
func NewClient(account *Account, identifier string, cfg *ClientConfig) (*Client, error) {
cfg, err := MergeClientConfig(cfg)
if err != nil {
return nil, err
}
pk := account.PubKey()
addr := address.MakeAddressString(pk, identifier)
var sk [ed25519.PrivateKeySize]byte
copy(sk[:], account.PrivKey())
curveSecretKey := ed25519.PrivateKeyToCurve25519PrivateKey(&sk)
w, err := NewWallet(account, &WalletConfig{SeedRPCServerAddr: cfg.SeedRPCServerAddr})
if err != nil {
return nil, err
}
gomobileResolvers := cfg.Resolvers.Elems()
resolvers := make([]Resolver, 0, len(gomobileResolvers))
for i := 0; i < len(resolvers); i++ {
r, ok := gomobileResolvers[i].(Resolver)
if !ok {
return nil, ErrInvalidResolver
}
resolvers = append(resolvers, r)
}
c := Client{
config: cfg,
account: account,
publicKey: pk,
curveSecretKey: curveSecretKey,
address: addr,
addressID: addressToID(addr),
OnConnect: NewOnConnect(1, nil),
OnMessage: NewOnMessage(int(cfg.MsgChanLen), nil),
reconnectChan: make(chan *Node),
responseChannels: cache.New(time.Duration(cfg.MsgCacheExpiration)*time.Millisecond, time.Duration(cfg.MsgCacheCleanupInterval)*time.Millisecond),
sharedKeys: make(map[string]*[sharedKeySize]byte),
wallet: w,
chChallengeSignature: make(chan *stSaltAndSignature, 1), // client auth
resolvers: resolvers,
}
go c.handleReconnect()
err = c.connect(int(c.config.ConnectRetries), nil)
if err != nil {
return nil, err
}
return &c, nil
}
// Account returns the account of the client.
func (c *Client) Account() *Account {
return c.account
}
// Seed returns the secret seed of the client. Secret seed can be used to create
// client/wallet with the same key pair and should be kept secret and safe.
func (c *Client) Seed() []byte {
return c.account.Seed()
}
// PubKey returns the public key of the client.
func (c *Client) PubKey() []byte {
return c.account.PubKey()
}
// Address returns the NKN client address of the client. Client address is in
// the form of
//
// identifier.pubKeyHex
//
// if identifier is not an empty string, or
//
// pubKeyHex
//
// if identifier is an empty string.
//
// Note that client address is different from wallet address using the same key
// pair (account). Wallet address can be computed from client address, but NOT
// vice versa.
func (c *Client) Address() string {
return c.address
}
// IsClosed returns whether the client is closed and should not be used anymore.
func (c *Client) IsClosed() bool {
c.lock.RLock()
defer c.lock.RUnlock()
return c.isClosed
}
// Close closes the client.
func (c *Client) Close() error {
c.lock.Lock()
defer c.lock.Unlock()
if c.isClosed {
return nil
}
c.isClosed = true
c.OnConnect.close()
c.OnMessage.close()
close(c.reconnectChan)
err := c.conn.Close()
// client auth
close(c.chChallengeSignature)
return err
}
// GetNode returns the node that client is currently connected to.
func (c *Client) GetNode() *Node {
c.lock.RLock()
defer c.lock.RUnlock()
return c.node
}
// GetConn returns the current websocket connection client is using.
func (c *Client) GetConn() nogomobile.WsConn {
c.lock.RLock()
defer c.lock.RUnlock()
return c.conn
}
func (c *Client) getOrComputeSharedKey(remotePublicKey []byte) (*[sharedKeySize]byte, error) {
c.lock.RLock()
sharedKey, ok := c.sharedKeys[string(remotePublicKey)]
c.lock.RUnlock()
if ok && sharedKey != nil {
return sharedKey, nil
}
if len(remotePublicKey) != ed25519.PublicKeySize {
return nil, ErrInvalidPubkeySize
}
var pk [ed25519.PublicKeySize]byte
copy(pk[:], remotePublicKey)
curve25519PublicKey, ok := ed25519.PublicKeyToCurve25519PublicKey(&pk)
if !ok {
return nil, ErrInvalidPubkey
}
sharedKey = new([sharedKeySize]byte)
box.Precompute(sharedKey, curve25519PublicKey, c.curveSecretKey)
c.lock.Lock()
c.sharedKeys[string(remotePublicKey)] = sharedKey
c.lock.Unlock()
return sharedKey, nil
}
func (c *Client) encryptPayload(msg *payloads.Payload, dests []string) ([][]byte, error) {
rawPayload, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
if len(dests) > 1 {
var key [sharedKeySize]byte
if _, err := rand.Read(key[:]); err != nil {
return nil, err
}
encrypted, msgNonce, err := encrypt(rawPayload, &key)
if err != nil {
return nil, err
}
msgs := make([][]byte, len(dests))
for i, dest := range dests {
_, destPubkey, _, err := address.ParseClientAddress(dest)
if err != nil {
return nil, err
}
sharedKey, err := c.getOrComputeSharedKey(destPubkey)
if err != nil {
return nil, err
}
encryptedKey, keyNonce, err := encrypt(key[:], sharedKey)
if err != nil {
return nil, err
}
nonce := append(keyNonce, msgNonce...)
msgs[i], err = proto.Marshal(&payloads.Message{
Payload: encrypted,
Encrypted: true,
Nonce: nonce,
EncryptedKey: encryptedKey,
})
if err != nil {
return nil, err
}
}
return msgs, nil
}
_, destPubkey, _, err := address.ParseClientAddress(dests[0])
if err != nil {
return nil, err
}
sharedKey, err := c.getOrComputeSharedKey(destPubkey)
if err != nil {
return nil, err
}
encrypted, nonce, err := encrypt(rawPayload, sharedKey)
if err != nil {
return nil, err
}
data, err := proto.Marshal(&payloads.Message{
Payload: encrypted,
Encrypted: true,
Nonce: nonce,
EncryptedKey: nil,
})
if err != nil {
return nil, err
}
return [][]byte{data}, nil
}
func (c *Client) decryptPayload(msg *payloads.Message, srcAddr string) ([]byte, error) {
rawPayload := msg.Payload
_, srcPubkey, _, err := address.ParseClientAddress(srcAddr)
if err != nil {
return nil, err
}
encryptedKey := msg.EncryptedKey
var decrypted []byte
if encryptedKey != nil && len(encryptedKey) > 0 {
var keyNonce, msgNonce [nonceSize]byte
copy(keyNonce[:], msg.Nonce[:nonceSize])
copy(msgNonce[:], msg.Nonce[nonceSize:])
sharedKey, err := c.getOrComputeSharedKey(srcPubkey)
if err != nil {
return nil, err
}
decryptedKeySlice, err := decrypt(encryptedKey, keyNonce, sharedKey)
if err != nil {
return nil, err
}
var decryptedKey [sharedKeySize]byte
copy(decryptedKey[:], decryptedKeySlice)
decrypted, err = decrypt(rawPayload, msgNonce, &decryptedKey)
if err != nil {
return nil, err
}
} else {
var nonce [nonceSize]byte
copy(nonce[:], msg.Nonce)
sharedKey, err := c.getOrComputeSharedKey(srcPubkey)
if err != nil {
return nil, err
}
decrypted, err = decrypt(rawPayload, nonce, sharedKey)
if err != nil {
return nil, err
}
}
return decrypted, nil
}
func (c *Client) handleMessage(msgType int, data []byte) error {
if c.IsClosed() {
return nil
}
switch msgType {
case websocket.TextMessage:
msg := make(map[string]*json.RawMessage)
if err := json.Unmarshal(data, &msg); err != nil {
return err
}
var action string
if err := json.Unmarshal(*msg["Action"], &action); err != nil {
return err
}
var errCode errcode.ErrCode
if err := json.Unmarshal(*msg["Error"], &errCode); err != nil {
return err
}
if errCode != errcode.SUCCESS {
if errCode == errcode.WRONG_NODE {
var node Node
if err := json.Unmarshal(*msg["Result"], &node); err != nil {
return err
}
go func() {
c.Reconnect(&node)
}()
} else if action == setClientAction {
c.Close()
}
return errorWithCode{
err: errors.New(errcode.ErrMessage[errCode]),
code: int32(errCode),
}
}
switch action {
case setClientAction:
var result setClientResult
if err := json.Unmarshal(*msg["Result"], &result); err != nil {
return err
}
c.sigChainBlockHash = result.SigChainBlockHash
c.lock.RLock()
defer c.lock.RUnlock()
if c.isClosed {
return nil
}
node := c.GetNode()
c.OnConnect.receive(node)
case "updateSigChainBlockHash":
var sigChainBlockHash string
if err := json.Unmarshal(*msg["Result"], &sigChainBlockHash); err != nil {
return err
}
c.sigChainBlockHash = sigChainBlockHash
// client auth
case authChallengeAction:
var challenge string
if err := json.Unmarshal(*msg["Challenge"], &challenge); err != nil {
return err
}
byteChallenge, err := hex.DecodeString(challenge)
if err != nil {
return err
}
clientSalt, err := RandomBytes(32)
if err != nil {
return err
}
// add client salt to the node's challenge
byteChallenge = append(byteChallenge, clientSalt...)
hash := sha256.Sum256(byteChallenge)
signature, err := crypto.Sign(c.account.PrivateKey, hash[:])
if err != nil {
return err
}
saltAndSig := &stSaltAndSignature{ClientSalt: clientSalt, Signature: signature}
select {
case c.chChallengeSignature <- saltAndSig:
default:
}
}
case websocket.BinaryMessage:
clientMsg := &pb.ClientMessage{}
if err := proto.Unmarshal(data, clientMsg); err != nil {
return err
}
switch clientMsg.MessageType {
case pb.ClientMessageType_INBOUND_MESSAGE:
inboundMsg := &pb.InboundMessage{}
if err := proto.Unmarshal(clientMsg.Message, inboundMsg); err != nil {
return err
}
if len(inboundMsg.PrevHash) > 0 {
go func() {
if err := c.sendReceipt(inboundMsg.PrevHash); err != nil {
log.Println(err)
}
}()
}
payloadMsg := &payloads.Message{}
if err := proto.Unmarshal(inboundMsg.Payload, payloadMsg); err != nil {
return err
}
var payloadBytes []byte
if payloadMsg.Encrypted {
var err error
payloadBytes, err = c.decryptPayload(payloadMsg, inboundMsg.Src)
if err != nil {
return err
}
} else if c.config.AllowUnencrypted {
payloadBytes = payloadMsg.Payload
} else {
return ErrUnencryptedMessage
}
payload := &payloads.Payload{}
if err := proto.Unmarshal(payloadBytes, payload); err != nil {
return err
}
data := payload.Data
switch payload.Type {
case payloads.PayloadType_TEXT:
textData := &payloads.TextData{}
if err := proto.Unmarshal(data, textData); err != nil {
return err
}
data = []byte(textData.Text)
case payloads.PayloadType_ACK:
data = nil
}
msg := &Message{
Src: inboundMsg.Src,
Data: data,
Type: int32(payload.Type),
Encrypted: payloadMsg.Encrypted,
MessageID: payload.MessageId,
NoReply: payload.NoReply,
}
if len(payload.ReplyToId) > 0 {
msgIDString := string(payload.ReplyToId)
onReply, ok := c.responseChannels.Get(msgIDString)
if ok {
c.responseChannels.Delete(msgIDString)
onReply.(*OnMessage).receive(msg, false)
}
return nil
}
if payload.NoReply {
msg.reply = func(data interface{}) error {
return nil
}
} else {
msg.reply = func(data interface{}) error {
payload, err := NewReplyPayload(data, payload.MessageId)
if err != nil {
return err
}
if err := c.send([]string{inboundMsg.Src}, payload, payloadMsg.Encrypted, 0); err != nil {
return err
}
return nil
}
}
c.lock.RLock()
defer c.lock.RUnlock()
if c.isClosed {
return nil
}
c.OnMessage.receive(msg, true)
}
}
return nil
}
func (c *Client) connectToNode(node *Node) error {
var rpcAddr string
var wg sync.WaitGroup
if len(node.RPCAddr) > 0 {
wg.Add(1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
defer wg.Done()
addr := (&url.URL{Scheme: "http", Host: node.RPCAddr}).String()
nodeState, err := GetNodeStateContext(ctx, &RPCConfig{
SeedRPCServerAddr: nkngomobile.NewStringArray(addr),
RPCTimeout: c.config.WsHandshakeTimeout,
HttpDialContext: c.config.HttpDialContext,
})
if err != nil {
return
}
if nodeState.SyncState != pb.SyncState_name[int32(pb.SyncState_PERSIST_FINISHED)] {
return
}
rpcAddr = addr
}()
}
var conn nogomobile.WsConn
var err error
if c.config.WebRTC {
c.peer.SetRemoteSdp(node.Sdp)
select {
case <-c.peer.OnOfferConnected:
conn = c.peer
case <-time.After(time.Duration(c.config.WebRTCConnectTimeout) * time.Millisecond):
return ErrConnectFailed
}
} else {
wsAddr := (&url.URL{Scheme: "ws", Host: node.Addr}).String()
dialer := &websocket.Dialer{
NetDialContext: c.config.WsDialContext,
Proxy: http.ProxyFromEnvironment,
}
dialer.HandshakeTimeout = time.Duration(c.config.WsHandshakeTimeout) * time.Millisecond
conn, _, err = dialer.Dial(wsAddr, nil)
if err != nil {
return err
}
}
wg.Wait()
c.lock.Lock()
prevConn := c.conn
c.conn = conn
c.node = node
if len(rpcAddr) > 0 {
c.wallet.config.SeedRPCServerAddr = nkngomobile.NewStringArray(rpcAddr)
} else {
c.wallet.config.SeedRPCServerAddr = nkngomobile.NewStringArray()
}
c.lock.Unlock()
if prevConn != nil {
prevConn.Close()
}
conn.SetReadLimit(config.MaxClientMessageSize)
conn.SetReadDeadline(time.Now().Add(pongTimeout))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongTimeout))
return nil
})
done := make(chan struct{})
go func() {
ticker := time.NewTicker(pingInterval)
defer ticker.Stop()
var err error
for {
select {
case <-ticker.C:
c.lock.Lock()
conn.SetWriteDeadline(time.Now().Add(pingInterval))
err = conn.WriteMessage(websocket.PingMessage, nil)
c.lock.Unlock()
if err != nil {
log.Println(err)
c.Reconnect(nil)
return
}
case <-done:
return
}
}
}()
go func() { // setClient Action function
// client auth
timer := time.NewTimer(waitForChallengeTimeout)
var saltAndSig *stSaltAndSignature
select { // time out or get challenge signature
case <-timer.C:
case saltAndSig = <-c.chChallengeSignature:
}
req := make(map[string]interface{})
req["Action"] = "setClient"
req["Addr"] = c.Address()
// client auth
if saltAndSig != nil {
req["ClientSalt"] = hex.EncodeToString(saltAndSig.ClientSalt)
req["Signature"] = hex.EncodeToString(saltAndSig.Signature)
}
c.lock.Lock()
err := conn.WriteJSON(req)
c.lock.Unlock()
if err != nil {
log.Println(err)
c.Reconnect(nil)
return
}
}()
go func() {
defer close(done)
for {
if c.IsClosed() {
return
}
msgType, data, err := conn.ReadMessage()
if err != nil {
log.Println(err)
c.Reconnect(nil)
return
}
conn.SetReadDeadline(time.Now().Add(pongTimeout))
err = c.handleMessage(msgType, data)
if err != nil {
log.Println(err)
continue
}
}
}()
return nil
}
func (c *Client) connect(maxRetries int, node *Node) error {
retryInterval := c.config.MinReconnectInterval
for retry := 1; maxRetries < 0 || retry <= maxRetries; retry++ {
if retry > 1 {
log.Printf("Retry in %v ms...", retryInterval)
time.Sleep(time.Duration(retryInterval) * time.Millisecond)
retryInterval *= 2
if retryInterval > c.config.MaxReconnectInterval {
retryInterval = c.config.MaxReconnectInterval
}
}
var err error
if node == nil {
if c.config.WebRTC {
c.peer = webrtc.NewPeer(c.config.StunServerAddr.Elems())
if c.peer == nil {
log.Println("failed to create peer")
continue
}
err = c.peer.Offer(c.address)
if err != nil {
log.Println("WebRTC offer error: ", err)
continue
}
select {
case offer := <-c.peer.OnSdp:
node, err = GetPeerAddr(c.Address(), offer, c.config)
if err != nil {
log.Println("GetPeerAddr error: ", err)
continue
}
case <-time.After(time.Duration(c.config.WebRTCConnectTimeout) * time.Millisecond):
log.Println("WebRTC get offer timeout")
continue
}
} else {
node, err = GetWsAddr(c.Address(), c.config)
if err != nil {
log.Println(err)
continue
}
}
}
err = c.connectToNode(node)
if err != nil {
log.Println(err)
continue
}
return nil
}
return ErrConnectFailed
}
// Reconnect forces the client to find node and connect again.
func (c *Client) Reconnect(node *Node) {
if c.IsClosed() {
return
}
select {
case c.reconnectChan <- node:
default:
}
}
func (c *Client) handleReconnect() {
for node := range c.reconnectChan {
if c.IsClosed() {
return
}
log.Printf("Reconnect in %v ms...", c.config.MinReconnectInterval)
time.Sleep(time.Duration(c.config.MinReconnectInterval) * time.Millisecond)
err := c.connect(-1, node)
if err != nil {
log.Println(err)
c.Close()
return
}
}
}
func (c *Client) writeMessage(buf []byte, writeTimeout time.Duration) error {
c.lock.Lock()
if writeTimeout == 0 {
c.conn.SetWriteDeadline(zeroTime)
} else {
c.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
}
err := c.conn.WriteMessage(websocket.BinaryMessage, buf)
c.lock.Unlock()
if err != nil {
c.Reconnect(nil)
}
return err
}
func (c *Client) sendReceipt(prevSignature []byte) error {
sigChainElem := &pb.SigChainElem{}
buff := bytes.NewBuffer(nil)
if err := sigChainElem.SerializationUnsigned(buff); err != nil {
return err
}
sigChainElemSerialized := buff.Bytes()
digest := sha256.Sum256(prevSignature)
digest = sha256.Sum256(append(digest[:], sigChainElemSerialized...))
signature, err := crypto.Sign(c.account.PrivateKey, digest[:])
if err != nil {
return err
}
receipt := &pb.Receipt{
PrevHash: prevSignature,
Signature: signature,
}
receiptData, err := proto.Marshal(receipt)
if err != nil {
return err
}
clientMsg := &pb.ClientMessage{
MessageType: pb.ClientMessageType_RECEIPT,
Message: receiptData,
CompressionType: pb.CompressionType_COMPRESSION_NONE,
}
buf, err := proto.Marshal(clientMsg)
if err != nil {
return err
}
return c.writeMessage(buf, time.Duration(c.config.WsWriteTimeout)*time.Millisecond)
}
// Send sends bytes or string data to one or multiple destinations with an
// optional config. Returned OnMessage channel will emit if a reply or ACK for
// this message is received.
func (c *Client) Send(dests *nkngomobile.StringArray, data interface{}, cfg *MessageConfig) (*OnMessage, error) {
cfg, err := MergeMessageConfig(c.config.MessageConfig, cfg)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.config.ResolverTimeout)*time.Millisecond)
defer cancel()
destArr, err := c.ResolveDestsContext(ctx, dests)
if err != nil {
return nil, err
}
payload, ok := data.(*payloads.Payload)
if !ok {
payload, err = newMessagePayload(data, cfg.MessageID, cfg.NoReply)
if err != nil {
return nil, err
}
}
if err := c.send(destArr.Elems(), payload, !cfg.Unencrypted, cfg.MaxHoldingSeconds); err != nil {
return nil, err
}
onReply := NewOnMessage(1, nil)
if !cfg.NoReply {
c.responseChannels.Add(string(payload.MessageId), onReply, cache.DefaultExpiration)
}
return onReply, nil
}
// SendBinary is a wrapper of Send without interface type for gomobile
// compatibility.
func (c *Client) SendBinary(dests *nkngomobile.StringArray, data []byte, config *MessageConfig) (*OnMessage, error) {
return c.Send(dests, data, config)
}
// SendText is a wrapper of Send without interface type for gomobile
// compatibility.
func (c *Client) SendText(dests *nkngomobile.StringArray, data string, config *MessageConfig) (*OnMessage, error) {
return c.Send(dests, data, config)
}
// SendPayload is a wrapper of Send without interface type for gomobile
// compatibility.
func (c *Client) SendPayload(dests *nkngomobile.StringArray, payload *payloads.Payload, config *MessageConfig) (*OnMessage, error) {
return c.Send(dests, payload, config)
}
// ResolveDest wraps ResolveDestContext with background context
func (c *Client) ResolveDest(dest string) (string, error) {
return c.ResolveDestContext(context.Background(), dest)
}
// ResolveDestContext resolvers an address, returns NKN address
func (c *Client) ResolveDestContext(ctx context.Context, dest string) (string, error) {
return ResolveDestN(ctx, dest, c.resolvers, c.config.ResolverDepth)
}
// ResolveDests wraps ResolveDestsContext with background context
func (c *Client) ResolveDests(dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error) {
return c.ResolveDestsContext(context.Background(), dests)
}
// ResolveDestsContext resolvers multiple addresses
func (c *Client) ResolveDestsContext(ctx context.Context, dests *nkngomobile.StringArray) (*nkngomobile.StringArray, error) {
destArr, err := ResolveDests(ctx, dests.Elems(), c.resolvers, c.config.ResolverDepth)
if err != nil {
return nil, err
}
return nkngomobile.NewStringArray(destArr...), nil
}
func (c *Client) processDest(ctx context.Context, dest string) (string, error) {
if len(dest) == 0 {
return "", ErrNoDestination
}
addr := strings.Split(dest, ".")
if len(addr[len(addr)-1]) < 2*ed25519.PublicKeySize {
reg, err := c.GetRegistrantContext(ctx, addr[len(addr)-1])
if err != nil {
return "", err
}
if len(reg.Registrant) == 0 {
return "", ErrInvalidPubkeyOrName
}
addr[len(addr)-1] = reg.Registrant
}
return strings.Join(addr, "."), nil
}
func (c *Client) processDests(ctx context.Context, dests []string) ([]string, error) {
if len(dests) == 0 {
return nil, nil
}
processedDests := make([]string, 0, len(dests))
for _, dest := range dests {
processedDest, err := c.processDest(ctx, dest)
if err != nil {
log.Println(err)
continue
}
processedDests = append(processedDests, processedDest)
}
if len(processedDests) == 0 {
return nil, ErrInvalidDestination
}
return processedDests, nil
}