/
eth_proxy.go
240 lines (217 loc) · 6 KB
/
eth_proxy.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
package onchain
import (
"context"
"strconv"
"strings"
"time"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/DOSNetwork/core/configuration"
"github.com/DOSNetwork/core/onchain/commitreveal"
"github.com/DOSNetwork/core/onchain/dosbridge"
"github.com/DOSNetwork/core/onchain/dosproxy"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
errors "golang.org/x/xerrors"
)
const (
//TrafficSystemRandom is a request type to build a corresponding pipeline
TrafficSystemRandom = iota // 0
//TrafficUserRandom is a request type to build a corresponding pipeline
TrafficUserRandom
//TrafficUserQuery is a request type to build a corresponding pipeline
TrafficUserQuery
)
type logger interface {
Info(msg string)
Error(err error)
TimeTrack(start time.Time, e string, info map[string]interface{})
Event(e string, info map[string]interface{})
}
type ethAdaptor struct {
logger
bridgeAddr common.Address
proxyAddr common.Address
commitRevealAddr common.Address
bootStrapUrl string
httpUrls []string
wsUrls []string
key *keystore.Key
gasPrice int64
gasLimit int64
connTimeout time.Duration
getTimeout time.Duration
setTimeout time.Duration
proxies []*dosproxy.DosproxySession
crs []*commitreveal.CommitrevealSession
clients []*ethclient.Client
ctxes []context.Context
cancels []context.CancelFunc
ctx context.Context
cancelFunc context.CancelFunc
reqQueue chan *request
}
//NewEthAdaptor creates an eth implemention of ProxyAdapter
func NewEthAdaptor(key *keystore.Key, config *configuration.Config, l logger) (adaptor *ethAdaptor, err error) {
if key == nil {
return nil, errors.New("no keystore")
}
if !common.IsHexAddress(config.DOSAddressBridgeAddress) {
return nil, errors.New("not a valid hex address")
}
gasLimitInt, err := strconv.Atoi(config.EthGasLimit)
if err != nil {
return nil, err
}
adaptor = ðAdaptor{}
adaptor.bridgeAddr = common.HexToAddress(config.DOSAddressBridgeAddress)
adaptor.key = key
adaptor.logger = l
adaptor.reqQueue = make(chan *request)
adaptor.gasLimit = int64(gasLimitInt)
adaptor.connTimeout = 60 * time.Second
adaptor.getTimeout = 60 * time.Second
adaptor.setTimeout = 60 * time.Second
return
}
//End close the connection to eth and release all resources
func (e *ethAdaptor) DisconnectAll() {
e.cancelFunc()
for {
if !e.isConnecting() {
return
}
}
return
}
func (e *ethAdaptor) Disconnect(idx int) {
if e.cancels[idx] != nil {
e.cancels[idx]()
}
return
}
func (e *ethAdaptor) isConnecting() (result bool) {
if e.ctx == nil {
return
}
select {
case <-e.ctx.Done():
return
default:
}
for _, ctx := range e.ctxes {
select {
case <-ctx.Done():
default:
result = true
return
}
}
return
}
func (e *ethAdaptor) Connect(urls []string, t time.Time) (err error) {
if e.isConnecting() {
err = errors.Errorf("connection existing")
return
}
var httpUrls []string
var wsUrls []string
for _, url := range urls {
if strings.Contains(url, "http") {
httpUrls = append(httpUrls, url)
} else if strings.Contains(url, "ws") {
wsUrls = append(wsUrls, url)
}
}
e.wsUrls = wsUrls
if len(wsUrls) == 0 {
return errors.New("no web socket URL")
}
e.ctx, e.cancelFunc = context.WithCancel(context.Background())
e.clients = nil
e.proxies = nil
e.crs = nil
e.ctxes = nil
e.cancels = nil
dialCtx, dialCancel := context.WithDeadline(e.ctx, t)
defer dialCancel()
results := DialToEth(dialCtx, e.wsUrls)
for result := range results {
if result.Err != nil {
e.logger.Error(errors.Errorf(": %w", result.Err))
continue
}
client := result.Client
bridge, err := dosbridge.NewDosbridge(e.bridgeAddr, client)
if err != nil {
e.logger.Error(errors.Errorf(": %w", err))
client.Close()
continue
}
proxyAddr, err := bridge.GetProxyAddress(&bind.CallOpts{Context: dialCtx})
if err != nil {
e.logger.Error(errors.Errorf(": %w", err))
client.Close()
continue
}
commitRevealAddr, err := bridge.GetCommitRevealAddress(&bind.CallOpts{Context: dialCtx})
if err != nil {
e.logger.Error(errors.Errorf(": %w", err))
client.Close()
continue
}
bootStrapUrl, err := bridge.GetBootStrapUrl(&bind.CallOpts{Context: dialCtx})
if err != nil {
e.logger.Error(errors.Errorf(": %w", err))
client.Close()
continue
}
p, err := dosproxy.NewDosproxy(proxyAddr, client)
if err != nil {
err = errors.Errorf("NewDosproxy failed: %w", err)
e.logger.Error(err)
client.Close()
continue
}
cr, err := commitreveal.NewCommitreveal(commitRevealAddr, client)
if err != nil {
err = errors.Errorf("NewCommitreveal failed : %w", err)
e.logger.Error(err)
client.Close()
continue
}
e.logger.Event("ConnToOnchain", map[string]interface{}{"OnchainURL": result.Url})
ctx, cancel := context.WithCancel(e.ctx)
ctx = context.WithValue(ctx, "index", len(e.ctxes))
auth := bind.NewKeyedTransactor(e.key.PrivateKey)
auth.GasLimit = uint64(e.gasLimit)
auth.Context = ctx
if bootStrapUrl != "" {
e.bootStrapUrl = bootStrapUrl
}
e.clients = append(e.clients, client)
e.proxies = append(e.proxies, &dosproxy.DosproxySession{Contract: p, CallOpts: bind.CallOpts{Context: ctx}, TransactOpts: *auth})
e.crs = append(e.crs, &commitreveal.CommitrevealSession{Contract: cr, CallOpts: bind.CallOpts{Context: ctx}, TransactOpts: *auth})
e.ctxes = append(e.ctxes, ctx)
e.cancels = append(e.cancels, cancel)
}
if len(e.proxies) == 0 {
err = errors.New("no proxy instance")
e.logger.Error(err)
return
}
if len(e.crs) == 0 {
err = errors.New("no commir reveal instance")
e.logger.Error(err)
return
}
go e.ReqLoop()
return
}
func (e *ethAdaptor) BootStrapUrl() string {
return e.bootStrapUrl
}
// Address gets the string representation of the underlying address.
func (e *ethAdaptor) Address() (addr common.Address) {
return e.key.Address
}