This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
/
helpers.go
514 lines (432 loc) · 14.8 KB
/
helpers.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package lcdtest
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"sort"
"strings"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/lcd"
"github.com/cosmos/cosmos-sdk/codec"
codecstd "github.com/cosmos/cosmos-sdk/codec/std"
keyring "github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/store"
"github.com/cosmos/cosmos-sdk/tests"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/crisis"
distr "github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/mint"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply"
"github.com/pkg/errors"
"github.com/spf13/viper"
tmcfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
nm "github.com/tendermint/tendermint/node"
"github.com/tendermint/tendermint/p2p"
pvm "github.com/tendermint/tendermint/privval"
"github.com/tendermint/tendermint/proxy"
tmrpc "github.com/tendermint/tendermint/rpc/lib/server"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/bandprotocol/goldcdp/app"
)
var (
cdc = codecstd.MakeCodec(app.ModuleBasics)
appCodec = codecstd.NewAppCodec(cdc)
)
func init() {
authclient.Codec = appCodec
}
// TODO: Make InitializeTestLCD safe to call in multiple tests at the same time
// InitializeLCD starts Tendermint and the LCD in process, listening on
// their respective sockets where nValidators is the total number of validators
// and initAddrs are the accounts to initialize with some stake tokens. It
// returns a cleanup function, a set of validator public keys, and a port.
func InitializeLCD(
nValidators int, initAddrs []sdk.AccAddress, minting bool, portExt ...string,
) (cleanup func(), valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, port string, err error) {
config, err := GetConfig()
if err != nil {
return
}
config.Consensus.TimeoutCommit = 100
config.Consensus.SkipTimeoutCommit = false
config.TxIndex.IndexAllKeys = true
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
logger = log.NewFilter(logger, log.AllowError())
db := dbm.NewMemDB()
bcapp := app.NewBandConsumerApp(logger, db, nil, true, 0, map[int64]bool{}, "", baseapp.SetPruning(store.PruneNothing))
genDoc, valConsPubKeys, valOperAddrs, privVal, err := defaultGenesis(config, nValidators, initAddrs, minting)
if err != nil {
return
}
var listenAddr string
if len(portExt) == 0 {
listenAddr, port, err = server.FreeTCPAddr()
if err != nil {
return
}
} else {
listenAddr = fmt.Sprintf("tcp://0.0.0.0:%s", portExt[0])
port = portExt[0]
}
// XXX: Need to set this so LCD knows the tendermint node address!
viper.Set(flags.FlagNode, config.RPC.ListenAddress)
viper.Set(flags.FlagChainID, genDoc.ChainID)
// TODO Set to false once the upstream Tendermint proof verification issue is fixed.
viper.Set(flags.FlagTrustNode, true)
node, err := startTM(config, logger, genDoc, privVal, bcapp)
if err != nil {
return
}
tests.WaitForNextHeightTM(tests.ExtractPortFromAddress(config.RPC.ListenAddress))
lcdInstance, err := startLCD(logger, listenAddr, cdc)
if err != nil {
return
}
tests.WaitForLCDStart(port)
tests.WaitForHeight(1, port)
cleanup = func() {
logger.Debug("cleaning up LCD initialization")
err = node.Stop()
if err != nil {
logger.Error(err.Error())
}
node.Wait()
err = lcdInstance.Close()
if err != nil {
logger.Error(err.Error())
}
}
return cleanup, valConsPubKeys, valOperAddrs, port, err
}
func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAddress, minting bool) (
genDoc *tmtypes.GenesisDoc, valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, privVal *pvm.FilePV, err error) {
privVal = pvm.LoadOrGenFilePV(config.PrivValidatorKeyFile(),
config.PrivValidatorStateFile())
privVal.Reset()
if nValidators < 1 {
err = errors.New("initializeLCD must use at least one validator")
return
}
genesisFile := config.GenesisFile()
genDoc, err = tmtypes.GenesisDocFromFile(genesisFile)
if err != nil {
return
}
genDoc.Validators = nil
err = genDoc.SaveAs(genesisFile)
if err != nil {
return
}
// append any additional (non-proposing) validators
//nolint:prealloc
var (
genTxs []auth.StdTx
genAccounts []authexported.GenesisAccount
genBalances []bank.Balance
)
totalSupply := sdk.ZeroInt()
for i := 0; i < nValidators; i++ {
operPrivKey := secp256k1.GenPrivKey()
operAddr := operPrivKey.PubKey().Address()
pubKey := privVal.GetPubKey()
power := int64(100)
if i > 0 {
pubKey = ed25519.GenPrivKey().PubKey()
power = 1
}
startTokens := sdk.TokensFromConsensusPower(power)
msg := staking.NewMsgCreateValidator(
sdk.ValAddress(operAddr),
pubKey,
sdk.NewCoin(sdk.DefaultBondDenom, startTokens),
staking.NewDescription(fmt.Sprintf("validator-%d", i+1), "", "", "", ""),
staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
sdk.OneInt(),
)
stdSignMsg := auth.StdSignMsg{
ChainID: genDoc.ChainID,
Msgs: []sdk.Msg{msg},
}
var sig []byte
sig, err = operPrivKey.Sign(stdSignMsg.Bytes())
if err != nil {
return
}
transaction := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{{Signature: sig, PubKey: operPrivKey.PubKey().Bytes()}}, "")
genTxs = append(genTxs, transaction)
valConsPubKeys = append(valConsPubKeys, pubKey)
valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr))
account := auth.NewBaseAccountWithAddress(sdk.AccAddress(operAddr))
accTokens := sdk.TokensFromConsensusPower(150)
totalSupply = totalSupply.Add(accTokens)
coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, accTokens))
genBalances = append(genBalances, bank.Balance{Address: account.GetAddress(), Coins: coins})
genAccounts = append(genAccounts, account)
}
genesisState := app.NewDefaultGenesisState()
genDoc.AppState, err = cdc.MarshalJSON(genesisState)
if err != nil {
return
}
genesisState, err = genutil.SetGenTxsInAppGenesisState(cdc, genesisState, genTxs)
if err != nil {
return
}
// add some tokens to init accounts
for _, addr := range initAddrs {
accAuth := auth.NewBaseAccountWithAddress(addr)
accTokens := sdk.TokensFromConsensusPower(100)
totalSupply = totalSupply.Add(accTokens)
coins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, accTokens))
genBalances = append(genBalances, bank.Balance{Address: accAuth.GetAddress(), Coins: coins})
genAccounts = append(genAccounts, accAuth)
}
// auth genesis state: params and genesis accounts
var authGenState auth.GenesisState
cdc.MustUnmarshalJSON(genesisState[auth.ModuleName], &authGenState)
authGenState.Accounts = genAccounts
genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenState)
var bankGenState bank.GenesisState
cdc.MustUnmarshalJSON(genesisState[bank.ModuleName], &bankGenState)
bankGenState.Balances = genBalances
genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenState)
var stakingData staking.GenesisState
cdc.MustUnmarshalJSON(genesisState[staking.ModuleName], &stakingData)
genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingData)
// distr data
var distrData distr.GenesisState
cdc.MustUnmarshalJSON(genesisState[distr.ModuleName], &distrData)
commPoolAmt := sdk.NewInt(10)
distrData.FeePool.CommunityPool = sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, commPoolAmt)}
genesisState[distr.ModuleName] = cdc.MustMarshalJSON(distrData)
// supply data
var supplyData supply.GenesisState
cdc.MustUnmarshalJSON(genesisState[supply.ModuleName], &supplyData)
supplyData.Supply = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply.Add(commPoolAmt)))
genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyData)
// mint genesis (none set within genesisState)
mintData := mint.DefaultGenesisState()
inflationMin := sdk.ZeroDec()
if minting {
inflationMin = sdk.MustNewDecFromStr("0.9")
mintData.Params.InflationMax = sdk.MustNewDecFromStr("1.0")
} else {
mintData.Params.InflationMax = inflationMin
}
mintData.Minter.Inflation = inflationMin
mintData.Params.InflationMin = inflationMin
genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintData)
// initialize crisis data
var crisisData crisis.GenesisState
cdc.MustUnmarshalJSON(genesisState[crisis.ModuleName], &crisisData)
crisisData.ConstantFee = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000)
genesisState[crisis.ModuleName] = cdc.MustMarshalJSON(crisisData)
//// double check inflation is set according to the minting boolean flag
if minting {
if !(mintData.Params.InflationMax.Equal(sdk.MustNewDecFromStr("1.0")) &&
mintData.Minter.Inflation.Equal(sdk.MustNewDecFromStr("0.9")) &&
mintData.Params.InflationMin.Equal(sdk.MustNewDecFromStr("0.9"))) {
err = errors.New("mint parameters does not correspond to their defaults")
return
}
} else {
if !(mintData.Params.InflationMax.Equal(sdk.ZeroDec()) &&
mintData.Minter.Inflation.Equal(sdk.ZeroDec()) &&
mintData.Params.InflationMin.Equal(sdk.ZeroDec())) {
err = errors.New("mint parameters not equal to decimal 0")
return
}
}
appState, err := codec.MarshalJSONIndent(cdc, genesisState)
if err != nil {
return
}
genDoc.AppState = appState
return genDoc, valConsPubKeys, valOperAddrs, privVal, err
}
// startTM creates and starts an in-process Tendermint node with memDB and
// in-process ABCI application. It returns the new node or any error that
// occurred.
//
// TODO: Clean up the WAL dir or enable it to be not persistent!
func startTM(
tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc,
privVal tmtypes.PrivValidator, app *app.BandConsumerApp,
) (*nm.Node, error) {
genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil }
dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil }
nodeKey, err := p2p.LoadOrGenNodeKey(tmcfg.NodeKeyFile())
if err != nil {
return nil, err
}
node, err := nm.NewNode(
tmcfg,
privVal,
nodeKey,
proxy.NewLocalClientCreator(app),
genDocProvider,
dbProvider,
nm.DefaultMetricsProvider(tmcfg.Instrumentation),
logger.With("module", "node"),
)
if err != nil {
return nil, err
}
err = node.Start()
if err != nil {
return nil, err
}
tests.WaitForRPC(tmcfg.RPC.ListenAddress)
logger.Info("Tendermint running!")
return node, err
}
// startLCD starts the LCD.
func startLCD(logger log.Logger, listenAddr string, cdc *codec.Codec) (net.Listener, error) {
rs := lcd.NewRestServer(cdc)
registerRoutes(rs)
listener, err := tmrpc.Listen(listenAddr, tmrpc.DefaultConfig())
if err != nil {
return nil, err
}
go tmrpc.StartHTTPServer(listener, rs.Mux, logger, tmrpc.DefaultConfig()) //nolint:errcheck
return listener, nil
}
// NOTE: If making updates here also update cmd/gaia/cmd/gaiacli/main.go
func registerRoutes(rs *lcd.RestServer) {
client.RegisterRoutes(rs.CliCtx, rs.Mux)
authrest.RegisterTxRoutes(rs.CliCtx, rs.Mux)
app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux)
}
// CreateAddr adds an address to the key store and returns an address and seed.
// It also requires that the key could be created.
func CreateAddr(name string, kb keyring.Keybase) (sdk.AccAddress, string, error) {
var (
err error
info keyring.Info
seed string
)
info, seed, err = kb.CreateMnemonic(name, keyring.English, keys.DefaultKeyPass, keyring.Secp256k1)
return sdk.AccAddress(info.GetPubKey().Address()), seed, err
}
// CreateAddrs adds multiple address to the key store and returns the addresses and associated seeds in lexographical order by address.
// It also requires that the keys could be created.
func CreateAddrs(kb keyring.Keybase, numAddrs int) (addrs []sdk.AccAddress, seeds, names []string, errs []error) {
var (
err error
info keyring.Info
seed string
)
addrSeeds := AddrSeedSlice{}
for i := 0; i < numAddrs; i++ {
name := fmt.Sprintf("test%d", i)
info, seed, err = kb.CreateMnemonic(name, keyring.English, keys.DefaultKeyPass, keyring.Secp256k1)
if err != nil {
errs = append(errs, err)
}
addrSeeds = append(addrSeeds, AddrSeed{Address: sdk.AccAddress(info.GetPubKey().Address()), Seed: seed, Name: name})
}
if len(errs) > 0 {
return
}
sort.Sort(addrSeeds)
for i := range addrSeeds {
addrs = append(addrs, addrSeeds[i].Address)
seeds = append(seeds, addrSeeds[i].Seed)
names = append(names, addrSeeds[i].Name)
}
return addrs, seeds, names, errs
}
// AddrSeed combines an Address with the mnemonic of the private key to that address
type AddrSeed struct {
Address sdk.AccAddress
Seed string
Name string
}
// AddrSeedSlice implements `Interface` in sort package.
type AddrSeedSlice []AddrSeed
func (b AddrSeedSlice) Len() int {
return len(b)
}
// Less sorts lexicographically by Address
func (b AddrSeedSlice) Less(i, j int) bool {
// bytes package already implements Comparable for []byte.
switch bytes.Compare(b[i].Address.Bytes(), b[j].Address.Bytes()) {
case -1:
return true
case 0, 1:
return false
default:
panic("not fail-able with `bytes.Comparable` bounded [-1, 1].")
}
}
func (b AddrSeedSlice) Swap(i, j int) {
b[j], b[i] = b[i], b[j]
}
// InitClientHome initialises client home dir.
func InitClientHome(dir string) string {
var err error
if dir == "" {
dir, err = ioutil.TempDir("", "lcd_test")
if err != nil {
panic(err)
}
}
// TODO: this should be set in NewRestServer
// and pass down the CLIContext to achieve
// parallelism.
viper.Set(cli.HomeFlag, dir)
return dir
}
// makePathname creates a unique pathname for each test.
func makePathname() (string, error) {
p, err := os.Getwd()
if err != nil {
return "", err
}
sep := string(filepath.Separator)
return strings.Replace(p, sep, "_", -1), nil
}
// GetConfig returns a Tendermint config for the test cases.
func GetConfig() (*tmcfg.Config, error) {
pathname, err := makePathname()
if err != nil {
return nil, err
}
config := tmcfg.ResetTestRoot(pathname)
tmAddr, _, err := server.FreeTCPAddr()
if err != nil {
return nil, err
}
rcpAddr, _, err := server.FreeTCPAddr()
if err != nil {
return nil, err
}
grpcAddr, _, err := server.FreeTCPAddr()
if err != nil {
return nil, err
}
config.P2P.ListenAddress = tmAddr
config.RPC.ListenAddress = rcpAddr
config.RPC.GRPCListenAddress = grpcAddr
return config, nil
}