-
Notifications
You must be signed in to change notification settings - Fork 572
/
node.go
427 lines (354 loc) · 11.3 KB
/
node.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
package initialization
import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
sdkcrypto "github.com/cosmos/cosmos-sdk/crypto"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/server"
srvconfig "github.com/cosmos/cosmos-sdk/server/config"
sdk "github.com/cosmos/cosmos-sdk/types"
sdktx "github.com/cosmos/cosmos-sdk/types/tx"
txsigning "github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
"github.com/cosmos/cosmos-sdk/x/genutil"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/go-bip39"
"github.com/spf13/viper"
tmconfig "github.com/tendermint/tendermint/config"
tmos "github.com/tendermint/tendermint/libs/os"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/privval"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/osmosis-labs/osmosis/osmomath"
osmosisApp "github.com/osmosis-labs/osmosis/v20/app"
"github.com/osmosis-labs/osmosis/v20/tests/e2e/util"
)
type internalNode struct {
chain *internalChain
moniker string
mnemonic string
keyInfo keyring.Info
privateKey cryptotypes.PrivKey
consensusKey privval.FilePVKey
nodeKey p2p.NodeKey
peerId string
isValidator bool
}
func newNode(chain *internalChain, nodeConfig *NodeConfig) (*internalNode, error) {
node := &internalNode{
chain: chain,
moniker: fmt.Sprintf("%s-node-%s", chain.chainMeta.Id, nodeConfig.Name),
isValidator: nodeConfig.IsValidator,
}
// generate genesis files
if err := node.init(); err != nil {
return nil, err
}
// create keys
if err := node.createKey(ValidatorWalletName); err != nil {
return nil, err
}
if err := node.createNodeKey(); err != nil {
return nil, err
}
if err := node.createConsensusKey(); err != nil {
return nil, err
}
node.createAppConfig(nodeConfig)
return node, nil
}
func (n *internalNode) configDir() string {
return fmt.Sprintf("%s/%s", n.chain.chainMeta.configDir(), n.moniker)
}
func (n *internalNode) buildCreateValidatorMsg(amount sdk.Coin) (sdk.Msg, error) {
description := stakingtypes.NewDescription(n.moniker, "", "", "", "")
commissionRates := stakingtypes.CommissionRates{
Rate: osmomath.MustNewDecFromStr("0.1"),
MaxRate: osmomath.MustNewDecFromStr("0.2"),
MaxChangeRate: osmomath.MustNewDecFromStr("0.01"),
}
// get the initial validator min self delegation
minSelfDelegation, _ := osmomath.NewIntFromString("1")
valPubKey, err := cryptocodec.FromTmPubKeyInterface(n.consensusKey.PubKey)
if err != nil {
return nil, err
}
return stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(n.keyInfo.GetAddress()),
valPubKey,
amount,
description,
commissionRates,
minSelfDelegation,
)
}
func (n *internalNode) createConfig() error {
p := path.Join(n.configDir(), "config")
return os.MkdirAll(p, 0o755)
}
func (n *internalNode) createAppConfig(nodeConfig *NodeConfig) {
// set application configuration
appCfgPath := filepath.Join(n.configDir(), "config", "app.toml")
appConfig := srvconfig.DefaultConfig()
appConfig.BaseConfig.Pruning = nodeConfig.Pruning
appConfig.BaseConfig.PruningKeepRecent = nodeConfig.PruningKeepRecent
appConfig.BaseConfig.PruningInterval = nodeConfig.PruningInterval
appConfig.API.Enable = true
appConfig.MinGasPrices = fmt.Sprintf("%s%s", MinGasPrice, OsmoDenom)
appConfig.StateSync.SnapshotInterval = nodeConfig.SnapshotInterval
appConfig.StateSync.SnapshotKeepRecent = nodeConfig.SnapshotKeepRecent
srvconfig.WriteConfigFile(appCfgPath, appConfig)
}
func (n *internalNode) createNodeKey() error {
serverCtx := server.NewDefaultContext()
config := serverCtx.Config
config.SetRoot(n.configDir())
config.Moniker = n.moniker
nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
if err != nil {
return err
}
n.nodeKey = *nodeKey
return nil
}
func (n *internalNode) createConsensusKey() error {
serverCtx := server.NewDefaultContext()
config := serverCtx.Config
config.SetRoot(n.configDir())
config.Moniker = n.moniker
pvKeyFile := config.PrivValidatorKeyFile()
if err := tmos.EnsureDir(filepath.Dir(pvKeyFile), 0o777); err != nil {
return err
}
pvStateFile := config.PrivValidatorStateFile()
if err := tmos.EnsureDir(filepath.Dir(pvStateFile), 0o777); err != nil {
return err
}
filePV := privval.LoadOrGenFilePV(pvKeyFile, pvStateFile)
n.consensusKey = filePV.Key
return nil
}
func (n *internalNode) createKeyFromMnemonic(name, mnemonic string) error {
kb, err := keyring.New(keyringAppName, keyring.BackendTest, n.configDir(), nil)
if err != nil {
return err
}
keyringAlgos, _ := kb.SupportedAlgorithms()
algo, err := keyring.NewSigningAlgoFromString(string(hd.Secp256k1Type), keyringAlgos)
if err != nil {
return err
}
info, err := kb.NewAccount(name, mnemonic, "", sdk.FullFundraiserPath, algo)
if err != nil {
return err
}
privKeyArmor, err := kb.ExportPrivKeyArmor(name, keyringPassphrase)
if err != nil {
return err
}
privKey, _, err := sdkcrypto.UnarmorDecryptPrivKey(privKeyArmor, keyringPassphrase)
if err != nil {
return err
}
n.keyInfo = info
n.mnemonic = mnemonic
n.privateKey = privKey
return nil
}
func (n *internalNode) createKey(name string) error {
mnemonic, err := n.createMnemonic()
if err != nil {
return err
}
return n.createKeyFromMnemonic(name, mnemonic)
}
func (n *internalNode) export() *Node {
return &Node{
Name: n.moniker,
ConfigDir: n.configDir(),
Mnemonic: n.mnemonic,
PublicAddress: n.keyInfo.GetAddress().String(),
PublicKey: n.keyInfo.GetPubKey().Address().String(),
PeerId: n.peerId,
IsValidator: n.isValidator,
}
}
func (n *internalNode) getNodeKey() *p2p.NodeKey {
return &n.nodeKey
}
func (n *internalNode) getGenesisDoc() (*tmtypes.GenesisDoc, error) {
serverCtx := server.NewDefaultContext()
config := serverCtx.Config
config.SetRoot(n.configDir())
genFile := config.GenesisFile()
doc := &tmtypes.GenesisDoc{}
if _, err := os.Stat(genFile); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
} else {
var err error
doc, err = tmtypes.GenesisDocFromFile(genFile)
if err != nil {
return nil, fmt.Errorf("failed to read genesis doc from file: %w", err)
}
}
return doc, nil
}
func (n *internalNode) init() error {
if err := n.createConfig(); err != nil {
return err
}
serverCtx := server.NewDefaultContext()
config := serverCtx.Config
config.SetRoot(n.configDir())
config.Moniker = n.moniker
genDoc, err := n.getGenesisDoc()
if err != nil {
return err
}
appState, err := json.MarshalIndent(osmosisApp.ModuleBasics.DefaultGenesis(util.Cdc), "", " ")
if err != nil {
return fmt.Errorf("failed to JSON encode app genesis state: %w", err)
}
genDoc.ChainID = n.chain.chainMeta.Id
genDoc.Validators = nil
genDoc.AppState = appState
if err = genutil.ExportGenesisFile(genDoc, config.GenesisFile()); err != nil {
return fmt.Errorf("failed to export app genesis state: %w", err)
}
tmconfig.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config)
return nil
}
func (n *internalNode) createMnemonic() (string, error) {
entropySeed, err := bip39.NewEntropy(256)
if err != nil {
return "", err
}
mnemonic, err := bip39.NewMnemonic(entropySeed)
if err != nil {
return "", err
}
return mnemonic, nil
}
func (n *internalNode) initNodeConfigs(persistentPeers []string) error {
tmCfgPath := filepath.Join(n.configDir(), "config", "config.toml")
vpr := viper.New()
vpr.SetConfigFile(tmCfgPath)
if err := vpr.ReadInConfig(); err != nil {
return err
}
valConfig := tmconfig.DefaultConfig()
if err := vpr.Unmarshal(valConfig); err != nil {
return err
}
valConfig.P2P.ListenAddress = "tcp://0.0.0.0:26656"
valConfig.P2P.AddrBookStrict = false
valConfig.P2P.ExternalAddress = fmt.Sprintf("%s:%d", n.moniker, 26656)
valConfig.RPC.ListenAddress = "tcp://0.0.0.0:26657"
valConfig.StateSync.Enable = false
valConfig.LogLevel = "info"
valConfig.P2P.PersistentPeers = strings.Join(persistentPeers, ",")
valConfig.Storage.DiscardABCIResponses = true
valConfig.Consensus.TimeoutPropose = time.Millisecond * 300
valConfig.Consensus.TimeoutProposeDelta = 0
valConfig.Consensus.TimeoutPrevote = 0
valConfig.Consensus.TimeoutPrevoteDelta = 0
valConfig.Consensus.TimeoutPrecommit = 0
valConfig.Consensus.TimeoutPrecommitDelta = 0
valConfig.Consensus.TimeoutCommit = 0
tmconfig.WriteConfigFile(tmCfgPath, valConfig)
return nil
}
func (n *internalNode) initStateSyncConfig(trustHeight int64, trustHash string, stateSyncRPCServers []string) error {
tmCfgPath := filepath.Join(n.configDir(), "config", "config.toml")
vpr := viper.New()
vpr.SetConfigFile(tmCfgPath)
if err := vpr.ReadInConfig(); err != nil {
return err
}
valConfig := tmconfig.DefaultConfig()
if err := vpr.Unmarshal(valConfig); err != nil {
return err
}
valConfig.StateSync = tmconfig.DefaultStateSyncConfig()
valConfig.StateSync.Enable = true
valConfig.StateSync.TrustHeight = trustHeight
valConfig.StateSync.TrustHash = trustHash
valConfig.StateSync.RPCServers = stateSyncRPCServers
tmconfig.WriteConfigFile(tmCfgPath, valConfig)
return nil
}
// signMsg returns a signed tx of the provided messages,
// signed by the validator, using 0 fees, a high gas limit, and a common memo.
func (n *internalNode) signMsg(msgs ...sdk.Msg) (*sdktx.Tx, error) {
txBuilder := util.EncodingConfig.TxConfig.NewTxBuilder()
if err := txBuilder.SetMsgs(msgs...); err != nil {
return nil, err
}
txBuilder.SetMemo(fmt.Sprintf("%s@%s:26656", n.nodeKey.ID(), n.moniker))
txBuilder.SetFeeAmount(sdk.NewCoins())
txBuilder.SetGasLimit(uint64(200000 * len(msgs)))
// TODO: Find a better way to sign this tx with less code.
signerData := authsigning.SignerData{
ChainID: n.chain.chainMeta.Id,
AccountNumber: 0,
Sequence: 0,
}
// For SIGN_MODE_DIRECT, calling SetSignatures calls setSignerInfos on
// TxBuilder under the hood, and SignerInfos is needed to generate the sign
// bytes. This is the reason for setting SetSignatures here, with a nil
// signature.
//
// Note: This line is not needed for SIGN_MODE_LEGACY_AMINO, but putting it
// also doesn't affect its generated sign bytes, so for code's simplicity
// sake, we put it here.
sig := txsigning.SignatureV2{
PubKey: n.keyInfo.GetPubKey(),
Data: &txsigning.SingleSignatureData{
SignMode: txsigning.SignMode_SIGN_MODE_DIRECT,
Signature: nil,
},
Sequence: 0,
}
if err := txBuilder.SetSignatures(sig); err != nil {
return nil, err
}
bytesToSign, err := util.EncodingConfig.TxConfig.SignModeHandler().GetSignBytes(
txsigning.SignMode_SIGN_MODE_DIRECT,
signerData,
txBuilder.GetTx(),
)
if err != nil {
return nil, err
}
sigBytes, err := n.privateKey.Sign(bytesToSign)
if err != nil {
return nil, err
}
sig = txsigning.SignatureV2{
PubKey: n.keyInfo.GetPubKey(),
Data: &txsigning.SingleSignatureData{
SignMode: txsigning.SignMode_SIGN_MODE_DIRECT,
Signature: sigBytes,
},
Sequence: 0,
}
if err := txBuilder.SetSignatures(sig); err != nil {
return nil, err
}
signedTx := txBuilder.GetTx()
bz, err := util.EncodingConfig.TxConfig.TxEncoder()(signedTx)
if err != nil {
return nil, err
}
return decodeTx(bz)
}