-
Notifications
You must be signed in to change notification settings - Fork 39
/
client.go
90 lines (72 loc) · 2.17 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
package client
import (
"context"
"os"
"path/filepath"
"sync"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/stratosnet/sds/cmd/relayd/setting"
"github.com/stratosnet/sds/relay/stratoschain/grpc"
"github.com/stratosnet/sds/utils"
"github.com/stratosnet/sds/utils/crypto/secp256k1"
"github.com/stratosnet/sds/utils/types"
)
type MultiClient struct {
cancel context.CancelFunc
Ctx context.Context
once *sync.Once
sdsConn connection
stchainConn connection
WalletAddress string
WalletPrivateKey cryptotypes.PrivKey
}
// connection is a generic interface for a client connection to an external service (sds or stchain)
type connection interface {
stop()
refresh() // Stop the connection if it was already started, then re-establish the connection
}
func NewClient(spHomePath string) (*MultiClient, error) {
ctx, cancel := context.WithCancel(context.Background())
newClient := &MultiClient{
cancel: cancel,
Ctx: ctx,
once: &sync.Once{},
}
newClient.sdsConn = newSdsConnection(newClient)
newClient.stchainConn = newStchainConnection(newClient)
err := newClient.loadKeys(spHomePath)
return newClient, err
}
func (m *MultiClient) loadKeys(spHomePath string) error {
walletJson, err := os.ReadFile(filepath.Join(spHomePath, setting.Config.Keys.WalletPath))
if err != nil {
return err
}
walletKey, err := utils.DecryptKey(walletJson, setting.Config.Keys.WalletPassword)
if err != nil {
return err
}
m.WalletPrivateKey = secp256k1.PrivKeyToSdkPrivKey(walletKey.PrivateKey)
m.WalletAddress, err = types.BytesToAddress(m.WalletPrivateKey.PubKey().Address()).WalletAddressToBech()
if err != nil {
return err
}
utils.DebugLogf("verified wallet key successfully! walletAddr is %v", m.WalletAddress)
return nil
}
func (m *MultiClient) Start() error {
// GRPC client to send msgs to stratos-chain
grpc.SERVER = setting.Config.StratosChain.GrpcServer.GrpcServer
grpc.INSECURE = setting.Config.StratosChain.GrpcServer.Insecure
// Start client connections
go m.sdsConn.refresh()
go m.stchainConn.refresh()
return nil
}
func (m *MultiClient) Stop() {
m.once.Do(func() {
m.cancel()
m.sdsConn.stop()
m.stchainConn.stop()
})
}