-
Notifications
You must be signed in to change notification settings - Fork 176
/
common.go
362 lines (309 loc) · 11.1 KB
/
common.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
package util
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"os"
"strconv"
"sync"
"time"
mLog "github.com/RichardKnop/machinery/v1/log"
cliContext "github.com/cosmos/cosmos-sdk/client/context"
"github.com/pkg/errors"
"github.com/spf13/viper"
"github.com/tendermint/tendermint/libs/log"
httpClient "github.com/tendermint/tendermint/rpc/client"
tmTypes "github.com/tendermint/tendermint/types"
authTypes "github.com/maticnetwork/heimdall/auth/types"
chainManagerTypes "github.com/maticnetwork/heimdall/chainmanager/types"
checkpointTypes "github.com/maticnetwork/heimdall/checkpoint/types"
"github.com/maticnetwork/heimdall/helper"
"github.com/maticnetwork/heimdall/types"
hmtypes "github.com/maticnetwork/heimdall/types"
)
const (
AccountDetailsURL = "/auth/accounts/%v"
LastNoAckURL = "/checkpoints/last-no-ack"
CheckpointParamsURL = "/checkpoints/params"
ChainManagerParamsURL = "/chainmanager/params"
ProposersURL = "/staking/proposer/%v"
BufferedCheckpointURL = "/checkpoints/buffer"
LatestCheckpointURL = "/checkpoints/latest"
CurrentProposerURL = "/staking/current-proposer"
LatestSpanURL = "/bor/latest-span"
NextSpanInfoURL = "/bor/prepare-next-span"
NextSpanSeedURL = "/bor/next-span-seed"
DividendAccountRootURL = "/topup/dividend-account-root"
ValidatorURL = "/staking/validator/%v"
CurrentValidatorSetURL = "staking/validator-set"
StakingTxStatusURL = "/staking/isoldtx"
TopupTxStatusURL = "/topup/isoldtx"
ClerkTxStatusURL = "/clerk/isoldtx"
LatestSlashInfoBytesURL = "/slashing/latest_slash_info_bytes"
TickSlashInfoListURL = "/slashing/tick_slash_infos"
SlashingTxStatusURL = "/slashing/isoldtx"
SlashingTickCountURL = "/slashing/tick-count"
TransactionTimeout = 1 * time.Minute
CommitTimeout = 2 * time.Minute
TaskDelayBetweenEachVal = 6 * time.Second
RetryTaskDelay = 12 * time.Second
BridgeDBFlag = "bridge-db"
)
var logger log.Logger
var loggerOnce sync.Once
// Logger returns logger singleton instance
func Logger() log.Logger {
loggerOnce.Do(func() {
logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout))
option, _ := log.AllowLevel(viper.GetString("log_level"))
logger = log.NewFilter(logger, option)
// set no-op logger if log level is not debug for machinery
if viper.GetString("log_level") != "debug" {
mLog.SetDebug(NoopLogger{})
}
})
return logger
}
// IsProposer checks if we are proposer
func IsProposer(cliCtx cliContext.CLIContext) (bool, error) {
var proposers []hmtypes.Validator
count := uint64(1)
result, err := helper.FetchFromAPI(cliCtx,
helper.GetHeimdallServerEndpoint(fmt.Sprintf(ProposersURL, strconv.FormatUint(count, 10))),
)
if err != nil {
logger.Error("Error fetching proposers", "url", ProposersURL, "error", err)
return false, err
}
err = json.Unmarshal(result.Result, &proposers)
if err != nil {
logger.Error("error unmarshalling proposer slice", "error", err)
return false, err
}
if bytes.Equal(proposers[0].Signer.Bytes(), helper.GetAddress()) {
return true, nil
}
return false, nil
}
// IsInProposerList checks if we are in current proposer
func IsInProposerList(cliCtx cliContext.CLIContext, count uint64) (bool, error) {
logger.Debug("Skipping proposers", "count", strconv.FormatUint(count, 10))
response, err := helper.FetchFromAPI(
cliCtx,
helper.GetHeimdallServerEndpoint(fmt.Sprintf(ProposersURL, strconv.FormatUint(count, 10))),
)
if err != nil {
logger.Error("Unable to send request for next proposers", "url", ProposersURL, "error", err)
return false, err
}
// unmarshall data from buffer
var proposers []hmtypes.Validator
if err := json.Unmarshal(response.Result, &proposers); err != nil {
logger.Error("Error unmarshalling validator data ", "error", err)
return false, err
}
logger.Debug("Fetched proposers list", "numberOfProposers", count)
for _, proposer := range proposers {
if bytes.Equal(proposer.Signer.Bytes(), helper.GetAddress()) {
return true, nil
}
}
return false, nil
}
// CalculateTaskDelay calculates delay required for current validator to propose the tx
// It solves for multiple validators sending same transaction.
func CalculateTaskDelay(cliCtx cliContext.CLIContext) (bool, time.Duration) {
// calculate validator position
valPosition := 0
isCurrentValidator := false
response, err := helper.FetchFromAPI(cliCtx, helper.GetHeimdallServerEndpoint(CurrentValidatorSetURL))
if err != nil {
logger.Error("Unable to send request for current validatorset", "url", CurrentValidatorSetURL, "error", err)
return isCurrentValidator, 0
}
// unmarshall data from buffer
var validatorSet hmtypes.ValidatorSet
err = json.Unmarshal(response.Result, &validatorSet)
if err != nil {
logger.Error("Error unmarshalling current validatorset data ", "error", err)
return isCurrentValidator, 0
}
logger.Info("Fetched current validatorset list", "currentValidatorcount", len(validatorSet.Validators))
for i, validator := range validatorSet.Validators {
if bytes.Equal(validator.Signer.Bytes(), helper.GetAddress()) {
valPosition = i + 1
isCurrentValidator = true
break
}
}
// calculate delay
taskDelay := time.Duration(valPosition) * TaskDelayBetweenEachVal
return isCurrentValidator, taskDelay
}
// IsCurrentProposer checks if we are current proposer
func IsCurrentProposer(cliCtx cliContext.CLIContext) (bool, error) {
var proposer hmtypes.Validator
result, err := helper.FetchFromAPI(cliCtx, helper.GetHeimdallServerEndpoint(CurrentProposerURL))
if err != nil {
logger.Error("Error fetching proposers", "error", err)
return false, err
}
err = json.Unmarshal(result.Result, &proposer)
if err != nil {
logger.Error("error unmarshalling validator", "error", err)
return false, err
}
logger.Debug("Current proposer fetched", "validator", proposer.String())
if bytes.Equal(proposer.Signer.Bytes(), helper.GetAddress()) {
return true, nil
}
return false, nil
}
// IsEventSender check if we are the EventSender
func IsEventSender(cliCtx cliContext.CLIContext, validatorID uint64) bool {
var validator hmtypes.Validator
result, err := helper.FetchFromAPI(cliCtx,
helper.GetHeimdallServerEndpoint(fmt.Sprintf(ValidatorURL, strconv.FormatUint(validatorID, 10))),
)
if err != nil {
logger.Error("Error fetching proposers", "error", err)
return false
}
err = json.Unmarshal(result.Result, &validator)
if err != nil {
logger.Error("error unmarshalling proposer slice", "error", err)
return false
}
logger.Debug("Current event sender received", "validator", validator.String())
return bytes.Equal(validator.Signer.Bytes(), helper.GetAddress())
}
//CreateURLWithQuery receives the uri and parameters in key value form
//it will return the new url with the given query from the parameter
func CreateURLWithQuery(uri string, param map[string]interface{}) (string, error) {
urlObj, err := url.Parse(uri)
if err != nil {
return uri, err
}
query := urlObj.Query()
for k, v := range param {
query.Set(k, fmt.Sprintf("%v", v))
}
urlObj.RawQuery = query.Encode()
return urlObj.String(), nil
}
// WaitForOneEvent subscribes to a websocket event for the given
// event time and returns upon receiving it one time, or
// when the timeout duration has expired.
//
// This handles subscribing and unsubscribing under the hood
func WaitForOneEvent(tx tmTypes.Tx, client *httpClient.HTTP) (tmTypes.TMEventData, error) {
ctx, cancel := context.WithTimeout(context.Background(), CommitTimeout)
defer cancel()
// subscriber
subscriber := hex.EncodeToString(tx.Hash())
// query
query := tmTypes.EventQueryTxFor(tx).String()
// register for the next event of this type
eventCh, err := client.Subscribe(ctx, subscriber, query)
if err != nil {
return nil, errors.Wrap(err, "failed to subscribe")
}
// make sure to unregister after the test is over
defer func() {
if err := client.UnsubscribeAll(ctx, subscriber); err != nil {
logger.Error("WaitForOneEvent | UnsubscribeAll", "Error", err)
}
}()
select {
case event := <-eventCh:
return event.Data.(tmTypes.TMEventData), nil
case <-ctx.Done():
return nil, errors.New("timed out waiting for event")
}
}
// IsCatchingUp checks if the heimdall node you are connected to is fully synced or not
// returns true when synced
func IsCatchingUp(cliCtx cliContext.CLIContext) bool {
resp, err := helper.GetNodeStatus(cliCtx)
if err != nil {
return true
}
return resp.SyncInfo.CatchingUp
}
// GetAccount returns heimdall auth account
func GetAccount(cliCtx cliContext.CLIContext, address types.HeimdallAddress) (account authTypes.Account, err error) {
url := helper.GetHeimdallServerEndpoint(fmt.Sprintf(AccountDetailsURL, address))
// call account rest api
response, err := helper.FetchFromAPI(cliCtx, url)
if err != nil {
return
}
if err = cliCtx.Codec.UnmarshalJSON(response.Result, &account); err != nil {
logger.Error("Error unmarshalling account details", "url", url)
return
}
return
}
// GetChainmanagerParams return chain manager params
func GetChainmanagerParams(cliCtx cliContext.CLIContext) (*chainManagerTypes.Params, error) {
response, err := helper.FetchFromAPI(
cliCtx,
helper.GetHeimdallServerEndpoint(ChainManagerParamsURL),
)
if err != nil {
logger.Error("Error fetching chainmanager params", "err", err)
return nil, err
}
var params chainManagerTypes.Params
if err := json.Unmarshal(response.Result, ¶ms); err != nil {
logger.Error("Error unmarshalling chainmanager params", "url", ChainManagerParamsURL, "err", err)
return nil, err
}
return ¶ms, nil
}
// GetCheckpointParams return params
func GetCheckpointParams(cliCtx cliContext.CLIContext) (*checkpointTypes.Params, error) {
response, err := helper.FetchFromAPI(
cliCtx,
helper.GetHeimdallServerEndpoint(CheckpointParamsURL),
)
if err != nil {
logger.Error("Error fetching Checkpoint params", "err", err)
return nil, err
}
var params checkpointTypes.Params
if err := json.Unmarshal(response.Result, ¶ms); err != nil {
logger.Error("Error unmarshalling Checkpoint params", "url", CheckpointParamsURL)
return nil, err
}
return ¶ms, nil
}
// GetBufferedCheckpoint return checkpoint from bueffer
func GetBufferedCheckpoint(cliCtx cliContext.CLIContext) (*hmtypes.Checkpoint, error) {
response, err := helper.FetchFromAPI(
cliCtx,
helper.GetHeimdallServerEndpoint(BufferedCheckpointURL),
)
if err != nil {
logger.Debug("Error fetching buffered checkpoint", "err", err)
return nil, err
}
var checkpoint hmtypes.Checkpoint
if err := json.Unmarshal(response.Result, &checkpoint); err != nil {
logger.Error("Error unmarshalling buffered checkpoint", "url", BufferedCheckpointURL, "err", err)
return nil, err
}
return &checkpoint, nil
}
// AppendPrefix returns publickey in uncompressed format
func AppendPrefix(signerPubKey []byte) []byte {
// append prefix - "0x04" as heimdall uses publickey in uncompressed format. Refer below link
// https://superuser.com/questions/1465455/what-is-the-size-of-public-key-for-ecdsa-spec256r1
prefix := make([]byte, 1)
prefix[0] = byte(0x04)
signerPubKey = append(prefix[:], signerPubKey[:]...)
return signerPubKey
}