forked from zeta-chain/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevnet.go
More file actions
319 lines (281 loc) · 10.7 KB
/
devnet.go
File metadata and controls
319 lines (281 loc) · 10.7 KB
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
package server
import (
"bufio"
"fmt"
"os"
"strings"
"time"
"cosmossdk.io/math"
tmproto "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
srvflags "github.com/cosmos/evm/server/flags"
"github.com/pkg/errors"
"github.com/spf13/cobra"
zeta "github.com/zeta-chain/node/app"
observertypes "github.com/zeta-chain/node/x/observer/types"
)
const (
DefaultDevnetValidatorTokes = "30000000000000000000000"
DefaultDelegatorShares = "30000000000000000000000.000000000000000"
)
func DevNetCmd(appCreator types.AppCreator) *cobra.Command {
return DevnetCmdWithOptions(appCreator, StartCmdOptions{
DBOpener: openDB,
StartCommandHandler: start,
})
}
// DevnetCmdWithOptions creates a command that modifies the local state to create a devnet fork.
// After running this command, the network can be started with the regular start command.
func DevnetCmdWithOptions(devnetAppCreator types.AppCreator, opts StartCmdOptions) *cobra.Command {
if opts.DBOpener == nil || opts.StartCommandHandler == nil {
panic("DBOpener and StartCommandHandler must be provided")
}
cmd := &cobra.Command{
Use: "devnet [newChainID] [operatorAddress]",
Short: "Modify state to create devnet from current local data",
Long: `Modify state to create a devnet from current local state. This will set the chain ID to the provided newChainID.
The provided operatorAddress is used as the operator for the single validator in this network. The existing node key is reused.
`,
Example: "zetacored devnet testnet_7001-1 zeta13c7p3xrhd6q2rx3h235jpt8pjdwvacyw6twpax",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := server.GetServerContextFromCmd(cmd)
_, err := server.GetPruningOptionsFromFlags(serverCtx.Viper)
if err != nil {
return errors.Wrap(err, "failed to get pruning options from flags")
}
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return errors.Wrap(err, "failed to get client query context")
}
newChainID := args[0]
operatorAddress := args[1]
_, err = sdk.AccAddressFromBech32(operatorAddress)
if err != nil {
return errors.Wrap(err, "invalid operator address")
}
skipConfirmation, err := cmd.Flags().GetBool(FlagSkipConfirmation)
if err != nil {
return errors.Wrap(err, "failed to get skip-confirmation flag")
}
if !skipConfirmation {
reader := bufio.NewReader(os.Stdin)
fmt.Println(
"This operation will modify state in your data folder and cannot be undone. This operation also updates the configuration , so it would not work with read only file systems. Do you want to continue? (y/n)",
)
text, _ := reader.ReadString('\n')
response := strings.TrimSpace(strings.ToLower(text))
if response != "y" && response != "yes" {
fmt.Println("Operation canceled.")
return nil
}
}
serverCtx.Viper.Set(KeyIsDevnet, true)
serverCtx.Viper.Set(KeyNewChainID, newChainID)
serverCtx.Viper.Set(KeyOperatorAddress, operatorAddress)
withCmt, err := cmd.Flags().GetBool(srvflags.WithCometBFT)
if err != nil {
return errors.Wrap(err, "failed to get with-cometbft flag")
}
err = opts.StartCommandHandler(serverCtx, clientCtx, devnetAppCreator, withCmt, opts)
if err != nil {
return errors.Wrap(err, "failed to start command handler")
}
return nil
},
}
cmd.Flags().Bool(FlagSkipConfirmation, false, "Skip the confirmation prompt")
cmd.Flags().Bool(srvflags.WithCometBFT, true, "Run abci app embedded in-process with CometBFT")
cmd.Flags().String(srvflags.TraceStore, "", "Enable KVStore tracing to an output file")
cmd.Flags().Duration(server.FlagShutdownGrace, 3*time.Second, "On Shutdown, duration to wait for resource clean up")
return cmd
}
func initAppForDevnet(svrCtx *server.Context, appInterface types.Application) error {
app, ok := appInterface.(*zeta.App)
if !ok {
return fmt.Errorf("invalid app type: %T", appInterface)
}
err := updateObserverData(svrCtx, *app)
if err != nil {
return errors.Wrap(err, "failed to update observer data")
}
err = updateValidatorData(svrCtx, *app)
if err != nil {
return errors.Wrap(err, "failed to update validator data")
}
return nil
}
// updateObserverData updates the observer state to have a single observer: the operator address.
func updateObserverData(svrCtx *server.Context, app zeta.App) error {
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
operatorAddrStr := svrCtx.Viper.GetString(KeyOperatorAddress)
newObserverSet := observertypes.ObserverSet{
ObserverList: []string{operatorAddrStr},
}
app.ObserverKeeper.SetObserverSet(ctx, newObserverSet)
app.ObserverKeeper.SetLastObserverCount(ctx, &observertypes.LastObserverCount{
Count: 1,
LastChangeHeight: ctx.BlockHeight(),
})
return nil
}
// updateValidatorData updates application state to have a single validator with the provided operator address and consensus pubkey.
// this affects staking, slashing, and distribution modules.
func updateValidatorData(svrCtx *server.Context, app zeta.App) error {
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
operatorAddrStr := svrCtx.Viper.GetString(KeyOperatorAddress)
newValPubkeyBytes, ok := svrCtx.Viper.Get(KeyValidatorConsensusPubkey).([]byte)
if !ok {
return errors.New("failed to get validator consensus pubkey as bytes")
}
pubkey := &ed25519.PubKey{Key: newValPubkeyBytes}
pubkeyAny, err := codectypes.NewAnyWithValue(pubkey)
if err != nil {
return errors.Wrap(err, "failed to pack pubkey into Any")
}
newValAddrBytes, ok := svrCtx.Viper.Get(KeyValidatorConsensusAddr).([]byte)
if !ok {
return errors.New("failed to get validator consensus address as bytes")
}
newConsAddr := sdk.ConsAddress(newValAddrBytes)
valAddress, err := observertypes.GetOperatorAddressFromAccAddress(operatorAddrStr)
if err != nil {
return errors.Wrap(err, "failed to get operator address from account address")
}
tokens, ok := math.NewIntFromString(DefaultDevnetValidatorTokes)
if !ok {
return errors.New("failed to parse tokens string to Int")
}
newVal := stakingtypes.Validator{
OperatorAddress: valAddress.String(),
ConsensusPubkey: pubkeyAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: tokens,
DelegatorShares: math.LegacyMustNewDecFromStr(DefaultDelegatorShares),
Description: stakingtypes.Description{
Moniker: "Devnet Validator",
},
Commission: stakingtypes.Commission{
CommissionRates: stakingtypes.CommissionRates{
Rate: math.LegacyMustNewDecFromStr("0.010000000000000000"),
MaxRate: math.LegacyMustNewDecFromStr("0.200000000000000000"),
MaxChangeRate: math.LegacyMustNewDecFromStr("0.100000000000000000"),
},
},
MinSelfDelegation: math.OneInt(),
}
params, err := app.StakingKeeper.GetParams(ctx)
if err != nil {
return errors.Wrap(err, "failed to get staking params")
}
params.MaxValidators = 1
params.UnbondingTime = 5 * time.Second
err = app.StakingKeeper.SetParams(ctx, params)
if err != nil {
return errors.Wrap(err, "failed to set staking params")
}
stakingKey := app.GetKey(stakingtypes.ModuleName)
stakingStore := ctx.KVStore(stakingKey)
iterator, err := app.StakingKeeper.ValidatorsPowerStoreIterator(ctx)
if err != nil {
return errors.Wrap(err, "failed to get validators power store iterator")
}
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
if err := iterator.Close(); err != nil {
return errors.Wrap(err, "failed to close validators power store iterator")
}
svrCtx.Logger.Info("Cleared staking validators by power index")
iterator, err = app.StakingKeeper.LastValidatorsIterator(ctx)
if err != nil {
return errors.Wrap(err, "failed to get last validators iterator")
}
for ; iterator.Valid(); iterator.Next() {
stakingStore.Delete(iterator.Key())
}
if err := iterator.Close(); err != nil {
return errors.Wrap(err, "failed to close last validators iterator")
}
svrCtx.Logger.Info("Cleared staking last validator power")
err = app.StakingKeeper.SetValidator(ctx, newVal)
if err != nil {
return errors.Wrap(err, "failed to set validator")
}
err = app.StakingKeeper.SetValidatorByConsAddr(ctx, newVal)
if err != nil {
return errors.Wrap(err, "failed to set validator by consensus address")
}
err = app.StakingKeeper.SetValidatorByPowerIndex(ctx, newVal)
if err != nil {
return errors.Wrap(err, "failed to set validator by power index")
}
err = app.StakingKeeper.SetLastValidatorPower(ctx, valAddress, 0)
if err != nil {
return errors.Wrap(err, "failed to set last validator power")
}
if err := app.StakingKeeper.Hooks().AfterValidatorCreated(ctx, valAddress); err != nil {
return errors.Wrap(err, "failed to execute after validator created hook")
}
err = app.DistrKeeper.SetValidatorHistoricalRewards(
ctx,
valAddress,
0,
distrtypes.NewValidatorHistoricalRewards(sdk.DecCoins{}, 1),
)
if err != nil {
return errors.Wrap(err, "failed to set validator historical rewards")
}
err = app.DistrKeeper.SetValidatorCurrentRewards(
ctx,
valAddress,
distrtypes.NewValidatorCurrentRewards(sdk.DecCoins{}, 1),
)
if err != nil {
return errors.Wrap(err, "failed to set validator current rewards")
}
err = app.DistrKeeper.SetValidatorAccumulatedCommission(
ctx,
valAddress,
distrtypes.InitialValidatorAccumulatedCommission(),
)
if err != nil {
return errors.Wrap(err, "failed to set validator accumulated commission")
}
err = app.DistrKeeper.SetValidatorOutstandingRewards(
ctx,
valAddress,
distrtypes.ValidatorOutstandingRewards{Rewards: sdk.DecCoins{}},
)
if err != nil {
return errors.Wrap(err, "failed to set validator outstanding rewards")
}
newValidatorSigningInfo := slashingtypes.ValidatorSigningInfo{
Address: newConsAddr.String(),
StartHeight: app.LastBlockHeight() - 1,
Tombstoned: false,
}
err = app.SlashingKeeper.SetValidatorSigningInfo(ctx, newConsAddr, newValidatorSigningInfo)
if err != nil {
return errors.Wrap(err, "failed to set validator signing info")
}
sp, err := app.SlashingKeeper.GetParams(ctx)
if err != nil {
return errors.Wrap(err, "failed to get slashing params")
}
sp.MinSignedPerWindow = math.LegacyZeroDec()
err = app.SlashingKeeper.SetParams(ctx, sp)
if err != nil {
return errors.Wrap(err, "failed to set slashing params")
}
return nil
}