-
Notifications
You must be signed in to change notification settings - Fork 182
/
util.go
328 lines (282 loc) · 7.49 KB
/
util.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
package common
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/okex/exchain/x/params/subspace"
"math/big"
"math/rand"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"testing"
"time"
sdkerrors "github.com/okex/exchain/libs/cosmos-sdk/types/errors"
apptypes "github.com/okex/exchain/app/types"
"github.com/okex/exchain/libs/cosmos-sdk/client/context"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
"github.com/okex/exchain/libs/cosmos-sdk/types/rest"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func InitConfig() {
config := sdk.GetConfig()
if config.GetBech32ConsensusAddrPrefix() == apptypes.Bech32PrefixConsAddr {
return
}
apptypes.SetBech32Prefixes(config)
apptypes.SetBip44CoinType(config)
config.Seal()
}
// Int64ToBytes converts int64 to bytes
func Int64ToBytes(i int64) []byte {
var buf = make([]byte, 8)
binary.BigEndian.PutUint64(buf, uint64(i))
return buf
}
// BytesToInt64 converts bytes to int64
func BytesToInt64(buf []byte) int64 {
return int64(binary.BigEndian.Uint64(buf))
}
// Paginate converts page params for a paginated query,
func Paginate(pageStr, perPageStr string) (page int, perPage int, err error) {
if pageStr != "" {
page, err = strconv.Atoi(pageStr)
if err != nil {
return
}
}
if perPageStr != "" {
perPage, err = strconv.Atoi(perPageStr)
if err != nil {
return
}
}
if page < 0 || perPage < 0 {
err = fmt.Errorf("negative page %d or per_page %d is invalid", page, perPage)
return
}
return
}
// GetPage returns the offset and limit for data query
func GetPage(page, perPage int) (offset, limit int) {
if page <= 0 || perPage <= 0 {
return
}
offset = (page - 1) * perPage
limit = perPage
return
}
// HandleErrorMsg handles the error msg
func HandleErrorMsg(w http.ResponseWriter, cliCtx context.CLIContext, code uint32, msg string) {
response := GetErrorResponseJSON(code, msg, msg)
rest.PostProcessResponse(w, cliCtx, response)
}
// HasSufficientCoins checks whether the account has sufficient coins
func HasSufficientCoins(addr sdk.AccAddress, availableCoins, amt sdk.Coins) (err error) {
//availableCoins := availCoins[:]
if !amt.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
if !availableCoins.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, amt.String())
}
_, hasNeg := availableCoins.SafeSub(amt)
if hasNeg {
return sdkerrors.Wrap(sdkerrors.ErrInsufficientFunds,
fmt.Sprintf("insufficient account funds;address: %s, availableCoin: %s, needCoin: %s",
addr.String(), availableCoins, amt),
)
}
return nil
}
// SkipSysTestChecker is supported to used in System Unit Test
// (described in http://gitlab.okcoin-inc.com/dex/okexchain/issues/472)
// if System environment variables "SYS_TEST_ALL" is set to 1, all of the system test will be enable. \n
// if System environment variables "ORM_MYSQL_SYS_TEST" is set to 1,
// all of the system test in orm_mysql_sys_test.go will be enble.
func SkipSysTestChecker(t *testing.T) {
_, fname, _, ok := runtime.Caller(0)
enable := ok
if enable {
enableAllEnv := "SYS_TEST_ALL"
sysTestName := strings.Split(fname, ".go")[0]
enableCurrent := strings.ToUpper(sysTestName)
enable = os.Getenv(enableAllEnv) == "1" ||
(strings.HasSuffix(sysTestName, "sys_test") && os.Getenv(enableCurrent) == "1")
}
if !enable {
t.SkipNow()
}
}
// mulAndQuo returns a * b / c
func MulAndQuo(a, b, c sdk.Dec) sdk.Dec {
// 10^8
auxiliaryDec := sdk.NewDecFromBigInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(sdk.Precision), nil))
a = a.MulTruncate(auxiliaryDec)
return a.MulTruncate(b).QuoTruncate(c).QuoTruncate(auxiliaryDec)
}
// BlackHoleAddress returns the black hole address
func BlackHoleAddress() sdk.AccAddress {
addr, _ := sdk.AccAddressFromHex(blackHoleHex)
return addr
}
func GetFixedLengthRandomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func PanicTrace(kb int) {
s := []byte("/src/runtime/panic.go")
e := []byte("\ngoroutine ")
line := []byte("\n")
stack := make([]byte, kb<<10) //4KB
length := runtime.Stack(stack, true)
start := bytes.Index(stack, s)
stack = stack[start:length]
start = bytes.Index(stack, line) + 1
stack = stack[start:]
end := bytes.LastIndex(stack, line)
if end != -1 {
stack = stack[:end]
}
end = bytes.Index(stack, e)
if end != -1 {
stack = stack[:end]
}
stack = bytes.TrimRight(stack, "\n")
fmt.Print(string(stack))
}
func SanityCheckHandler(res *sdk.Result, err error) {
if res == nil && err == nil {
panic("Invalid handler")
}
if res != nil && err != nil {
panic("Invalid handler")
}
}
func ValidateSysCoin(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(sdk.SysCoin)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if !v.IsValid() {
return fmt.Errorf("invalid %s: %s", param, v)
}
return nil
}
}
func ValidateSysCoins(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(sdk.SysCoins)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if !v.IsValid() {
return fmt.Errorf("invalid %s: %s", param, v)
}
return nil
}
}
func ValidateDurationPositive(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(time.Duration)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v <= 0 {
return fmt.Errorf("%s must be positive: %d", param, v)
}
return nil
}
}
func ValidateBool(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
_, ok := i.(bool)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
return nil
}
}
func ValidateInt64Positive(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(int64)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v <= 0 {
return fmt.Errorf("%s must be positive: %d", param, v)
}
return nil
}
}
func ValidateUint64Positive(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(uint64)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v == 0 {
return fmt.Errorf("%s must be positive: %d", param, v)
}
return nil
}
}
func ValidateRateNotNeg(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(sdk.Dec)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v.IsNegative() {
return fmt.Errorf("%s cannot be negative: %s", param, v)
}
if v.GT(sdk.OneDec()) {
return fmt.Errorf("%s is too large: %s", param, v)
}
return nil
}
}
func ValidateDecPositive(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(sdk.Dec)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if !v.IsPositive() {
return fmt.Errorf("%s must be positive: %s", param, v)
}
return nil
}
}
func ValidateDenom(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(string)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if sdk.ValidateDenom(v) != nil {
return fmt.Errorf("invalid %s", param)
}
return nil
}
}
func ValidateUint16Positive(param string) subspace.ValueValidatorFn {
return func(i interface{}) error {
v, ok := i.(uint16)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v == 0 {
return fmt.Errorf("%s must be positive: %d", param, v)
}
return nil
}
}