-
Notifications
You must be signed in to change notification settings - Fork 246
/
manager.go
5377 lines (4447 loc) · 162 KB
/
manager.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 communities
import (
"context"
"crypto/ecdsa"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
"github.com/golang/protobuf/proto"
"github.com/google/uuid"
"github.com/pkg/errors"
"go.uber.org/zap"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/status-im/status-go/account"
utils "github.com/status-im/status-go/common"
"github.com/status-im/status-go/eth-node/crypto"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/images"
multiaccountscommon "github.com/status-im/status-go/multiaccounts/common"
"github.com/status-im/status-go/params"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/common/shard"
community_token "github.com/status-im/status-go/protocol/communities/token"
"github.com/status-im/status-go/protocol/encryption"
"github.com/status-im/status-go/protocol/ens"
"github.com/status-im/status-go/protocol/protobuf"
"github.com/status-im/status-go/protocol/requests"
"github.com/status-im/status-go/protocol/transport"
"github.com/status-im/status-go/services/communitytokens"
"github.com/status-im/status-go/services/wallet/bigint"
walletcommon "github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/services/wallet/thirdparty"
"github.com/status-im/status-go/services/wallet/token"
"github.com/status-im/status-go/signal"
)
var defaultAnnounceList = [][]string{
{"udp://tracker.opentrackr.org:1337/announce"},
{"udp://tracker.openbittorrent.com:6969/announce"},
}
var pieceLength = 100 * 1024
const maxArchiveSizeInBytes = 30000000
var memberPermissionsCheckInterval = 1 * time.Hour
var validateInterval = 2 * time.Minute
// Used for testing only
func SetValidateInterval(duration time.Duration) {
validateInterval = duration
}
// errors
var (
ErrTorrentTimedout = errors.New("torrent has timed out")
ErrCommunityRequestAlreadyRejected = errors.New("that user was already rejected from the community")
ErrInvalidClock = errors.New("invalid clock to cancel request to join")
)
type Manager struct {
persistence *Persistence
encryptor *encryption.Protocol
ensSubscription chan []*ens.VerificationRecord
subscriptions []chan *Subscription
ensVerifier *ens.Verifier
ownerVerifier OwnerVerifier
identity *ecdsa.PrivateKey
installationID string
accountsManager account.Manager
tokenManager TokenManager
collectiblesManager CollectiblesManager
logger *zap.Logger
stdoutLogger *zap.Logger
transport *transport.Transport
timesource common.TimeSource
quit chan struct{}
torrentConfig *params.TorrentConfig
torrentClient *torrent.Client
walletConfig *params.WalletConfig
communityTokensService communitytokens.ServiceInterface
historyArchiveTasksWaitGroup sync.WaitGroup
historyArchiveTasks sync.Map // stores `chan struct{}`
membersReevaluationTasks sync.Map // stores `membersReevaluationTask`
torrentTasks map[string]metainfo.Hash
historyArchiveDownloadTasks map[string]*HistoryArchiveDownloadTask
stopped bool
RekeyInterval time.Duration
PermissionChecker PermissionChecker
keyDistributor KeyDistributor
communityLock *CommunityLock
}
type CommunityLock struct {
logger *zap.Logger
locks map[string]*sync.Mutex
mutex sync.Mutex
}
func NewCommunityLock(logger *zap.Logger) *CommunityLock {
return &CommunityLock{
logger: logger.Named("CommunityLock"),
locks: make(map[string]*sync.Mutex),
}
}
func (c *CommunityLock) Lock(communityID types.HexBytes) {
c.mutex.Lock()
communityIDStr := types.EncodeHex(communityID)
lock, ok := c.locks[communityIDStr]
if !ok {
lock = &sync.Mutex{}
c.locks[communityIDStr] = lock
}
c.mutex.Unlock()
lock.Lock()
}
func (c *CommunityLock) Unlock(communityID types.HexBytes) {
c.mutex.Lock()
communityIDStr := types.EncodeHex(communityID)
lock, ok := c.locks[communityIDStr]
c.mutex.Unlock()
if ok {
lock.Unlock()
} else {
c.logger.Warn("trying to unlock a non-existent lock", zap.String("communityID", communityIDStr))
}
}
func (c *CommunityLock) Init() {
c.locks = make(map[string]*sync.Mutex)
}
func (c *CommunityLock) Release() {
c.locks = nil
}
type HistoryArchiveDownloadTask struct {
CancelChan chan struct{}
Waiter sync.WaitGroup
m sync.RWMutex
Cancelled bool
}
func (t *HistoryArchiveDownloadTask) IsCancelled() bool {
t.m.RLock()
defer t.m.RUnlock()
return t.Cancelled
}
func (t *HistoryArchiveDownloadTask) Cancel() {
t.m.Lock()
defer t.m.Unlock()
t.Cancelled = true
close(t.CancelChan)
}
type membersReevaluationTask struct {
lastSuccessTime time.Time
onDemandRequestTime time.Time
mutex sync.Mutex
}
type managerOptions struct {
accountsManager account.Manager
tokenManager TokenManager
collectiblesManager CollectiblesManager
walletConfig *params.WalletConfig
communityTokensService communitytokens.ServiceInterface
permissionChecker PermissionChecker
}
type TokenManager interface {
GetBalancesByChain(ctx context.Context, accounts, tokens []gethcommon.Address, chainIDs []uint64) (map[uint64]map[gethcommon.Address]map[gethcommon.Address]*hexutil.Big, error)
FindOrCreateTokenByAddress(ctx context.Context, chainID uint64, address gethcommon.Address) *token.Token
GetAllChainIDs() ([]uint64, error)
}
type DefaultTokenManager struct {
tokenManager *token.Manager
}
func NewDefaultTokenManager(tm *token.Manager) *DefaultTokenManager {
return &DefaultTokenManager{tokenManager: tm}
}
type BalancesByChain = map[uint64]map[gethcommon.Address]map[gethcommon.Address]*hexutil.Big
func (m *DefaultTokenManager) GetAllChainIDs() ([]uint64, error) {
networks, err := m.tokenManager.RPCClient.NetworkManager.Get(false)
if err != nil {
return nil, err
}
areTestNetworksEnabled, err := m.tokenManager.RPCClient.NetworkManager.GetTestNetworksEnabled()
if err != nil {
return nil, err
}
chainIDs := make([]uint64, 0)
for _, network := range networks {
if areTestNetworksEnabled == network.IsTest {
chainIDs = append(chainIDs, network.ChainID)
}
}
return chainIDs, nil
}
type CollectiblesManager interface {
FetchBalancesByOwnerAndContractAddress(ctx context.Context, chainID walletcommon.ChainID, ownerAddress gethcommon.Address, contractAddresses []gethcommon.Address) (thirdparty.TokenBalancesPerContractAddress, error)
GetCollectibleOwnership(id thirdparty.CollectibleUniqueID) ([]thirdparty.AccountBalance, error)
}
func (m *DefaultTokenManager) GetBalancesByChain(ctx context.Context, accounts, tokenAddresses []gethcommon.Address, chainIDs []uint64) (BalancesByChain, error) {
clients, err := m.tokenManager.RPCClient.EthClients(chainIDs)
if err != nil {
return nil, err
}
resp, err := m.tokenManager.GetBalancesByChain(context.Background(), clients, accounts, tokenAddresses)
return resp, err
}
func (m *DefaultTokenManager) FindOrCreateTokenByAddress(ctx context.Context, chainID uint64, address gethcommon.Address) *token.Token {
return m.tokenManager.FindOrCreateTokenByAddress(ctx, chainID, address)
}
type ManagerOption func(*managerOptions)
func WithAccountManager(accountsManager account.Manager) ManagerOption {
return func(opts *managerOptions) {
opts.accountsManager = accountsManager
}
}
func WithPermissionChecker(permissionChecker PermissionChecker) ManagerOption {
return func(opts *managerOptions) {
opts.permissionChecker = permissionChecker
}
}
func WithCollectiblesManager(collectiblesManager CollectiblesManager) ManagerOption {
return func(opts *managerOptions) {
opts.collectiblesManager = collectiblesManager
}
}
func WithTokenManager(tokenManager TokenManager) ManagerOption {
return func(opts *managerOptions) {
opts.tokenManager = tokenManager
}
}
func WithWalletConfig(walletConfig *params.WalletConfig) ManagerOption {
return func(opts *managerOptions) {
opts.walletConfig = walletConfig
}
}
func WithCommunityTokensService(communityTokensService communitytokens.ServiceInterface) ManagerOption {
return func(opts *managerOptions) {
opts.communityTokensService = communityTokensService
}
}
type OwnerVerifier interface {
SafeGetSignerPubKey(ctx context.Context, chainID uint64, communityID string) (string, error)
}
func NewManager(identity *ecdsa.PrivateKey, installationID string, db *sql.DB, encryptor *encryption.Protocol, logger *zap.Logger, ensverifier *ens.Verifier, ownerVerifier OwnerVerifier, transport *transport.Transport, timesource common.TimeSource, keyDistributor KeyDistributor, torrentConfig *params.TorrentConfig, opts ...ManagerOption) (*Manager, error) {
if identity == nil {
return nil, errors.New("empty identity")
}
if timesource == nil {
return nil, errors.New("no timesource")
}
var err error
if logger == nil {
if logger, err = zap.NewDevelopment(); err != nil {
return nil, errors.Wrap(err, "failed to create a logger")
}
}
stdoutLogger, err := zap.NewDevelopment()
if err != nil {
return nil, errors.Wrap(err, "failed to create archive logger")
}
managerConfig := managerOptions{}
for _, opt := range opts {
opt(&managerConfig)
}
manager := &Manager{
logger: logger,
stdoutLogger: stdoutLogger,
encryptor: encryptor,
identity: identity,
installationID: installationID,
ownerVerifier: ownerVerifier,
quit: make(chan struct{}),
transport: transport,
timesource: timesource,
torrentConfig: torrentConfig,
torrentTasks: make(map[string]metainfo.Hash),
historyArchiveDownloadTasks: make(map[string]*HistoryArchiveDownloadTask),
keyDistributor: keyDistributor,
communityLock: NewCommunityLock(logger),
}
manager.persistence = &Persistence{
db: db,
recordBundleToCommunity: manager.dbRecordBundleToCommunity,
}
if managerConfig.accountsManager != nil {
manager.accountsManager = managerConfig.accountsManager
}
if managerConfig.collectiblesManager != nil {
manager.collectiblesManager = managerConfig.collectiblesManager
}
if managerConfig.tokenManager != nil {
manager.tokenManager = managerConfig.tokenManager
}
if managerConfig.walletConfig != nil {
manager.walletConfig = managerConfig.walletConfig
}
if managerConfig.communityTokensService != nil {
manager.communityTokensService = managerConfig.communityTokensService
}
if ensverifier != nil {
sub := ensverifier.Subscribe()
manager.ensSubscription = sub
manager.ensVerifier = ensverifier
}
if managerConfig.permissionChecker != nil {
manager.PermissionChecker = managerConfig.permissionChecker
} else {
manager.PermissionChecker = &DefaultPermissionChecker{
tokenManager: manager.tokenManager,
collectiblesManager: manager.collectiblesManager,
logger: logger,
ensVerifier: ensverifier,
}
}
return manager, nil
}
func (m *Manager) LogStdout(msg string, fields ...zap.Field) {
m.stdoutLogger.Info(msg, fields...)
m.logger.Debug(msg, fields...)
}
type archiveMDSlice []*archiveMetadata
type archiveMetadata struct {
hash string
from uint64
}
func (md archiveMDSlice) Len() int {
return len(md)
}
func (md archiveMDSlice) Swap(i, j int) {
md[i], md[j] = md[j], md[i]
}
func (md archiveMDSlice) Less(i, j int) bool {
return md[i].from > md[j].from
}
type Subscription struct {
Community *Community
CreatingHistoryArchivesSignal *signal.CreatingHistoryArchivesSignal
HistoryArchivesCreatedSignal *signal.HistoryArchivesCreatedSignal
NoHistoryArchivesCreatedSignal *signal.NoHistoryArchivesCreatedSignal
HistoryArchivesSeedingSignal *signal.HistoryArchivesSeedingSignal
HistoryArchivesUnseededSignal *signal.HistoryArchivesUnseededSignal
HistoryArchiveDownloadedSignal *signal.HistoryArchiveDownloadedSignal
DownloadingHistoryArchivesStartedSignal *signal.DownloadingHistoryArchivesStartedSignal
DownloadingHistoryArchivesFinishedSignal *signal.DownloadingHistoryArchivesFinishedSignal
ImportingHistoryArchiveMessagesSignal *signal.ImportingHistoryArchiveMessagesSignal
CommunityEventsMessage *CommunityEventsMessage
AcceptedRequestsToJoin []types.HexBytes
RejectedRequestsToJoin []types.HexBytes
CommunityPrivilegedMemberSyncMessage *CommunityPrivilegedMemberSyncMessage
TokenCommunityValidated *CommunityResponse
}
type CommunityResponse struct {
Community *Community `json:"community"`
Changes *CommunityChanges `json:"changes"`
RequestsToJoin []*RequestToJoin `json:"requestsToJoin"`
FailedToDecrypt []*CommunityPrivateDataFailedToDecrypt `json:"-"`
}
func (m *Manager) Subscribe() chan *Subscription {
subscription := make(chan *Subscription, 100)
m.subscriptions = append(m.subscriptions, subscription)
return subscription
}
func (m *Manager) Start() error {
m.stopped = false
m.communityLock.Init()
if m.ensVerifier != nil {
m.runENSVerificationLoop()
}
if m.ownerVerifier != nil {
m.runOwnerVerificationLoop()
}
if m.torrentConfig != nil && m.torrentConfig.Enabled {
err := m.StartTorrentClient()
if err != nil {
m.LogStdout("couldn't start torrent client", zap.Error(err))
}
}
return nil
}
func (m *Manager) runENSVerificationLoop() {
go func() {
for {
select {
case <-m.quit:
m.logger.Debug("quitting ens verification loop")
return
case records, more := <-m.ensSubscription:
if !more {
m.logger.Debug("no more ens records, quitting")
return
}
m.logger.Info("received records", zap.Any("records", records))
}
}
}()
}
// Only for testing
func (m *Manager) CommunitiesToValidate() (map[string][]communityToValidate, error) { // nolint: golint
return m.persistence.getCommunitiesToValidate()
}
func (m *Manager) runOwnerVerificationLoop() {
m.logger.Info("starting owner verification loop")
go func() {
for {
select {
case <-m.quit:
m.logger.Debug("quitting owner verification loop")
return
case <-time.After(validateInterval):
// If ownerverifier is nil, we skip, this is useful for testing
if m.ownerVerifier == nil {
continue
}
communitiesToValidate, err := m.persistence.getCommunitiesToValidate()
if err != nil {
m.logger.Error("failed to fetch communities to validate", zap.Error(err))
continue
}
for id, communities := range communitiesToValidate {
m.logger.Info("validating communities", zap.String("id", id), zap.Int("count", len(communities)))
_, _ = m.validateCommunity(communities)
}
}
}
}()
}
func (m *Manager) ValidateCommunityByID(communityID types.HexBytes) (*CommunityResponse, error) {
communitiesToValidate, err := m.persistence.getCommunityToValidateByID(communityID)
if err != nil {
m.logger.Error("failed to validate community by ID", zap.String("id", communityID.String()), zap.Error(err))
return nil, err
}
return m.validateCommunity(communitiesToValidate)
}
func (m *Manager) validateCommunity(communityToValidateData []communityToValidate) (*CommunityResponse, error) {
for _, community := range communityToValidateData {
signer, description, err := UnwrapCommunityDescriptionMessage(community.payload)
if err != nil {
m.logger.Error("failed to unwrap community", zap.Error(err))
continue
}
chainID := CommunityDescriptionTokenOwnerChainID(description)
if chainID == 0 {
// This should not happen
m.logger.Error("chain id is 0, ignoring")
continue
}
m.logger.Info("validating community", zap.String("id", types.EncodeHex(community.id)), zap.String("signer", common.PubkeyToHex(signer)))
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
owner, err := m.ownerVerifier.SafeGetSignerPubKey(ctx, chainID, types.EncodeHex(community.id))
if err != nil {
m.logger.Error("failed to get owner", zap.Error(err))
continue
}
ownerPK, err := common.HexToPubkey(owner)
if err != nil {
m.logger.Error("failed to convert pk string to ecdsa", zap.Error(err))
continue
}
// TODO: handle shards
response, err := m.HandleCommunityDescriptionMessage(signer, description, community.payload, ownerPK, nil)
if err != nil {
m.logger.Error("failed to handle community", zap.Error(err))
err = m.persistence.DeleteCommunityToValidate(community.id, community.clock)
if err != nil {
m.logger.Error("failed to delete community to validate", zap.Error(err))
}
continue
}
if response != nil {
m.logger.Info("community validated", zap.String("id", types.EncodeHex(community.id)), zap.String("signer", common.PubkeyToHex(signer)))
m.publish(&Subscription{TokenCommunityValidated: response})
err := m.persistence.DeleteCommunitiesToValidateByCommunityID(community.id)
if err != nil {
m.logger.Error("failed to delete communities to validate", zap.Error(err))
}
return response, nil
}
}
return nil, nil
}
func (m *Manager) Stop() error {
m.stopped = true
close(m.quit)
for _, c := range m.subscriptions {
close(c)
}
m.StopTorrentClient()
m.communityLock.Release()
return nil
}
func (m *Manager) SetTorrentConfig(config *params.TorrentConfig) {
m.torrentConfig = config
}
// getTCPandUDPport will return the same port number given if != 0,
// otherwise, it will attempt to find a free random tcp and udp port using
// the same number for both protocols
func (m *Manager) getTCPandUDPport(portNumber int) (int, error) {
if portNumber != 0 {
return portNumber, nil
}
// Find free port
for i := 0; i < 10; i++ {
port := func() int {
tcpAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort("localhost", "0"))
if err != nil {
m.logger.Warn("unable to resolve tcp addr: %v", zap.Error(err))
return 0
}
tcpListener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
m.logger.Warn("unable to listen on addr", zap.Stringer("addr", tcpAddr), zap.Error(err))
return 0
}
defer tcpListener.Close()
port := tcpListener.Addr().(*net.TCPAddr).Port
udpAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort("localhost", fmt.Sprintf("%d", port)))
if err != nil {
m.logger.Warn("unable to resolve udp addr: %v", zap.Error(err))
return 0
}
udpListener, err := net.ListenUDP("udp", udpAddr)
if err != nil {
m.logger.Warn("unable to listen on addr", zap.Stringer("addr", udpAddr), zap.Error(err))
return 0
}
defer udpListener.Close()
return port
}()
if port != 0 {
return port, nil
}
}
return 0, fmt.Errorf("no free port found")
}
func (m *Manager) StartTorrentClient() error {
if m.torrentConfig == nil {
return fmt.Errorf("can't start torrent client: missing torrentConfig")
}
if m.TorrentClientStarted() {
return nil
}
port, err := m.getTCPandUDPport(m.torrentConfig.Port)
if err != nil {
return err
}
config := torrent.NewDefaultClientConfig()
config.SetListenAddr(":" + fmt.Sprint(port))
config.Seed = true
config.DataDir = m.torrentConfig.DataDir
if _, err := os.Stat(m.torrentConfig.DataDir); os.IsNotExist(err) {
err := os.MkdirAll(m.torrentConfig.DataDir, 0700)
if err != nil {
return err
}
}
m.logger.Info("Starting torrent client", zap.Any("port", port))
// Instantiating the client will make it bootstrap and listen eagerly,
// so no go routine is needed here
client, err := torrent.NewClient(config)
if err != nil {
return err
}
m.torrentClient = client
return nil
}
func (m *Manager) StopTorrentClient() []error {
if m.TorrentClientStarted() {
m.StopHistoryArchiveTasksIntervals()
m.logger.Info("Stopping torrent client")
errs := m.torrentClient.Close()
if len(errs) > 0 {
return errs
}
m.torrentClient = nil
}
return make([]error, 0)
}
func (m *Manager) TorrentClientStarted() bool {
return m.torrentClient != nil
}
func (m *Manager) publish(subscription *Subscription) {
if m.stopped {
return
}
for _, s := range m.subscriptions {
select {
case s <- subscription:
default:
m.logger.Warn("subscription channel full, dropping message")
}
}
}
func (m *Manager) All() ([]*Community, error) {
return m.persistence.AllCommunities(&m.identity.PublicKey)
}
type CommunityShard struct {
CommunityID string `json:"communityID"`
Shard *shard.Shard `json:"shard"`
}
type CuratedCommunities struct {
ContractCommunities []string
ContractFeaturedCommunities []string
}
type KnownCommunitiesResponse struct {
ContractCommunities []string `json:"contractCommunities"`
ContractFeaturedCommunities []string `json:"contractFeaturedCommunities"`
Descriptions map[string]*Community `json:"communities"`
UnknownCommunities []string `json:"unknownCommunities"`
}
func (m *Manager) GetStoredDescriptionForCommunities(communityIDs []string) (*KnownCommunitiesResponse, error) {
response := &KnownCommunitiesResponse{
Descriptions: make(map[string]*Community),
}
for i := range communityIDs {
communityID := communityIDs[i]
communityIDBytes, err := types.DecodeHex(communityID)
if err != nil {
return nil, err
}
community, err := m.GetByID(types.HexBytes(communityIDBytes))
if err != nil {
return nil, err
}
if community != nil {
response.Descriptions[community.IDString()] = community
} else {
response.UnknownCommunities = append(response.UnknownCommunities, communityID)
}
response.ContractCommunities = append(response.ContractCommunities, communityID)
}
return response, nil
}
func (m *Manager) Joined() ([]*Community, error) {
return m.persistence.JoinedCommunities(&m.identity.PublicKey)
}
func (m *Manager) Spectated() ([]*Community, error) {
return m.persistence.SpectatedCommunities(&m.identity.PublicKey)
}
func (m *Manager) CommunityUpdateLastOpenedAt(communityID types.HexBytes, timestamp int64) (*Community, error) {
community, err := m.GetByID(communityID)
if err != nil {
return nil, err
}
err = m.persistence.UpdateLastOpenedAt(community.ID(), timestamp)
if err != nil {
return nil, err
}
community.UpdateLastOpenedAt(timestamp)
return community, nil
}
func (m *Manager) JoinedAndPendingCommunitiesWithRequests() ([]*Community, error) {
return m.persistence.JoinedAndPendingCommunitiesWithRequests(&m.identity.PublicKey)
}
func (m *Manager) DeletedCommunities() ([]*Community, error) {
return m.persistence.DeletedCommunities(&m.identity.PublicKey)
}
func (m *Manager) Controlled() ([]*Community, error) {
communities, err := m.persistence.CommunitiesWithPrivateKey(&m.identity.PublicKey)
if err != nil {
return nil, err
}
controlled := make([]*Community, 0, len(communities))
for _, c := range communities {
if c.IsControlNode() {
controlled = append(controlled, c)
}
}
return controlled, nil
}
// CreateCommunity takes a description, generates an ID for it, saves it and return it
func (m *Manager) CreateCommunity(request *requests.CreateCommunity, publish bool) (*Community, error) {
description, err := request.ToCommunityDescription()
if err != nil {
return nil, err
}
description.Members = make(map[string]*protobuf.CommunityMember)
description.Members[common.PubkeyToHex(&m.identity.PublicKey)] = &protobuf.CommunityMember{Roles: []protobuf.CommunityMember_Roles{protobuf.CommunityMember_ROLE_OWNER}}
err = ValidateCommunityDescription(description)
if err != nil {
return nil, err
}
description.Clock = 1
key, err := crypto.GenerateKey()
if err != nil {
return nil, err
}
description.ID = types.EncodeHex(crypto.CompressPubkey(&key.PublicKey))
config := Config{
ID: &key.PublicKey,
PrivateKey: key,
ControlNode: &key.PublicKey,
ControlDevice: true,
Logger: m.logger,
Joined: true,
JoinedAt: time.Now().Unix(),
MemberIdentity: &m.identity.PublicKey,
CommunityDescription: description,
Shard: nil,
LastOpenedAt: 0,
}
var descriptionEncryptor DescriptionEncryptor
if m.encryptor != nil {
descriptionEncryptor = m
}
community, err := New(config, m.timesource, descriptionEncryptor)
if err != nil {
return nil, err
}
// We join any community we create
community.Join()
err = m.persistence.SaveCommunity(community)
if err != nil {
return nil, err
}
// Save grant for own community
grant, err := community.BuildGrant(&m.identity.PublicKey, "")
if err != nil {
return nil, err
}
err = m.persistence.SaveCommunityGrant(community.IDString(), grant, description.Clock)
if err != nil {
return nil, err
}
// Mark this device as the control node
syncControlNode := &protobuf.SyncCommunityControlNode{
Clock: 1,
InstallationId: m.installationID,
}
err = m.SaveSyncControlNode(community.ID(), syncControlNode)
if err != nil {
return nil, err
}
if publish {
m.publish(&Subscription{Community: community})
}
return community, nil
}
func (m *Manager) CreateCommunityTokenPermission(request *requests.CreateCommunityTokenPermission) (*Community, *CommunityChanges, error) {
community, err := m.GetByID(request.CommunityID)
if err != nil {
return nil, nil, err
}
// ensure key is generated before marshaling,
// as it requires key to encrypt description
if community.IsControlNode() && m.encryptor != nil {
key, err := m.encryptor.GenerateHashRatchetKey(community.ID())
if err != nil {
return nil, nil, err
}
keyID, err := key.GetKeyID()
if err != nil {
return nil, nil, err
}
m.logger.Info("generate key for token", zap.String("group-id", types.Bytes2Hex(community.ID())), zap.String("key-id", types.Bytes2Hex(keyID)))
}
community, changes, err := m.createCommunityTokenPermission(request, community)
if err != nil {
return nil, nil, err
}
err = m.saveAndPublish(community)
if err != nil {
return nil, nil, err
}
return community, changes, nil
}
func (m *Manager) EditCommunityTokenPermission(request *requests.EditCommunityTokenPermission) (*Community, *CommunityChanges, error) {
community, err := m.GetByID(request.CommunityID)
if err != nil {
return nil, nil, err
}
tokenPermission := request.ToCommunityTokenPermission()
changes, err := community.UpsertTokenPermission(&tokenPermission)
if err != nil {
return nil, nil, err
}
err = m.saveAndPublish(community)
if err != nil {
return nil, nil, err
}
return community, changes, nil
}
func (m *Manager) ReevaluateMembers(community *Community) (map[protobuf.CommunityMember_Roles][]*ecdsa.PublicKey, error) {
becomeMemberPermissions := community.TokenPermissionsByType(protobuf.CommunityTokenPermission_BECOME_MEMBER)
becomeAdminPermissions := community.TokenPermissionsByType(protobuf.CommunityTokenPermission_BECOME_ADMIN)
becomeTokenMasterPermissions := community.TokenPermissionsByType(protobuf.CommunityTokenPermission_BECOME_TOKEN_MASTER)
hasMemberPermissions := len(becomeMemberPermissions) > 0
newPrivilegedRoles := make(map[protobuf.CommunityMember_Roles][]*ecdsa.PublicKey)
newPrivilegedRoles[protobuf.CommunityMember_ROLE_TOKEN_MASTER] = []*ecdsa.PublicKey{}
newPrivilegedRoles[protobuf.CommunityMember_ROLE_ADMIN] = []*ecdsa.PublicKey{}
for memberKey := range community.Members() {
memberPubKey, err := common.HexToPubkey(memberKey)
if err != nil {
return nil, err
}
if memberKey == common.PubkeyToHex(&m.identity.PublicKey) || community.IsMemberOwner(memberPubKey) {
continue
}
isCurrentRoleTokenMaster := community.IsMemberTokenMaster(memberPubKey)
isCurrentRoleAdmin := community.IsMemberAdmin(memberPubKey)
requestID := CalculateRequestID(memberKey, community.ID())
revealedAccounts, err := m.persistence.GetRequestToJoinRevealedAddresses(requestID)
if err != nil {
return nil, err
}
memberHasWallet := len(revealedAccounts) > 0
// Check if user has privilege role without sharing the account to controlNode
// or user treated as a member without wallet in closed community
if !memberHasWallet && (hasMemberPermissions || isCurrentRoleTokenMaster || isCurrentRoleAdmin) {
_, err = community.RemoveUserFromOrg(memberPubKey)
if err != nil {
return nil, err
}
continue
}
accountsAndChainIDs := revealedAccountsToAccountsAndChainIDsCombination(revealedAccounts)
isNewRoleTokenMaster, err := m.ReevaluatePrivilegedMember(community, becomeTokenMasterPermissions, accountsAndChainIDs, memberPubKey,
protobuf.CommunityMember_ROLE_TOKEN_MASTER, isCurrentRoleTokenMaster)
if err != nil {
return nil, err
}
if isNewRoleTokenMaster {
if !isCurrentRoleTokenMaster {
newPrivilegedRoles[protobuf.CommunityMember_ROLE_TOKEN_MASTER] =
append(newPrivilegedRoles[protobuf.CommunityMember_ROLE_TOKEN_MASTER], memberPubKey)
}
// Skip further validation if user has TokenMaster permissions
continue
}
isNewRoleAdmin, err := m.ReevaluatePrivilegedMember(community, becomeAdminPermissions, accountsAndChainIDs, memberPubKey,