-
Notifications
You must be signed in to change notification settings - Fork 12
/
baseProxy.go
255 lines (211 loc) · 7.14 KB
/
baseProxy.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
package blockchain
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/multiversx/mx-chain-core-go/core/check"
"github.com/multiversx/mx-chain-core-go/data/transaction"
logger "github.com/multiversx/mx-chain-logger-go"
"github.com/multiversx/mx-sdk-go/core"
"github.com/multiversx/mx-sdk-go/data"
)
var log = logger.GetOrCreate("mx-sdk-go/blockchain")
const (
minimumCachingInterval = time.Second
)
type argsBaseProxy struct {
expirationTime time.Duration
httpClientWrapper httpClientWrapper
endpointProvider EndpointProvider
}
type baseProxy struct {
httpClientWrapper
mut sync.RWMutex
fetchedConfigs *data.NetworkConfig
lastFetchedTime time.Time
cacheExpiryDuration time.Duration
sinceTimeHandler func(t time.Time) time.Duration
endpointProvider EndpointProvider
}
// newBaseProxy will create a base multiversx proxy with cache instance
func newBaseProxy(args argsBaseProxy) (*baseProxy, error) {
err := checkArgsBaseProxy(args)
if err != nil {
return nil, err
}
return &baseProxy{
httpClientWrapper: args.httpClientWrapper,
cacheExpiryDuration: args.expirationTime,
endpointProvider: args.endpointProvider,
sinceTimeHandler: since,
}, nil
}
func checkArgsBaseProxy(args argsBaseProxy) error {
if args.expirationTime < minimumCachingInterval {
return fmt.Errorf("%w, provided: %v, minimum: %v", ErrInvalidCacherDuration, args.expirationTime, minimumCachingInterval)
}
if check.IfNil(args.httpClientWrapper) {
return ErrNilHTTPClientWrapper
}
if check.IfNil(args.endpointProvider) {
return ErrNilEndpointProvider
}
return nil
}
func since(t time.Time) time.Duration {
return time.Since(t)
}
// GetNetworkConfig will return the cached network configs fetching new values and saving them if necessary
func (proxy *baseProxy) GetNetworkConfig(ctx context.Context) (*data.NetworkConfig, error) {
proxy.mut.RLock()
cachedConfigs := proxy.getCachedConfigs()
proxy.mut.RUnlock()
if cachedConfigs != nil {
return cachedConfigs, nil
}
return proxy.cacheConfigs(ctx)
}
func (proxy *baseProxy) getCachedConfigs() *data.NetworkConfig {
if proxy.sinceTimeHandler(proxy.lastFetchedTime) > proxy.cacheExpiryDuration {
return nil
}
return proxy.fetchedConfigs
}
func (proxy *baseProxy) cacheConfigs(ctx context.Context) (*data.NetworkConfig, error) {
proxy.mut.Lock()
defer proxy.mut.Unlock()
// maybe another parallel running go routine already did the fetching
cachedConfig := proxy.getCachedConfigs()
if cachedConfig != nil {
return cachedConfig, nil
}
log.Debug("Network config not cached. caching...")
configs, err := proxy.getNetworkConfigFromSource(ctx)
if err != nil {
return nil, err
}
proxy.lastFetchedTime = time.Now()
proxy.fetchedConfigs = configs
return configs, nil
}
// getNetworkConfigFromSource retrieves the network configuration from the proxy
func (proxy *baseProxy) getNetworkConfigFromSource(ctx context.Context) (*data.NetworkConfig, error) {
buff, code, err := proxy.GetHTTP(ctx, proxy.endpointProvider.GetNetworkConfig())
if err != nil || code != http.StatusOK {
return nil, createHTTPStatusError(code, err)
}
response := &data.NetworkConfigResponse{}
err = json.Unmarshal(buff, response)
if err != nil {
return nil, err
}
if response.Error != "" {
return nil, errors.New(response.Error)
}
return response.Data.Config, nil
}
// GetShardOfAddress returns the shard ID of a provided address by using a shardCoordinator object and querying the
// network config route
func (proxy *baseProxy) GetShardOfAddress(ctx context.Context, bech32Address string) (uint32, error) {
addr, err := data.NewAddressFromBech32String(bech32Address)
if err != nil {
return 0, err
}
networkConfigs, err := proxy.GetNetworkConfig(ctx)
if err != nil {
return 0, err
}
shardCoordinatorInstance, err := NewShardCoordinator(networkConfigs.NumShardsWithoutMeta, 0)
if err != nil {
return 0, err
}
return shardCoordinatorInstance.ComputeShardId(addr)
}
// GetNetworkStatus will return the network status of a provided shard
func (proxy *baseProxy) GetNetworkStatus(ctx context.Context, shardID uint32) (*data.NetworkStatus, error) {
endpoint := proxy.endpointProvider.GetNodeStatus(shardID)
buff, code, err := proxy.GetHTTP(ctx, endpoint)
if err != nil || code != http.StatusOK {
return nil, createHTTPStatusError(code, err)
}
endpointProviderType := proxy.endpointProvider.GetRestAPIEntityType()
switch endpointProviderType {
case core.Proxy:
return proxy.getNetworkStatus(buff, shardID)
case core.ObserverNode:
return proxy.getNodeStatus(buff, shardID)
}
return &data.NetworkStatus{}, ErrInvalidEndpointProvider
}
func (proxy *baseProxy) getNetworkStatus(buff []byte, shardID uint32) (*data.NetworkStatus, error) {
response := &data.NetworkStatusResponse{}
err := json.Unmarshal(buff, response)
if err != nil {
return nil, err
}
if response.Error != "" {
return nil, errors.New(response.Error)
}
err = proxy.checkReceivedNodeStatus(response.Data.Status, shardID)
if err != nil {
return nil, err
}
return response.Data.Status, nil
}
func (proxy *baseProxy) getNodeStatus(buff []byte, shardID uint32) (*data.NetworkStatus, error) {
response := &data.NodeStatusResponse{}
err := json.Unmarshal(buff, response)
if err != nil {
return nil, err
}
if response.Error != "" {
return nil, errors.New(response.Error)
}
err = proxy.checkReceivedNodeStatus(response.Data.Status, shardID)
if err != nil {
return nil, err
}
return response.Data.Status, nil
}
func (proxy *baseProxy) checkReceivedNodeStatus(networkStatus *data.NetworkStatus, shardID uint32) error {
if networkStatus == nil {
return fmt.Errorf("%w, requested from %d", ErrNilNetworkStatus, shardID)
}
if !proxy.endpointProvider.ShouldCheckShardIDForNodeStatus() {
return nil
}
if networkStatus.ShardID == shardID {
return nil
}
return fmt.Errorf("%w, requested from %d, got response from %d", ErrShardIDMismatch, shardID, networkStatus.ShardID)
}
// GetRestAPIEntityType returns the REST API entity type that this implementation works with
func (proxy *baseProxy) GetRestAPIEntityType() core.RestAPIEntityType {
return proxy.endpointProvider.GetRestAPIEntityType()
}
// ProcessTransactionStatus will parse the provided transaction info and return its status accordingly
func (proxy *baseProxy) ProcessTransactionStatus(ctx context.Context, hexTxHash string) (transaction.TxStatus, error) {
endpoint := proxy.endpointProvider.GetProcessedTransactionStatus(hexTxHash)
buff, code, err := proxy.GetHTTP(ctx, endpoint)
if err != nil || code != http.StatusOK {
wrappedErr := fmt.Errorf("%w, please make sure you run the proxy version v1.1.38 or higher", err)
return transaction.TxStatusFail, createHTTPStatusError(code, wrappedErr)
}
response := &data.ProcessedTransactionStatus{}
err = json.Unmarshal(buff, response)
if err != nil {
return transaction.TxStatusFail, err
}
if response.Error != "" {
return transaction.TxStatusFail, errors.New(response.Error)
}
return transaction.TxStatus(response.Data.ProcessedStatus), nil
}
// IsInterfaceNil returns true if there is no value under the interface
func (proxy *baseProxy) IsInterfaceNil() bool {
return proxy == nil
}