diff --git a/Makefile b/Makefile index 1f00ae4c..382d9bf9 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,10 @@ BRANCH := $(shell git rev-parse --abbrev-ref HEAD) COMMIT := $(shell git log -1 --format='%H') +APP_DIR = ./app +BINDIR ?= ~/go/bin +RUNSIM = $(BINDIR)/runsim + ifeq (,$(VERSION)) VERSION := $(shell git describe --tags) # if VERSION is empty, then populate it with branch's name and raw commit hash @@ -13,7 +17,7 @@ endif LEDGER_ENABLED ?= true SDK_PACK := $(shell go list -m github.com/cosmos/cosmos-sdk | sed 's/ /\@/g') -TM_VERSION := $(shell go list -m github.com/tendermint/tendermint | sed 's:.* ::') +TM_VERSION := $(shell go list -m github.com/cometbft/cometbft | sed 's:.* ::') DOCKER := $(shell which docker) DOCKER_BUF := $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace bufbuild/buf BUILDDIR ?= $(CURDIR)/build @@ -64,7 +68,7 @@ ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=migaloo \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" \ - -X github.com/tendermint/tendermint/version.TMCoreSemVer=$(TM_VERSION) + -X github.com/cometbft/cometbft/version.TMCoreSemVer=$(TM_VERSION) ifeq (cleveldb,$(findstring cleveldb,$(COSMOS_BUILD_OPTIONS))) ldflags += -X github.com/cosmos/cosmos-sdk/types.DBBackend=cleveldb @@ -92,3 +96,53 @@ install: go.sum build: go build $(BUILD_FLAGS) -o bin/migalood ./cmd/migalood + +docker-build-debug: + @DOCKER_BUILDKIT=1 docker build -t migaloo:debug -f Dockerfile . + +runsim: $(RUNSIM) +$(RUNSIM): + @echo "Installing runsim..." + @go install github.com/cosmos/tools/cmd/runsim@v1.0.0 + +test-sim-import-export: runsim + @echo "Running application import/export simulation. This may take several minutes..." + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP_DIR) 50 5 TestAppImportExport + +test-sim-custom-genesis-multi-seed: runsim + @echo "Running multi-seed custom genesis simulation..." + @echo "By default, ${HOME}/.migalood/config/genesis.json will be used." + @$(BINDIR)/runsim -Genesis=${HOME}/.migalood/config/genesis.json -SimAppPkg=$(APP_DIR) 400 5 TestFullAppSimulation + +test-sim-multi-seed-long: runsim + @echo "Running long multi-seed application simulation. This may take awhile!" + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP_DIR) 500 50 TestFullAppSimulation + +test-sim-multi-seed-short: runsim + @echo "Running short multi-seed application simulation. This may take awhile!" + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP_DIR) 50 10 TestFullAppSimulation + +test-sim-custom-genesis-fast: + @echo "Running custom genesis simulation..." + @echo "By default, ${HOME}/.migalood/config/genesis.json will be used." + @go test $(TEST_FLAGS) -mod=readonly $(SIMAPP) -run TestFullAppSimulation \ + -Enabled=true -NumBlocks=100 -BlockSize=200 -Commit=true -Seed=99 -Period=5 -v -timeout 24h + +############################################################################### +### Interchain test ### +############################################################################### + +# Executes start chain tests via interchaintest +ictest-start-cosmos: + cd tests/interchaintest && go test -race -v -run TestStartMigaloo . + +ictest-ibc: + cd tests/interchaintest && go test -race -v -run TestMigalooGaiaIBCTransfer . + +ictest-ibc-hooks: + cd tests/interchaintest && go test -race -v -run TestIBCHooks . + +# Executes all tests via interchaintest after compling a local image as migaloo:local +ictest-all: ictest-start-cosmos ictest-ibc + +.PHONY: ictest-start-cosmos ictest-all ictest-ibc-hooks ictest-ibc diff --git a/app/app.go b/app/app.go index d582f5c8..d3e393e7 100644 --- a/app/app.go +++ b/app/app.go @@ -3,12 +3,6 @@ package app import ( "encoding/json" "fmt" - "io" - "net/http" - "os" - "path/filepath" - "sort" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" @@ -44,9 +38,15 @@ import ( crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" + govtypesv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" solomachine "github.com/cosmos/ibc-go/v7/modules/light-clients/06-solomachine" ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" icq "github.com/strangelove-ventures/async-icq/v7" + "io" + "net/http" + "os" + "path/filepath" + "sort" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -62,7 +62,6 @@ import ( govclient "github.com/cosmos/cosmos-sdk/x/gov/client" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/cosmos/cosmos-sdk/x/mint" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" @@ -102,7 +101,8 @@ import ( ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client" ibcclientclient "github.com/cosmos/ibc-go/v7/modules/core/02-client/client" ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + ibcporttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" @@ -113,7 +113,7 @@ import ( routerkeeper "github.com/strangelove-ventures/packet-forward-middleware/v7/router/keeper" routertypes "github.com/strangelove-ventures/packet-forward-middleware/v7/router/types" - bank "github.com/terra-money/core/v2/custom/bank" + terracustombank "github.com/terra-money/core/v2/custom/bank" custombankkeeper "github.com/terra-money/core/v2/custom/bank/keeper" ibchooks "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7" @@ -151,11 +151,9 @@ import ( // unnamed import of statik for swagger UI support _ "github.com/cosmos/cosmos-sdk/client/docs/statik" - // Upgrade Handler - upgrades "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/upgrades" v2 "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/upgrades/v2" - "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/upgrades/v2_2_5" v3_0_2 "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/upgrades/v3_0_2" + v4 "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/upgrades/v4_1_0" ) const ( @@ -165,8 +163,7 @@ const ( // We pull these out so we can set them with LDFLAGS in the Makefile var ( - NodeDir = ".migalood" - Upgrades = []upgrades.Upgrade{v2.Upgrade, v2_2_5.Upgrade, v3_0_2.Upgrade} + NodeDir = ".migalood" ) // These constants are derived from the above variables. @@ -185,7 +182,7 @@ var ( auth.AppModuleBasic{}, alliancemodule.AppModuleBasic{}, genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), - bank.AppModule{}, + terracustombank.AppModule{}, capability.AppModuleBasic{}, consensus.AppModuleBasic{}, staking.AppModuleBasic{}, @@ -314,6 +311,11 @@ type MigalooApp struct { configurator module.Configurator } +func (app *MigalooApp) Close() error { + //TODO implement me + panic("implement me") +} + func (app *MigalooApp) RegisterNodeService(clientCtx client.Context) { nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) } @@ -329,7 +331,7 @@ func NewMigalooApp( invCheckPeriod uint, encodingConfig appparams.EncodingConfig, appOpts servertypes.AppOptions, - wasmOpts []wasm.Option, + wasmOpts []wasmkeeper.Option, baseAppOptions ...func(*baseapp.BaseApp), ) *MigalooApp { appCodec, legacyAmino, txConfig := encodingConfig.Codec, encodingConfig.Amino, encodingConfig.TxConfig @@ -643,7 +645,7 @@ func NewMigalooApp( ) // Create Transfer Stack - var transferStack porttypes.IBCModule + var transferStack ibcporttypes.IBCModule transferStack = transfer.NewIBCModule(app.TransferKeeper) transferStack = ibcfee.NewIBCMiddleware(transferStack, app.IBCFeeKeeper) transferStack = router.NewIBCMiddleware( @@ -663,14 +665,14 @@ func NewMigalooApp( // Note: please do your research before using this in production app, this is a demo and not an officially // supported IBC team implementation. Do your own research before using it. - var icaControllerStack porttypes.IBCModule + var icaControllerStack ibcporttypes.IBCModule // You will likely want to use your own reviewed and maintained ica auth module icaControllerStack = icacontroller.NewIBCMiddleware(icaControllerStack, app.ICAControllerKeeper) icaControllerStack = ibcfee.NewIBCMiddleware(icaControllerStack, app.IBCFeeKeeper) // RecvPacket, message that originates from core IBC and goes down to app, the flow is: // channel.RecvPacket -> fee.OnRecvPacket -> icaHost.OnRecvPacket - var icaHostStack porttypes.IBCModule + var icaHostStack ibcporttypes.IBCModule icaHostStack = icahost.NewIBCModule(app.ICAHostKeeper) icaHostStack = ibcfee.NewIBCMiddleware(icaHostStack, app.IBCFeeKeeper) @@ -679,13 +681,13 @@ func NewMigalooApp( icqStack := icq.NewIBCModule(app.ICQKeeper) // Create fee enabled wasm ibc Stack - var wasmStack porttypes.IBCModule + var wasmStack ibcporttypes.IBCModule wasmStack = wasm.NewIBCHandler(app.WasmKeeper, app.IBCKeeper.ChannelKeeper, app.IBCFeeKeeper) wasmStack = ibcfee.NewIBCMiddleware(wasmStack, app.IBCFeeKeeper) // Create static IBC router, add app routes, then set and seal it - ibcRouter := porttypes.NewRouter(). - AddRoute(ibctransfertypes.ModuleName, hooksTransferStack). + ibcRouter := ibcporttypes.NewRouter(). + AddRoute(ibctransfertypes.ModuleName, transferStack). AddRoute(wasmtypes.ModuleName, wasmStack). AddRoute(icahosttypes.SubModuleName, icaHostStack). AddRoute(icqtypes.ModuleName, icqStack) @@ -707,6 +709,7 @@ func NewMigalooApp( govConfig, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + govKeeper.SetLegacyRouter(govRouter) app.GovKeeper = *govKeeper.SetHooks( govtypes.NewMultiGovHooks( @@ -734,13 +737,14 @@ func NewMigalooApp( ), auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), + terracustombank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), + consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), upgrade.NewAppModule(&app.UpgradeKeeper), wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), evidence.NewAppModule(app.EvidenceKeeper), @@ -783,15 +787,16 @@ func NewMigalooApp( vestingtypes.ModuleName, icqtypes.ModuleName, // additional non simd modules - routertypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, + routertypes.ModuleName, + ibchookstypes.ModuleName, wasmtypes.ModuleName, tokenfactorytypes.ModuleName, alliancemoduletypes.ModuleName, - ibchookstypes.ModuleName, + consensusparamtypes.ModuleName, ) app.mm.SetOrderEndBlockers( @@ -818,10 +823,11 @@ func NewMigalooApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, + ibchookstypes.ModuleName, wasmtypes.ModuleName, tokenfactorytypes.ModuleName, alliancemoduletypes.ModuleName, - ibchookstypes.ModuleName, + consensusparamtypes.ModuleName, ) // NOTE: The genutils module must occur after staking so that pools are @@ -857,9 +863,10 @@ func NewMigalooApp( ibcfeetypes.ModuleName, tokenfactorytypes.ModuleName, // wasm after ibc transfer + ibchookstypes.ModuleName, wasmtypes.ModuleName, alliancemoduletypes.ModuleName, - ibchookstypes.ModuleName, + consensusparamtypes.ModuleName, ) // Uncomment if you want to set a custom migration order here. @@ -929,6 +936,9 @@ func NewMigalooApp( app.ScopedICAControllerKeeper = scopedICAControllerKeeper app.ScopedICQKeeper = scopedICQKeeper + // set the contract keeper for the Ics20WasmHooks + app.Ics20WasmHooks.ContractKeeper = &app.WasmKeeper + if loadLatest { if err := app.LoadLatestVersion(); err != nil { tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) @@ -1028,6 +1038,7 @@ func (app *MigalooApp) LegacyAmino() *codec.LegacyAmino { // NOTE: This is solely to be used for testing purposes. func (app *MigalooApp) GetSubspace(moduleName string) paramstypes.Subspace { subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) + fmt.Println(moduleName, subspace) return subspace } @@ -1085,27 +1096,66 @@ func RegisterSwaggerAPI(rtr *mux.Router) { // Setup Upgrade Handler func (app *MigalooApp) setupUpgradeHandlers(cfg module.Configurator) { + app.UpgradeKeeper.SetUpgradeHandler( + v2.UpgradeName, + v2.CreateUpgradeHandler(app.mm, app.configurator), + ) + + app.UpgradeKeeper.SetUpgradeHandler( + v3_0_2.UpgradeName, + v3_0_2.CreateUpgradeHandler(app.mm, app.configurator), + ) + + // !! ATTENTION !! + // v4 upgrade handler + // !! WHEN UPGRADING TO SDK v0.47 MAKE SURE TO INCLUDE THIS + // source: https://github.com/cosmos/cosmos-sdk/blob/release/v0.47.x/UPGRADING.md#xconsensus + app.UpgradeKeeper.SetUpgradeHandler( + v4.UpgradeName, + v4.CreateUpgradeHandler( + app.mm, + app.configurator, + app.IBCKeeper.ClientKeeper, + app.ParamsKeeper, + app.ConsensusParamsKeeper, + app.ICAControllerKeeper, + ), + ) + + // When a planned update height is reached, the old binary will panic + // writing on disk the height and name of the update that triggered it + // This will read that value, and execute the preparations for the upgrade. upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() if err != nil { - panic(fmt.Sprintf("failed to read upgrade info from disk %s", err)) + panic(fmt.Errorf("failed to read upgrade info from disk: %w", err)) } if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { return } - for _, upgrade := range Upgrades { - upgrade := upgrade - if upgradeInfo.Name == upgrade.UpgradeName { - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &upgrade.StoreUpgrades)) + var storeUpgrades *storetypes.StoreUpgrades + + switch upgradeInfo.Name { + case v4.UpgradeName: + // !! ATTENTION !! + // !! WHEN UPGRADING TO SDK v0.47 MAKE SURE TO INCLUDE THIS + // source: https://github.com/cosmos/cosmos-sdk/blob/release/v0.47.x/UPGRADING.md + storeUpgrades = &storetypes.StoreUpgrades{ + Added: []string{ + consensusparamtypes.StoreKey, + crisistypes.StoreKey, + icqtypes.StoreKey, + }, + Deleted: []string{ + "intertx", + }, } - app.UpgradeKeeper.SetUpgradeHandler( - upgrade.UpgradeName, - upgrade.CreateUpgradeHandler( - app.mm, - cfg, - ), - ) + } + + if storeUpgrades != nil { + // configure store loader that checks if version == upgradeHeight and applies store upgrades + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, storeUpgrades)) } } @@ -1131,22 +1181,22 @@ func stringMapKeys(m map[string][]string) []string { func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) - paramsKeeper.Subspace(authtypes.ModuleName) - paramsKeeper.Subspace(banktypes.ModuleName) - paramsKeeper.Subspace(stakingtypes.ModuleName) - paramsKeeper.Subspace(minttypes.ModuleName) - paramsKeeper.Subspace(distrtypes.ModuleName) - paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) - paramsKeeper.Subspace(crisistypes.ModuleName) + paramsKeeper.Subspace(authtypes.ModuleName).WithKeyTable(authtypes.ParamKeyTable()) + paramsKeeper.Subspace(banktypes.ModuleName).WithKeyTable(banktypes.ParamKeyTable()) + paramsKeeper.Subspace(stakingtypes.ModuleName).WithKeyTable(stakingtypes.ParamKeyTable()) + paramsKeeper.Subspace(minttypes.ModuleName).WithKeyTable(minttypes.ParamKeyTable()) + paramsKeeper.Subspace(distrtypes.ModuleName).WithKeyTable(distrtypes.ParamKeyTable()) + paramsKeeper.Subspace(slashingtypes.ModuleName).WithKeyTable(slashingtypes.ParamKeyTable()) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypesv1.ParamKeyTable()) + paramsKeeper.Subspace(crisistypes.ModuleName).WithKeyTable(crisistypes.ParamKeyTable()) paramsKeeper.Subspace(ibctransfertypes.ModuleName) paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(icahosttypes.SubModuleName) - paramsKeeper.Subspace(tokenfactorytypes.ModuleName) + paramsKeeper.Subspace(tokenfactorytypes.ModuleName).WithKeyTable(tokenfactorytypes.ParamKeyTable()) paramsKeeper.Subspace(icacontrollertypes.SubModuleName) paramsKeeper.Subspace(icqtypes.ModuleName) - paramsKeeper.Subspace(wasmtypes.ModuleName) - paramsKeeper.Subspace(routertypes.ModuleName) + paramsKeeper.Subspace(wasmtypes.ModuleName).WithKeyTable(wasmtypes.ParamKeyTable()) + paramsKeeper.Subspace(routertypes.ModuleName).WithKeyTable(routertypes.ParamKeyTable()) paramsKeeper.Subspace(alliancemoduletypes.ModuleName).WithKeyTable(alliancemoduletypes.ParamKeyTable()) return paramsKeeper diff --git a/app/app_test.go b/app/app_test.go index 4a22563b..e9e3bb8e 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -2,6 +2,7 @@ package app import ( "encoding/json" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" "os" "testing" "time" @@ -21,11 +22,9 @@ import ( alliancemoduletypes "github.com/terra-money/alliance/x/alliance/types" abci "github.com/cometbft/cometbft/abci/types" - - "github.com/CosmWasm/wasmd/x/wasm" ) -var emptyWasmOpts []wasm.Option +var emptyWasmOpts []wasmkeeper.Option func TestWasmdExport(t *testing.T) { db := db.NewMemDB() @@ -91,7 +90,7 @@ func TestGetMaccPerms(t *testing.T) { require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions") } -func SetupGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, _ []wasm.Option, app *MigalooApp, balances ...banktypes.Balance) GenesisState { +func SetupGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, _ []wasmkeeper.Option, app *MigalooApp, balances ...banktypes.Balance) GenesisState { genesisState := NewDefaultGenesisState() // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) diff --git a/app/test_helpers.go b/app/test_helpers.go index fd6940cc..e3f5c463 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -5,13 +5,13 @@ import ( "encoding/hex" "encoding/json" "fmt" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" "math/rand" "path/filepath" "strconv" "testing" "time" - "github.com/CosmWasm/wasmd/x/wasm" "github.com/cosmos/ibc-go/v7/testing/mock" "github.com/stretchr/testify/require" @@ -61,7 +61,7 @@ var DefaultConsensusParams = &tmproto.ConsensusParams{ }, } -func setup(tb testing.TB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*MigalooApp, GenesisState) { +func setup(tb testing.TB, withGenesis bool, invCheckPeriod uint, opts ...wasmkeeper.Option) (*MigalooApp, GenesisState) { tb.Helper() nodeHome := tb.TempDir() snapshotDir := filepath.Join(nodeHome, "data", "snapshots") @@ -80,7 +80,7 @@ func setup(tb testing.TB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Op return app, GenesisState{} } -func setupWithChainID(tb testing.TB, withGenesis bool, invCheckPeriod uint, chainID string, opts ...wasm.Option) (*MigalooApp, GenesisState) { +func setupWithChainID(tb testing.TB, withGenesis bool, invCheckPeriod uint, chainID string, opts ...wasmkeeper.Option) (*MigalooApp, GenesisState) { tb.Helper() nodeHome := tb.TempDir() snapshotDir := filepath.Join(nodeHome, "data", "snapshots") @@ -109,7 +109,7 @@ func setupWithChainID(tb testing.TB, withGenesis bool, invCheckPeriod uint, chai } // Setup initializes a new MigalooApp with DefaultNodeHome for integration tests -func Setup(isCheckTx bool, opts ...wasm.Option) *MigalooApp { +func Setup(isCheckTx bool, opts ...wasmkeeper.Option) *MigalooApp { db := dbm.NewMemDB() app := NewMigalooApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, 5, MakeEncodingConfig(), EmptyBaseAppOptions{}, opts) @@ -161,7 +161,7 @@ func SetupMigalooAppWithValSet(t *testing.T) *MigalooApp { // that also act as delegators. For simplicity, each validator is bonded with a delegation // of one consensus engine unit (10^6) in the default token of the MigalooApp from first genesis // account. A Nop logger is set in MigalooApp. -func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, chainID string, opts []wasm.Option, balances ...banktypes.Balance) *MigalooApp { +func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, chainID string, opts []wasmkeeper.Option, balances ...banktypes.Balance) *MigalooApp { t.Helper() app, genesisState := setupWithChainID(t, true, 5, chainID, opts...) genesisState, err := simtestutil.GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, genAccs, balances...) diff --git a/app/upgrades/v4_1_0/constants.go b/app/upgrades/v4_1_0/constants.go new file mode 100644 index 00000000..07b276ad --- /dev/null +++ b/app/upgrades/v4_1_0/constants.go @@ -0,0 +1,5 @@ +package v3 + +// UpgradeName defines the on-chain upgrade name for the Migaloo v3.0.2 upgrade. +// this upgrade includes the fix for pfm +const UpgradeName = "v4.1.0" diff --git a/app/upgrades/v4_1_0/upgrades.go b/app/upgrades/v4_1_0/upgrades.go new file mode 100644 index 00000000..d850891d --- /dev/null +++ b/app/upgrades/v4_1_0/upgrades.go @@ -0,0 +1,42 @@ +package v3 + +import ( + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + consensuskeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + icacontrollerkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/keeper" + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + clientkeeper "github.com/cosmos/ibc-go/v7/modules/core/02-client/keeper" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" +) + +// small security fix, can be a no-op, running mm.RunMigarions just to be sure +func CreateUpgradeHandler( + mm *module.Manager, + configurator module.Configurator, + clientKeeper clientkeeper.Keeper, + paramsKeeper paramskeeper.Keeper, + consensusParamsKeeper consensuskeeper.Keeper, + icacontrollerKeeper icacontrollerkeeper.Keeper, +) upgradetypes.UpgradeHandler { + return func(ctx sdk.Context, _plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { + // READ: https://github.com/cosmos/cosmos-sdk/blob/v0.47.4/UPGRADING.md#xconsensus + baseAppLegacySS := paramsKeeper.Subspace(baseapp.Paramspace). + WithKeyTable(paramstypes.ConsensusParamsKeyTable()) + baseapp.MigrateParams(ctx, baseAppLegacySS, &consensusParamsKeeper) + + // READ: https://github.com/cosmos/ibc-go/blob/v7.2.0/docs/migrations/v7-to-v7_1.md#chains + params := clientKeeper.GetParams(ctx) + params.AllowedClients = append(params.AllowedClients, ibcexported.Localhost) + clientKeeper.SetParams(ctx, params) + + // READ: https://github.com/terra-money/core/issues/166 + icacontrollerKeeper.SetParams(ctx, icacontrollertypes.DefaultParams()) + + return mm.RunMigrations(ctx, configurator, fromVM) + } +} diff --git a/cmd/migalood/cmd/root.go b/cmd/migalood/cmd/root.go index 993bbc60..9d798519 100644 --- a/cmd/migalood/cmd/root.go +++ b/cmd/migalood/cmd/root.go @@ -25,7 +25,6 @@ import ( snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" "github.com/spf13/cobra" - "github.com/CosmWasm/wasmd/x/wasm" wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app" "github.com/White-Whale-Defi-Platform/migaloo-chain/v3/app/params" @@ -281,7 +280,7 @@ func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, a if err != nil { panic(err) } - var wasmOpts []wasm.Option + var wasmOpts []wasmkeeper.Option if cast.ToBool(appOpts.Get("telemetry.enabled")) { wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer)) } @@ -347,7 +346,7 @@ func (a appCreator) appExport( } loadLatest := height == -1 - var emptyWasmOpts []wasm.Option + var emptyWasmOpts []wasmkeeper.Option migalooApp = app.NewMigalooApp( logger, db, @@ -361,11 +360,5 @@ func (a appCreator) appExport( emptyWasmOpts, ) - if height != -1 { - if err := migalooApp.LoadHeight(height); err != nil { - return servertypes.ExportedApp{}, err - } - } - return migalooApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) } diff --git a/cmd/migalood/cmd/testnet.go b/cmd/migalood/cmd/testnet.go index e60f2d39..e85c3797 100644 --- a/cmd/migalood/cmd/testnet.go +++ b/cmd/migalood/cmd/testnet.go @@ -80,7 +80,7 @@ func addTestnetFlagsToCmd(cmd *cobra.Command) { cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with") cmd.Flags().StringP(flagOutputDir, "o", "./.testnets", "Directory to store initialization data for the testnet") cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") - cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") + cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.001uwhale)") cmd.Flags().String(flagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") } diff --git a/cmd/migalood/main.go b/cmd/migalood/main.go index 5278e631..e06673b6 100644 --- a/cmd/migalood/main.go +++ b/cmd/migalood/main.go @@ -12,7 +12,7 @@ import ( func main() { rootCmd, _ := cmd.NewRootCmd() - if err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome); err != nil { + if err := svrcmd.Execute(rootCmd, "MIGALOOD", app.DefaultNodeHome); err != nil { switch e := err.(type) { case server.ErrorCode: os.Exit(e.Code) diff --git a/go.mod b/go.mod index b8139786..e9f079ce 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/strangelove-ventures/packet-forward-middleware/v7 v7.0.0-20230523193151-73dea436e53f github.com/stretchr/testify v1.8.4 github.com/terra-money/alliance v0.3.2 - github.com/terra-money/core/v2 v2.0.0-00010101000000-000000000000 + github.com/terra-money/core/v2 v2.5.0 ) require ( @@ -192,8 +192,6 @@ require ( replace ( // use cosmos fork of keyring github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 - // use notional's wasmd fork with token factory - github.com/CosmWasm/wasmd => github.com/notional-labs/wasmd v0.45.0-tf.rc0 // downgraded to avoid some annoying warning messages // should be fixed after sdk 0.47.3 and gogoproto 1.4.10 // https://github.com/cosmos/gogoproto/issues/66 diff --git a/go.sum b/go.sum index e261d352..787ac4f8 100644 --- a/go.sum +++ b/go.sum @@ -420,6 +420,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v1.0.0 h1:3aDA67lAykLaG1y3AOjs88dMxC88PgUuHRrLeDnvGIM= github.com/ChainSafe/go-schnorrkel v1.0.0/go.mod h1:dpzHYVxLZcp8pjlV+O+UR8K0Hp/z7vcchBSbMBEhCw4= +github.com/CosmWasm/wasmd v0.45.0 h1:9zBqrturKJwC2kVsfHvbrA++EN0PS7UTXCffCGbg6JI= +github.com/CosmWasm/wasmd v0.45.0/go.mod h1:RnSAiqbNIZu4QhO+0pd7qGZgnYAMBPGmXpzTADag944= github.com/CosmWasm/wasmvm v1.5.0 h1:3hKeT9SfwfLhxTGKH3vXaKFzBz1yuvP8SlfwfQXbQfw= github.com/CosmWasm/wasmvm v1.5.0/go.mod h1:fXB+m2gyh4v9839zlIXdMZGeLAxqUdYdFQqYsTha2hc= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -1026,8 +1028,6 @@ github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/notional-labs/wasmd v0.45.0-tf.rc0 h1:JCMD7GY/C2Pk7klQNpjpgU5FW4zn0KL6Du1W5rP2OKM= -github.com/notional-labs/wasmd v0.45.0-tf.rc0/go.mod h1:nMVHI6PFNpaMqMw4pj6fThldCP3mmf9LcrmYw1nNG5Y= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= diff --git a/scripts/local_node.sh b/scripts/local_node.sh new file mode 100755 index 00000000..cd20b6ed --- /dev/null +++ b/scripts/local_node.sh @@ -0,0 +1,98 @@ +#!/bin/bash + +KEY="mykey" +CHAINID="migaloo-1" +MONIKER="localtestnet" +KEYALGO="secp256k1" +KEYRING="test" +LOGLEVEL="info" +# to trace evm +#TRACE="--trace" +TRACE="" + +HOMEDIR="$HOME/.migaloo-tmp" + +CONFIG=$HOMEDIR/config/config.toml +GENESIS=$HOMEDIR/config/genesis.json +TMP_GENESIS=$HOMEDIR/config/tmp_genesis.json + +# validate dependencies are installed +command -v jq >/dev/null 2>&1 || { + echo >&2 "jq not installed. More info: https://stedolan.github.io/jq/download/" + exit 1 +} + +# used to exit on first error (any non-zero exit code) +set -e + +rm -rf "$HOMEDIR" + +migalood config keyring-backend $KEYRING --home $HOMEDIR +migalood config chain-id $CHAINID --home $HOMEDIR + +# if $KEY exists it should be deleted +migalood keys add $KEY --keyring-backend $KEYRING --algo $KEYALGO --home $HOMEDIR + +migalood init $MONIKER --chain-id $CHAINID --home $HOMEDIR + +# Change parameter token denominations to uwhale +jq '.app_state["staking"]["params"]["bond_denom"]="uwhale"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" +jq '.app_state["mint"]["params"]["mint_denom"]="uwhale"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" +jq '.app_state["crisis"]["constant_fee"]["denom"]="uwhale"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" +jq '.app_state["gov"]["deposit_params"]["min_deposit"][0]["denom"]="uwhale"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" +jq '.app_state["tokenfactory"]["params"]["denom_creation_fee"][0]["denom"]="uwhale"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + + +# Set gas limit in genesis +jq '.consensus_params["block"]["max_gas"]="10000000"' "$GENESIS" >"$TMP_GENESIS" && mv "$TMP_GENESIS" "$GENESIS" + +if [[ $1 == "pending" ]]; then + if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' 's/timeout_propose = "3s"/timeout_propose = "30s"/g' "$CONFIG" + sed -i '' 's/timeout_propose_delta = "500ms"/timeout_propose_delta = "5s"/g' "$CONFIG" + sed -i '' 's/timeout_prevote = "1s"/timeout_prevote = "10s"/g' "$CONFIG" + sed -i '' 's/timeout_prevote_delta = "500ms"/timeout_prevote_delta = "5s"/g' "$CONFIG" + sed -i '' 's/timeout_precommit = "1s"/timeout_precommit = "10s"/g' "$CONFIG" + sed -i '' 's/timeout_precommit_delta = "500ms"/timeout_precommit_delta = "5s"/g' "$CONFIG" + sed -i '' 's/timeout_commit = "5s"/timeout_commit = "150s"/g' "$CONFIG" + sed -i '' 's/timeout_broadcast_tx_commit = "10s"/timeout_broadcast_tx_commit = "150s"/g' "$CONFIG" + else + sed -i 's/timeout_propose = "3s"/timeout_propose = "30s"/g' "$CONFIG" + sed -i 's/timeout_propose_delta = "500ms"/timeout_propose_delta = "5s"/g' "$CONFIG" + sed -i 's/timeout_prevote = "1s"/timeout_prevote = "10s"/g' "$CONFIG" + sed -i 's/timeout_prevote_delta = "500ms"/timeout_prevote_delta = "5s"/g' "$CONFIG" + sed -i 's/timeout_precommit = "1s"/timeout_precommit = "10s"/g' "$CONFIG" + sed -i 's/timeout_precommit_delta = "500ms"/timeout_precommit_delta = "5s"/g' "$CONFIG" + sed -i 's/timeout_commit = "5s"/timeout_commit = "150s"/g' "$CONFIG" + sed -i 's/timeout_broadcast_tx_commit = "10s"/timeout_broadcast_tx_commit = "150s"/g' "$CONFIG" + fi +fi + +if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' 's/laddr = "tcp:\/\/127.0.0.1:26657"/laddr = "tcp:\/\/0.0.0.0:26657"/g' "$CONFIG" +else + sed -i 's/laddr = "tcp:\/\/127.0.0.1:26657"/laddr = "tcp:\/\/0.0.0.0:26657"/g' "$CONFIG" +fi + +# Allocate genesis accounts (cosmos formatted addresses) +migalood add-genesis-account $KEY 100000000000000000000000000uwhale --keyring-backend $KEYRING --home $HOMEDIR + +# Sign genesis transaction +migalood gentx $KEY 1000000000000000000000uwhale --keyring-backend $KEYRING --chain-id $CHAINID --home $HOMEDIR + +# Collect genesis tx +migalood collect-gentxs --home $HOMEDIR + +# Run this to ensure everything worked and that the genesis file is setup correctly +migalood validate-genesis --home $HOMEDIR + +if [[ $1 == "pending" ]]; then + echo "pending mode is on, please wait for the first block committed." +fi + +# update request max size so that we can upload the light client +# '' -e is a must have params on mac, if use linux please delete before run +sed -i'' -e 's/max_body_bytes = /max_body_bytes = 1/g' "$CONFIG" + +# Start the node (remove the --pruning=nothing flag if historical queries are not needed) +# migalood start --pruning=nothing --minimum-gas-prices=0.0001uwhale --rpc.laddr tcp://0.0.0.0:26657 --home $HOMEDIR \ No newline at end of file diff --git a/scripts/run-node.sh b/scripts/run-node.sh new file mode 100755 index 00000000..38ccefa4 --- /dev/null +++ b/scripts/run-node.sh @@ -0,0 +1,83 @@ +#!/bin/bash + +BINARY=$1 +CONTINUE=${CONTINUE:-"false"} +HOME_DIR=mytestnet +ENV=${ENV:-""} + +if [ "$CONTINUE" == "true" ]; then + $BINARY start --home $HOME_DIR --log_level debug + exit 0 +fi + +rm -rf mytestnet +pkill migalood + +# check DENOM is set. If not, set to uwhale +DENOM=${2:-uwhale} + +COMMISSION_RATE=0.01 +COMMISSION_MAX_RATE=0.02 + +SED_BINARY=sed +# check if this is OS X +if [[ "$OSTYPE" == "darwin"* ]]; then + # check if gsed is installed + if ! command -v gsed &> /dev/null + then + echo "gsed could not be found. Please install it with 'brew install gnu-sed'" + exit + else + SED_BINARY=gsed + fi +fi + +# check BINARY is set. If not, build migalood and set BINARY +if [ -z "$BINARY" ]; then + make build + BINARY=build/migalood +fi + +CHAIN_ID="localmigaloo" +KEYRING="test" +KEY="test0" +KEY1="test1" +KEY2="test2" + +# Function updates the config based on a jq argument as a string +update_test_genesis () { + # update_test_genesis '.consensus_params["block"]["max_gas"]="100000000"' + cat $HOME_DIR/config/genesis.json | jq "$1" > $HOME_DIR/config/tmp_genesis.json && mv $HOME_DIR/config/tmp_genesis.json $HOME_DIR/config/genesis.json +} + +$BINARY init --chain-id $CHAIN_ID moniker --home $HOME_DIR + +$BINARY keys add $KEY --keyring-backend $KEYRING --home $HOME_DIR +$BINARY keys add $KEY1 --keyring-backend $KEYRING --home $HOME_DIR +$BINARY keys add $KEY2 --keyring-backend $KEYRING --home $HOME_DIR + +# Allocate genesis accounts (cosmos formatted addresses) +$BINARY add-genesis-account $KEY "1000000000000${DENOM}" --keyring-backend $KEYRING --home $HOME_DIR +$BINARY add-genesis-account $KEY1 "1000000000000${DENOM}" --keyring-backend $KEYRING --home $HOME_DIR +$BINARY add-genesis-account $KEY2 "1000000000000${DENOM}" --keyring-backend $KEYRING --home $HOME_DIR + +update_test_genesis '.app_state["gov"]["voting_params"]["voting_period"]="20s"' +update_test_genesis '.app_state["mint"]["params"]["mint_denom"]="'$DENOM'"' +update_test_genesis '.app_state["gov"]["deposit_params"]["min_deposit"]=[{"denom":"'$DENOM'","amount": "1000000"}]' +update_test_genesis '.app_state["crisis"]["constant_fee"]={"denom":"'$DENOM'","amount":"1000"}' +update_test_genesis '.app_state["staking"]["params"]["bond_denom"]="'$DENOM'"' + +# enable rest server and swagger +$SED_BINARY -i '0,/enable = false/s//enable = true/' $HOME_DIR/config/app.toml +$SED_BINARY -i 's/swagger = false/swagger = true/' $HOME_DIR/config/app.toml + +# Sign genesis transaction +$BINARY gentx $KEY "1000000${DENOM}" --commission-rate=$COMMISSION_RATE --commission-max-rate=$COMMISSION_MAX_RATE --keyring-backend $KEYRING --chain-id $CHAIN_ID --home $HOME_DIR + +# Collect genesis tx +$BINARY collect-gentxs --home $HOME_DIR + +# Run this to ensure everything worked and that the genesis file is setup correctly +$BINARY validate-genesis --home $HOME_DIR + +$BINARY start --home $HOME_DIR \ No newline at end of file diff --git a/scripts/upgrade_test.sh b/scripts/upgrade_test.sh new file mode 100755 index 00000000..36a91c76 --- /dev/null +++ b/scripts/upgrade_test.sh @@ -0,0 +1,169 @@ +#!/bin/bash + +# the upgrade is a fork, "true" otherwise +FORK=${FORK:-"false"} + +OLD_VERSION=v3.0.2 +UPGRADE_WAIT=${UPGRADE_WAIT:-20} +HOME=mytestnet +ROOT=$(pwd) +DENOM=uwhale +CHAIN_ID=localmigaloo +SOFTWARE_UPGRADE_NAME="v4.1.0" +ADDITIONAL_PRE_SCRIPTS=${ADDITIONAL_PRE_SCRIPTS:-""} +ADDITIONAL_AFTER_SCRIPTS=${ADDITIONAL_AFTER_SCRIPTS:-""} + +if [[ "$FORK" == "true" ]]; then + export MIGALOO_HALT_HEIGHT=20 +fi + +# underscore so that go tool will not take gocache into account +mkdir -p _build/gocache +export GOMODCACHE=$ROOT/_build/gocache + +# install old binary if not exist +if [ ! -f "_build/$OLD_VERSION.zip" ] &> /dev/null +then + mkdir -p _build/old + wget -c "https://github.com/White-Whale-Defi-Platform/migaloo-chain/archive/refs/tags/${OLD_VERSION}.zip" -O _build/${OLD_VERSION}.zip + unzip _build/${OLD_VERSION}.zip -d _build +fi + +# reinstall old binary +if [ $# -eq 1 ] && [ $1 == "--reinstall-old" ] || ! command -v _build/old/migalood &> /dev/null; then + cd ./_build/migaloo-chain-${OLD_VERSION:1} + GOBIN="$ROOT/_build/old" go install -mod=readonly ./... + cd ../.. +fi + +# install new binary +if ! command -v _build/new/migalood &> /dev/null +then + mkdir -p _build/new + GOBIN="$ROOT/_build/new" go install -mod=readonly ./... +fi + +# run old node +if [[ "$OSTYPE" == "darwin"* ]]; then + screen -L -dmS node1 bash scripts/run-node.sh _build/old/migalood $DENOM +else + screen -L -Logfile $HOME/log-screen.txt -dmS node1 bash scripts/run-node.sh _build/old/migalood $DENOM +fi + +sleep 20 + +# execute additional pre scripts +if [ ! -z "$ADDITIONAL_PRE_SCRIPTS" ]; then + # slice ADDITIONAL_SCRIPTS by , + SCRIPTS=($(echo "$ADDITIONAL_PRE_SCRIPTS" | tr ',' ' ')) + for SCRIPT in "${SCRIPTS[@]}"; do + # check if SCRIPT is a file + if [ -f "$SCRIPT" ]; then + echo "executing additional pre scripts from $SCRIPT" + source $SCRIPT + sleep 5 + else + echo "$SCRIPT is not a file" + fi + done +fi + +run_fork () { + echo "forking" + + while true; do + BLOCK_HEIGHT=$(./_build/old/migalood status | jq '.SyncInfo.latest_block_height' -r) + # if BLOCK_HEIGHT is not empty + if [ ! -z "$BLOCK_HEIGHT" ]; then + echo "BLOCK_HEIGHT = $BLOCK_HEIGHT" + sleep 10 + else + echo "BLOCK_HEIGHT is empty, forking" + break + fi + done +} + +run_upgrade () { + echo "start upgrading" + + STATUS_INFO=($(./_build/old/migalood status --home $HOME | jq -r '.NodeInfo.network,.SyncInfo.latest_block_height')) + UPGRADE_HEIGHT=$((STATUS_INFO[1] + 12)) + + tar -cf ./_build/new/migalood.tar -C ./_build/new migalood + SUM=$(shasum -a 256 ./_build/new/migalood.tar | cut -d ' ' -f1) + UPGRADE_INFO=$(jq -n ' + { + "binaries": { + "linux/amd64": "file://'$(pwd)'/_build/new/migalood.tar?checksum=sha256:'"$SUM"'", + } + }') + + ./_build/old/migalood keys list --home $HOME --keyring-backend test + + ./_build/old/migalood tx gov submit-legacy-proposal software-upgrade "$SOFTWARE_UPGRADE_NAME" --upgrade-height $UPGRADE_HEIGHT --upgrade-info "$UPGRADE_INFO" --title "upgrade" --description "upgrade" --from test1 --keyring-backend test --chain-id $CHAIN_ID --home $HOME -y + + sleep 5 + + ./_build/old/migalood tx gov deposit 1 "20000000${DENOM}" --from test1 --keyring-backend test --chain-id $CHAIN_ID --home $HOME -y + + sleep 5 + + ./_build/old/migalood tx gov vote 1 yes --from test0 --keyring-backend test --chain-id $CHAIN_ID --home $HOME -y + + sleep 5 + + ./_build/old/migalood tx gov vote 1 yes --from test1 --keyring-backend test --chain-id $CHAIN_ID --home $HOME -y + + sleep 5 + + # determine block_height to halt + while true; do + BLOCK_HEIGHT=$(./_build/old/migalood status | jq '.SyncInfo.latest_block_height' -r) + if [ $BLOCK_HEIGHT = "$UPGRADE_HEIGHT" ]; then + # assuming running only 1 migalood + echo "BLOCK HEIGHT = $UPGRADE_HEIGHT REACHED, KILLING OLD ONE" + pkill migalood + break + else + ./_build/old/migalood q gov proposal 1 --output=json | jq ".status" + echo "BLOCK_HEIGHT = $BLOCK_HEIGHT" + sleep 10 + fi + done +} + +# if FORK = true +if [[ "$FORK" == "true" ]]; then + run_fork + unset MIGALOO_HALT_HEIGHT +else + run_upgrade +fi + +sleep 5 + +# run new node +if [[ "$OSTYPE" == "darwin"* ]]; then + CONTINUE="true" screen -L -dmS node1 bash scripts/run-node.sh _build/new/migalood $DENOM +else + CONTINUE="true" screen -L -Logfile $HOME/log-screen.txt -dmS node1 bash scripts/run-node.sh _build/new/migalood $DENOM +fi + +sleep 20 + +# execute additional after scripts +if [ ! -z "$ADDITIONAL_AFTER_SCRIPTS" ]; then + # slice ADDITIONAL_SCRIPTS by , + SCRIPTS=($(echo "$ADDITIONAL_AFTER_SCRIPTS" | tr ',' ' ')) + for SCRIPT in "${SCRIPTS[@]}"; do + # check if SCRIPT is a file + if [ -f "$SCRIPT" ]; then + echo "executing additional after scripts from $SCRIPT" + source $SCRIPT + sleep 5 + else + echo "$SCRIPT is not a file" + fi + done +fi \ No newline at end of file