From 11baca28259127fafdcd776b56720886111f18b8 Mon Sep 17 00:00:00 2001 From: zheng-bin Date: Thu, 16 Nov 2023 12:19:39 +0800 Subject: [PATCH] Disable old prefix address compatibility. (#787) * Disable old prefix address compatibility. --- app/upgrade_handler_test.go | 248 -------------------------- common/prefix.go | 18 -- common/prefix_test.go | 22 +-- go.mod | 2 - go.sum | 4 +- x/cert/legacy/v2/store_test.go | 131 -------------- x/oracle/legacy/v3/store_test.go | 194 -------------------- x/shield/legacy/v4/store_test.go | 293 ------------------------------- 8 files changed, 5 insertions(+), 907 deletions(-) delete mode 100644 app/upgrade_handler_test.go delete mode 100644 x/cert/legacy/v2/store_test.go delete mode 100644 x/oracle/legacy/v3/store_test.go delete mode 100644 x/shield/legacy/v4/store_test.go diff --git a/app/upgrade_handler_test.go b/app/upgrade_handler_test.go deleted file mode 100644 index 163bbe581..000000000 --- a/app/upgrade_handler_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package app - -import ( - "encoding/json" - "errors" - "io/ioutil" - "reflect" - "regexp" - "strings" - "testing" - "time" - - "github.com/test-go/testify/require" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkauthtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/authz" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - fgtypes "github.com/cosmos/cosmos-sdk/x/feegrant" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - sktypes "github.com/cosmos/cosmos-sdk/x/staking/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/gogo/protobuf/proto" - "github.com/shentufoundation/shentu/v2/common" - authtypes "github.com/shentufoundation/shentu/v2/x/auth/types" -) - -func setConfig(prefix string) { - stoc := func(txt string) string { - if prefix == "certik" { - return strings.Replace(txt, "shentu", "certik", 1) - } - return txt - } - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(stoc(common.Bech32PrefixAccAddr), stoc(common.Bech32PrefixAccPub)) - cfg.SetBech32PrefixForValidator(stoc(common.Bech32PrefixValAddr), stoc(common.Bech32PrefixValPub)) - cfg.SetBech32PrefixForConsensusNode(stoc(common.Bech32PrefixConsAddr), stoc(common.Bech32PrefixConsPub)) -} - -func TestMigrateStore(t *testing.T) { - genesisState := loadState(t) - - app := Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) - setConfig("certik") - - for _, m := range []string{"auth", "authz", "bank", "staking", "slashing", "gov", "feegrant"} { - app.mm.Modules[m].InitGenesis(ctx, app.appCodec, genesisState[m]) - } - - checkStaking(t, ctx, app, true) - checkFeegrant(t, ctx, app, true) - checkGov(t, ctx, app, true) - checkSlashing(t, ctx, app, true) - checkAuth(t, ctx, app, true) - checkAuthz(t, ctx, app, true) - require.NoError(t, checkBank(ctx, app, true)) - - setConfig("shentu") - err := transAddrPrefix(ctx, *app) - if err != nil { - panic(err) - } - - checkStaking(t, ctx, app, false) - checkFeegrant(t, ctx, app, false) - checkGov(t, ctx, app, false) - checkSlashing(t, ctx, app, false) - checkAuth(t, ctx, app, false) - checkAuthz(t, ctx, app, false) - require.NoError(t, checkBank(ctx, app, false)) - - //check for error cases - require.Error(t, transAddrPrefix(ctx, *app)) - require.Error(t, transAddrPrefixForFeegrant(ctx, *app)) - require.Error(t, transAddrPrefixForStaking(ctx, *app)) - require.Error(t, transAddrPrefixForGov(ctx, *app)) -} - -func loadState(t *testing.T) GenesisState { - data, err := ioutil.ReadFile("../tests/pruned-state.json") - if err != nil { - t.Fatal("failed to read in json") - } - var genesisState GenesisState - if err = json.Unmarshal(data, &genesisState); err != nil { - t.Fatal("failed to parse the json") - } - return genesisState -} - -func NewChecker(t *testing.T, app *ShentuApp, store sdk.KVStore, old bool) Checker { - prePos, preNeg := "shentu", "certik" - if old { - prePos, preNeg = "certik", "shentu" - } - return Checker{t, app, store, - regexp.MustCompile(prePos + "[a-z]{0,10}1"), - regexp.MustCompile(preNeg + "[a-z]{0,10}1"), - } -} - -type Checker struct { - t *testing.T - app *ShentuApp - store sdk.KVStore - prefixPos *regexp.Regexp - prefixNeg *regexp.Regexp -} - -func (c Checker) checkForOneKey(keyPrefix []byte, v any) { - iter := sdk.KVStorePrefixIterator(c.store, keyPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - iv, ok := v.(codec.ProtoMarshaler) - if !ok { - panic("failed to cast to codec.ProtoMarshaler") - } - c.app.appCodec.MustUnmarshal(iter.Value(), iv) - jsonStr := c.app.appCodec.MustMarshalJSON(v.(proto.Message)) - c.checkStr(jsonStr) - p := reflect.ValueOf(v).Elem() - p.Set(reflect.Zero(p.Type())) - } -} - -func (c Checker) checkStr(str []byte) { - if c.prefixPos.FindIndex(str) != nil || c.prefixNeg.FindIndex(str) != nil { - require.NotNil(c.t, c.prefixPos.FindIndex(str)) - require.Nil(c.t, c.prefixNeg.FindIndex(str)) - } -} - -func checkStaking(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[sktypes.StoreKey]) - ck := NewChecker(t, app, store, old) - - ck.checkForOneKey(sktypes.ValidatorsKey, &sktypes.Validator{}) - ck.checkForOneKey(sktypes.DelegationKey, &sktypes.Delegation{}) - ck.checkForOneKey(sktypes.UnbondingDelegationKey, &sktypes.UnbondingDelegation{}) - ck.checkForOneKey(sktypes.RedelegationKey, &sktypes.Redelegation{}) - ck.checkForOneKey(sktypes.UnbondingQueueKey, &sktypes.DVPairs{}) - ck.checkForOneKey(sktypes.RedelegationQueueKey, &sktypes.DVVTriplets{}) - ck.checkForOneKey(sktypes.ValidatorQueueKey, &sktypes.ValAddresses{}) - ck.checkForOneKey(sktypes.HistoricalInfoKey, &sktypes.HistoricalInfo{}) - -} - -func checkGov(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[govtypes.StoreKey]) - ck := NewChecker(t, app, store, old) - ck.checkForOneKey(govtypes.DepositsKeyPrefix, &govtypes.Deposit{}) - ck.checkForOneKey(govtypes.VotesKeyPrefix, &govtypes.Vote{}) - ck.checkForOneKey(govtypes.ProposalsKeyPrefix, &govtypes.Proposal{}) -} - -func checkFeegrant(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[fgtypes.StoreKey]) - ck := NewChecker(t, app, store, old) - ck.checkForOneKey(fgtypes.FeeAllowanceKeyPrefix, &fgtypes.Grant{}) -} - -func checkAuth(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[sdkauthtypes.StoreKey]) - ck := NewChecker(t, app, store, old) - ck.checkForAuth(sdkauthtypes.AddressStoreKeyPrefix) -} - -func checkSlashing(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[slashingtypes.StoreKey]) - ck := NewChecker(t, app, store, old) - ck.checkForOneKey(slashingtypes.ValidatorSigningInfoKeyPrefix, &slashingtypes.ValidatorSigningInfo{}) -} - -func checkAuthz(t *testing.T, ctx sdk.Context, app *ShentuApp, old bool) { - store := ctx.KVStore(app.keys[authzkeeper.StoreKey]) - ck := NewChecker(t, app, store, old) - ck.checkForAuthz(authzkeeper.GrantKey) -} - -func checkBank(ctx sdk.Context, app *ShentuApp, old bool) error { - baseKeeper := app.BankKeeper.BaseKeeper - metaData := baseKeeper.GetAllDenomMetaData(ctx) - oldDescription := "The native staking token of the CertiK Chain." - newDescription := "The native staking token of the Shentu Chain." - for _, meta := range metaData { - if old { - if meta.Description != oldDescription { - return errors.New("bank migration error") - } - } else { - if meta.Description != newDescription { - return errors.New("bank migration error") - } - } - } - return nil - -} - -func (c Checker) checkForAuth(keyPrefix []byte) { - ak := c.app.AccountKeeper - iter := sdk.KVStorePrefixIterator(c.store, keyPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - acc, err := ak.UnmarshalAccount(iter.Value()) - if err != nil { - panic(err) - } - - switch account := acc.(type) { - case *sdkauthtypes.BaseAccount: - c.checkStr([]byte(account.Address)) - case *sdkauthtypes.ModuleAccount: - c.checkStr([]byte(account.Address)) - case *authtypes.ManualVestingAccount: - c.checkStr([]byte(account.Address + account.Unlocker)) - default: - panic("unknown account type") - } - } -} - -func (c Checker) checkForAuthz(keyPrefix []byte) { - iter := sdk.KVStorePrefixIterator(c.store, keyPrefix) - defer iter.Close() - for ; iter.Valid(); iter.Next() { - var grant authz.Grant - c.app.appCodec.MustUnmarshal(iter.Value(), &grant) - authorization := grant.Authorization - value := authorization.GetValue() - - switch authorization.GetTypeUrl() { - case "/cosmos.staking.v1beta1.StakeAuthorization": - stakeAuthorization := &stakingtypes.StakeAuthorization{} - if err := stakeAuthorization.Unmarshal(value); err != nil { - panic(err) - } - c.checkStr([]byte(stakeAuthorization.String())) - } - } -} diff --git a/common/prefix.go b/common/prefix.go index 8a476fa59..54e68010d 100644 --- a/common/prefix.go +++ b/common/prefix.go @@ -26,24 +26,6 @@ const ( Bech32PrefixConsPub = Bech32MainPrefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic ) -// PrefixToCertik convert shentu prefix address to certik prefix address -func PrefixToCertik(address string) (string, error) { - hrp, data, err := bech32.DecodeAndConvert(address) - if err != nil { - return "", err - } - if !strings.HasPrefix(hrp, "shentu") { - return "", fmt.Errorf("invalid address:%s", address) - } - - newhrp := strings.Replace(hrp, "shentu", "certik", 1) - certikAddr, err := bech32.ConvertAndEncode(newhrp, data) - if err != nil { - return "", err - } - return certikAddr, nil -} - // PrefixToShentu convert certik prefix address to shentu prefix address func PrefixToShentu(address string) (string, error) { hrp, data, err := bech32.DecodeAndConvert(address) diff --git a/common/prefix_test.go b/common/prefix_test.go index 30aab21e8..bbece0b46 100644 --- a/common/prefix_test.go +++ b/common/prefix_test.go @@ -2,30 +2,14 @@ package common import ( "crypto/sha256" - "github.com/stretchr/testify/require" "strings" "testing" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/types/bech32" ) -func TestPrefixToCertik(t *testing.T) { - sum := sha256.Sum256([]byte("hello world\n")) - ss := "shentu" - - address, err := bech32.ConvertAndEncode(ss, sum[:]) - require.NoError(t, err) - - certikAddr, err := PrefixToCertik(address) - require.NoError(t, err) - require.True(t, strings.HasPrefix(certikAddr, "certik")) - - address, err = bech32.ConvertAndEncode("certik", sum[:]) - require.NoError(t, err) - _, err = PrefixToCertik(address) - require.Error(t, err) -} - func TestPrefixToShentu(t *testing.T) { sum := sha256.Sum256([]byte("hello world\n")) ss := "certik" @@ -40,5 +24,5 @@ func TestPrefixToShentu(t *testing.T) { address, err = bech32.ConvertAndEncode("shentu", sum[:]) require.NoError(t, err) _, err = PrefixToShentu(address) - require.Error(t, err) + require.NoError(t, err) } diff --git a/go.mod b/go.mod index 15910baff..987aaa963 100644 --- a/go.mod +++ b/go.mod @@ -304,5 +304,3 @@ require ( replace google.golang.org/grpc => google.golang.org/grpc v1.33.2 replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.2-alpha.regen.4 - -replace github.com/cosmos/cosmos-sdk => github.com/shentufoundation/cosmos-sdk v0.45.11-3 diff --git a/go.sum b/go.sum index 149820ae9..d3456e5c6 100644 --- a/go.sum +++ b/go.sum @@ -233,6 +233,8 @@ github.com/cosmos/btcutil v1.0.4 h1:n7C2ngKXo7UC9gNyMNLbzqz7Asuf+7Qv4gnX/rOdQ44= github.com/cosmos/btcutil v1.0.4/go.mod h1:Ffqc8Hn6TJUdDgHBwIZLtrLQC1KdJ9jGJl/TvgUaxbU= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= +github.com/cosmos/cosmos-sdk v0.45.11 h1:Pc44fFEkai0KXFND5Ys/2ZJkfVdstMIBzKBN8MY7Ll0= +github.com/cosmos/cosmos-sdk v0.45.11/go.mod h1:45z8Q1Ah4iypFycu2Kl4kBPIsQKUiND8G2CUX+HTtPM= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= @@ -1055,8 +1057,6 @@ github.com/securego/gosec/v2 v2.13.1/go.mod h1:EO1sImBMBWFjOTFzMWfTRrZW6M15gm60l github.com/segmentio/fasthash v1.0.3/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= -github.com/shentufoundation/cosmos-sdk v0.45.11-3 h1:c3x/2g02HVE36OkHCC7WHqxEvvdZaeMrPTXYTiqQDew= -github.com/shentufoundation/cosmos-sdk v0.45.11-3/go.mod h1:45z8Q1Ah4iypFycu2Kl4kBPIsQKUiND8G2CUX+HTtPM= github.com/shirou/gopsutil v2.20.5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= diff --git a/x/cert/legacy/v2/store_test.go b/x/cert/legacy/v2/store_test.go deleted file mode 100644 index f4203fb57..000000000 --- a/x/cert/legacy/v2/store_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package v2_test - -import ( - "fmt" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/gogo/protobuf/proto" - "github.com/stretchr/testify/require" - "math/rand" - "testing" - "time" - - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - - shentuapp "github.com/shentufoundation/shentu/v2/app" - "github.com/shentufoundation/shentu/v2/common" - v2 "github.com/shentufoundation/shentu/v2/x/cert/legacy/v2" - "github.com/shentufoundation/shentu/v2/x/cert/types" -) - -func makeCertificate(certType string) types.Certificate { - _, _, addr := testdata.KeyTestPubAddr() - certifier, _ := common.PrefixToCertik(addr.String()) - - content := types.AssembleContent(certType, certifier) - msg, ok := content.(proto.Message) - if !ok { - panic(fmt.Errorf("%T does not implement proto.Message", content)) - } - any, err := codectypes.NewAnyWithValue(msg) - if err != nil { - panic(err) - } - - return types.Certificate{ - CertificateId: rand.Uint64(), - Content: any, - CompilationContent: &types.CompilationContent{Compiler: "", BytecodeHash: ""}, - Description: "for test", - Certifier: certifier, - } -} - -func makeCertifier(certifierAddr, alias string) types.Certifier { - _, _, addr := testdata.KeyTestPubAddr() - proposer, _ := common.PrefixToCertik(addr.String()) - - return types.Certifier{ - Address: certifierAddr, - Alias: alias, - Proposer: proposer, - Description: "unit test", - } -} - -func saveLibrary(cdc codec.BinaryCodec, storeKey sdk.KVStore) types.Library { - _, _, libraryAddr := testdata.KeyTestPubAddr() - libraryAddrStr, _ := common.PrefixToCertik(libraryAddr.String()) - - _, _, publisherAddr := testdata.KeyTestPubAddr() - publisherStr, _ := common.PrefixToCertik(publisherAddr.String()) - - library := types.Library{ - Address: libraryAddrStr, - Publisher: publisherStr, - } - - bz := cdc.MustMarshalLengthPrefixed(&library) - storeKey.Set(types.LibraryStoreKey(libraryAddr), bz) - return library -} - -func TestMigrateStore(t *testing.T) { - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(common.Bech32PrefixAccAddr, common.Bech32PrefixAccPub) - - app := shentuapp.Setup(false) - ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) - cdc := shentuapp.MakeEncodingConfig().Marshaler - - oldCertificate := makeCertificate("IDENTITY") - - oldCertifier := makeCertifier(oldCertificate.Certifier, "test_certifier") - - app.CertKeeper.SetCertificate(ctx, oldCertificate) - app.CertKeeper.SetCertifier(ctx, oldCertifier) - - store := ctx.KVStore(app.GetKey(types.StoreKey)) - - oldLibrary := saveLibrary(cdc, store) - - err := v2.MigrateStore(ctx, app.GetKey(types.StoreKey), cdc) - require.NoError(t, err) - - //check for Certificate - var cert types.Certificate - bz := store.Get(types.CertificateStoreKey(oldCertificate.CertificateId)) - cdc.MustUnmarshal(bz, &cert) - - newCertifierAddr, _ := common.PrefixToShentu(oldCertificate.Certifier) - require.Equal(t, newCertifierAddr, cert.Certifier) - - var certifier types.Certifier - certifierAcc, err := sdk.AccAddressFromBech32(cert.Certifier) - require.NoError(t, err) - bz = store.Get(types.CertifierStoreKey(certifierAcc)) - cdc.MustUnmarshalLengthPrefixed(bz, &certifier) - require.Equal(t, newCertifierAddr, certifier.Address) - require.Equal(t, newCertifierAddr, cert.GetContentString()) - - newCertifierProposer, _ := common.PrefixToShentu(oldCertifier.Proposer) - require.Equal(t, newCertifierProposer, certifier.Proposer) - - bz = store.Get(types.CertifierAliasStoreKey(oldCertifier.Alias)) - var certifierAlias types.Certifier - cdc.MustUnmarshalLengthPrefixed(bz, &certifierAlias) - require.Equal(t, newCertifierAddr, certifierAlias.Address) - require.Equal(t, newCertifierProposer, certifierAlias.Proposer) - - libraryAddr, _ := sdk.AccAddressFromBech32(oldLibrary.Address) - bz = store.Get(types.LibraryStoreKey(libraryAddr)) - var library types.Library - cdc.MustUnmarshalLengthPrefixed(bz, &library) - newLibraryAddr, _ := common.PrefixToShentu(oldLibrary.Address) - newPublisherAddr, _ := common.PrefixToShentu(oldLibrary.Publisher) - require.Equal(t, library.Address, newLibraryAddr) - require.Equal(t, library.Publisher, newPublisherAddr) -} diff --git a/x/oracle/legacy/v3/store_test.go b/x/oracle/legacy/v3/store_test.go deleted file mode 100644 index 1bd851bfb..000000000 --- a/x/oracle/legacy/v3/store_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package v3_test - -import ( - "encoding/hex" - "github.com/stretchr/testify/require" - "math/rand" - "testing" - "time" - - "github.com/tendermint/tendermint/crypto/ed25519" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/bech32" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - - shentuapp "github.com/shentufoundation/shentu/v2/app" - "github.com/shentufoundation/shentu/v2/common" - v3 "github.com/shentufoundation/shentu/v2/x/oracle/legacy/v3" - oracletypes "github.com/shentufoundation/shentu/v2/x/oracle/types" -) - -func Test_MigrateAllTaskStore(t *testing.T) { - app := shentuapp.Setup(false) - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(common.Bech32PrefixAccAddr, common.Bech32PrefixAccPub) - ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) - cdc := shentuapp.MakeEncodingConfig().Marshaler - - store := ctx.KVStore(app.GetKey(oracletypes.StoreKey)) - operator, _ := common.PrefixToCertik(sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()).String()) - // mock old data - - response := oracletypes.Response{ - Operator: operator, - Weight: sdk.NewInt(50), - Reward: nil, - } - - tasks := make(map[string]oracletypes.TaskI) - for i := 0; i < 10; i++ { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - beginBlock := r.Int63n(100) - waitingBlocks := r.Int63n(10) + 1 - expireHeight := beginBlock + waitingBlocks - status := r.Intn(4) - creator, _ := common.PrefixToCertik(sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()).String()) - - task := oracletypes.Task{ - Contract: simtypes.RandStringOfLength(r, 10), - Function: simtypes.RandStringOfLength(r, 5), - BeginBlock: beginBlock, - Bounty: nil, - Description: simtypes.RandStringOfLength(r, 5), - Expiration: time.Time{}, - Creator: creator, - Responses: nil, - Result: simtypes.RandomAmount(r, sdk.NewInt(100)), - ExpireHeight: expireHeight, - WaitingBlocks: waitingBlocks, - Status: oracletypes.TaskStatus(status), - } - task.AddResponse(response) - tasks[string(oracletypes.NewTaskID(task.Contract, task.Function))] = &task - - bz, err := cdc.MarshalInterface(&task) - if err != nil { - panic(err) - } - store.Set(oracletypes.TaskStoreKey(task.GetID()), bz) - - txTask := oracletypes.TxTask{ - AtxHash: []byte(hex.EncodeToString([]byte(simtypes.RandStringOfLength(r, 10)))), - Bounty: nil, - ValidTime: time.Time{}, - Expiration: time.Time{}, - Creator: creator, - Responses: nil, - Status: oracletypes.TaskStatus(status), - Score: r.Int63n(100), - } - txTask.AddResponse(response) - tasks[string(txTask.GetID())] = &txTask - - bz, err = cdc.MarshalInterface(&txTask) - if err != nil { - panic(err) - } - store.Set(oracletypes.TaskStoreKey(txTask.GetID()), bz) - } - - err := v3.MigrateAllTaskStore(ctx, app.GetKey(oracletypes.StoreKey), cdc) - require.Nil(t, err) - - app.OracleKeeper.IteratorAllTasks(ctx, func(task oracletypes.TaskI) bool { - creator := task.GetCreator() - _, _, err := bech32.DecodeAndConvert(creator) - require.NoError(t, err) - - tk, ok := tasks[string(task.GetID())] - require.True(t, ok) - shentuAddr, err := common.PrefixToShentu(tk.GetCreator()) - require.NoError(t, err) - require.Equal(t, shentuAddr, task.GetCreator()) - - require.Equal(t, tk.GetBounty(), task.GetBounty()) - require.Equal(t, tk.GetScore(), task.GetScore()) - return false - }) - -} - -func Test_MigrateOperator(t *testing.T) { - app := shentuapp.Setup(false) - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(common.Bech32PrefixAccAddr, common.Bech32PrefixAccPub) - ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) - cdc := shentuapp.MakeEncodingConfig().Marshaler - - store := ctx.KVStore(app.GetKey(oracletypes.StoreKey)) - // mock old data - for i := 0; i < 10; i++ { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - operatorAddr, _ := common.PrefixToCertik(sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()).String()) - proposerAddr, _ := common.PrefixToCertik(sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()).String()) - - operator := oracletypes.Operator{ - Address: operatorAddr, - Proposer: proposerAddr, - Collateral: nil, - AccumulatedRewards: nil, - Name: simtypes.RandStringOfLength(r, 10), - } - - bz := cdc.MustMarshalLengthPrefixed(&operator) - _, addrBz, err := bech32.DecodeAndConvert(operatorAddr) - if err != nil { - panic(err) - } - addr := sdk.AccAddress(addrBz) - store.Set(oracletypes.OperatorStoreKey(addr), bz) - } - - err := v3.MigrateOperatorStore(ctx, app.GetKey(oracletypes.StoreKey), cdc) - require.Nil(t, err) - - app.OracleKeeper.IterateAllOperators(ctx, func(operator oracletypes.Operator) bool { - hrp, _, err := bech32.DecodeAndConvert(operator.Address) - require.NoError(t, err) - require.Equal(t, hrp, "shentu") - - hrp, _, err = bech32.DecodeAndConvert(operator.Proposer) - require.NoError(t, err) - require.Equal(t, hrp, "shentu") - return false - }) -} - -func Test_MigrateWithdraw(t *testing.T) { - app := shentuapp.Setup(false) - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(common.Bech32PrefixAccAddr, common.Bech32PrefixAccPub) - ctx := app.BaseApp.NewContext(false, tmproto.Header{Time: time.Now().UTC()}) - cdc := shentuapp.MakeEncodingConfig().Marshaler - - store := ctx.KVStore(app.GetKey(oracletypes.StoreKey)) - // mock old data - for i := 0; i < 10; i++ { - withdrawsAddr, _ := common.PrefixToCertik(sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address().Bytes()).String()) - - withdraw := oracletypes.Withdraw{ - Address: withdrawsAddr, - Amount: nil, - DueBlock: rand.Int63(), - } - - bz := cdc.MustMarshalLengthPrefixed(&withdraw) - withdrawAcc, err := sdk.AccAddressFromBech32(withdrawsAddr) - if err != nil { - panic(err) - } - store.Set(oracletypes.WithdrawStoreKey(withdrawAcc, withdraw.DueBlock), bz) - } - - err := v3.MigrateWithdrawStore(ctx, app.GetKey(oracletypes.StoreKey), cdc) - require.Nil(t, err) - - app.OracleKeeper.IterateAllWithdraws(ctx, func(withdraw oracletypes.Withdraw) bool { - hrp, _, err := bech32.DecodeAndConvert(withdraw.Address) - require.NoError(t, err) - require.Equal(t, hrp, "shentu") - return false - }) -} diff --git a/x/shield/legacy/v4/store_test.go b/x/shield/legacy/v4/store_test.go deleted file mode 100644 index 4b05c31cf..000000000 --- a/x/shield/legacy/v4/store_test.go +++ /dev/null @@ -1,293 +0,0 @@ -package v4_test - -import ( - "github.com/stretchr/testify/require" - "math/rand" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/testutil" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/shentufoundation/shentu/v2/common" - v4 "github.com/shentufoundation/shentu/v2/x/shield/legacy/v4" - "github.com/shentufoundation/shentu/v2/x/shield/types" -) - -const ( - DENOM = "uctk" - AMOUNT_PROVIDER = 10e5 - SHIELD = 1e8 - SERVICE_FEES = 1e3 - PURCHASE_NUM = 8 - PURCHASE_COIN = 1000 -) - -type ProviderAndAddr struct { - addr sdk.AccAddress - pvd types.Provider -} - -func makeProvider() ProviderAndAddr { - _, _, addr := testdata.KeyTestPubAddr() - newAddr, _ := common.PrefixToCertik(addr.String()) - return ProviderAndAddr{ - addr, - types.Provider{ - Address: newAddr, - DelegationBonded: sdk.NewInt(10), - Collateral: sdk.NewInt(3), - TotalLocked: sdk.NewInt(20), - Withdrawing: sdk.NewInt(7), - Rewards: sdk.NewDecCoins(sdk.NewDecCoin(DENOM, sdk.NewInt(AMOUNT_PROVIDER))), - }, - } -} - -func makePurchases() (entries []types.Purchase) { - for i := 0; i < PURCHASE_NUM; i++ { - entries = append(entries, types.Purchase{ - PurchaseId: rand.Uint64(), - ProtectionEndTime: time.Now().Add(10 * time.Minute), - DeletionTime: time.Now().Add(time.Hour), - Description: "--", - Shield: sdk.NewInt(SHIELD), - ServiceFees: sdk.NewDecCoins(sdk.NewDecCoin(DENOM, sdk.NewInt(SERVICE_FEES))), - }) - } - return -} - -func makePool() types.Pool { - _, _, addr := testdata.KeyTestPubAddr() - sponsorAddr, _ := common.PrefixToCertik(addr.String()) - - pool := types.Pool{ - Id: rand.Uint64(), - Description: "for_test", - Sponsor: "for_test", - SponsorAddr: sponsorAddr, - ShieldLimit: sdk.NewInt(PURCHASE_NUM), - } - return pool -} - -func makePurchaseList(poolId uint64) (sdk.AccAddress, types.PurchaseList) { - _, _, addr := testdata.KeyTestPubAddr() - purchaserAddr, _ := common.PrefixToCertik(addr.String()) - return addr, types.PurchaseList{ - PoolId: poolId, - Purchaser: purchaserAddr, - Entries: makePurchases(), - } -} - -func makeReimbursement() types.Reimbursement { - _, _, addr := testdata.KeyTestPubAddr() - beneficiaryAddr, _ := common.PrefixToCertik(addr.String()) - return types.Reimbursement{ - Amount: sdk.NewCoins(sdk.NewCoin(DENOM, sdk.NewInt(PURCHASE_COIN))), - PayoutTime: time.Now().Add(time.Hour), - Beneficiary: beneficiaryAddr, - } -} - -func makeWithdraws() (withdraws []types.Withdraw) { - for i := 0; i < 5; i++ { - _, _, addr := testdata.KeyTestPubAddr() - withdrawAddr, _ := common.PrefixToCertik(addr.String()) - - withdraws = append(withdraws, types.Withdraw{ - Address: withdrawAddr, - Amount: sdk.NewInt(rand.Int63()), - CompletionTime: time.Now().Add(time.Hour), - }) - } - return -} - -func makeShieldStaking(poolId uint64) types.ShieldStaking { - _, _, addr := testdata.KeyTestPubAddr() - purchaser, _ := common.PrefixToCertik(addr.String()) - - return types.ShieldStaking{ - PoolId: poolId, - Purchaser: purchaser, - Amount: sdk.NewInt(rand.Int63()), - WithdrawRequested: sdk.NewInt(rand.Int63()), - } -} - -func TestMigrateStore(t *testing.T) { - cfg := sdk.GetConfig() - cfg.SetBech32PrefixForAccount(common.Bech32PrefixAccAddr, common.Bech32PrefixAccPub) - cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) - shieldKey := sdk.NewKVStoreKey("shield") - ctx := testutil.DefaultContext(shieldKey, sdk.NewTransientStoreKey("transient_test")) - store := ctx.KVStore(shieldKey) - - providerCases := []ProviderAndAddr{ - makeProvider(), - makeProvider(), - } - for _, pc := range providerCases { - bz := cdc.MustMarshalLengthPrefixed(&pc.pvd) - store.Set(types.GetProviderKey(pc.addr), bz) - } - - //set data of PurchaseList in the store - type PLCase struct { - poolID uint64 - key []byte - purchaser string - } - - type poolCase struct { - poolID uint64 - sponsorAddr string - } - var poolPurchaserPairs types.PoolPurchaserPairs - plCases := make([]PLCase, 0, 5) - poolCases := make([]poolCase, 0, 5) - for i := 0; i < 5; i++ { - pool := makePool() - bz := cdc.MustMarshalLengthPrefixed(&pool) - store.Set(types.GetPoolKey(pool.Id), bz) - poolCases = append(poolCases, poolCase{poolID: pool.Id, sponsorAddr: pool.SponsorAddr}) - - addr, purchaseList := makePurchaseList(pool.Id) - key := types.GetPurchaseListKey(pool.Id, addr) - bz = cdc.MustMarshalLengthPrefixed(&purchaseList) - store.Set(key, bz) - plCases = append(plCases, PLCase{poolID: pool.Id, key: key, purchaser: purchaseList.Purchaser}) - - poolPurchaserPairs.Pairs = append(poolPurchaserPairs.Pairs, types.PoolPurchaser{ - PoolId: pool.Id, - Purchaser: purchaseList.Purchaser, - }) - } - - oneHour := time.Now().Add(time.Hour) - { - //set PurchaseExpirationTimeKey value - bz := cdc.MustMarshalLengthPrefixed(&poolPurchaserPairs) - store.Set(types.GetPurchaseExpirationTimeKey(oneHour), bz) - } - - proposalID := rand.Uint64() - reimbursement := makeReimbursement() - { - bz := cdc.MustMarshalLengthPrefixed(&reimbursement) - store.Set(types.GetReimbursementKey(proposalID), bz) - } - - withdraws := makeWithdraws() - { - bz := cdc.MustMarshalLengthPrefixed(&types.Withdraws{Withdraws: withdraws}) - store.Set(types.GetWithdrawCompletionTimeKey(oneHour), bz) - } - - shieldStaking := makeShieldStaking(plCases[0].poolID) - { - purchaseAddr, _ := sdk.AccAddressFromBech32(shieldStaking.Purchaser) - bz := cdc.MustMarshalLengthPrefixed(&shieldStaking) - store.Set(types.GetStakeForShieldKey(plCases[0].poolID, purchaseAddr), bz) - - } - err := v4.MigrateStore(ctx, shieldKey, cdc) - require.NoError(t, err) - - //check for Provider - for _, pc := range providerCases { - item := pc - t.Run("provider", func(t *testing.T) { - var pvd types.Provider - bz := store.Get(types.GetProviderKey(item.addr)) - cdc.MustUnmarshalLengthPrefixed(bz, &pvd) - - shentuAddr, _ := common.PrefixToShentu(item.pvd.Address) - require.Equal(t, pvd.Address, shentuAddr) - dc := pvd.Rewards[0] - require.Equal(t, sdk.NewInt64DecCoin(DENOM, AMOUNT_PROVIDER), dc) - }) - } - - //check for PurchaseList - for _, item := range plCases { - t.Run("PurchaseList", func(t *testing.T) { - var pl types.PurchaseList - bz := store.Get(item.key) - cdc.MustUnmarshalLengthPrefixed(bz, &pl) - require.Equal(t, item.poolID, pl.PoolId) - shentuPurchaser, _ := common.PrefixToShentu(item.purchaser) - require.Equal(t, shentuPurchaser, pl.Purchaser) - require.Equal(t, PURCHASE_NUM, len(pl.Entries)) - require.Equal(t, sdk.NewInt(SHIELD), pl.Entries[0].Shield) - require.Equal(t, - sdk.DecCoins{sdk.NewInt64DecCoin(DENOM, SERVICE_FEES)}, - pl.Entries[1].ServiceFees) - }) - } - - //check for pool - for _, item := range poolCases { - t.Run("pool", func(t *testing.T) { - var pool types.Pool - bz := store.Get(types.GetPoolKey(item.poolID)) - cdc.MustUnmarshalLengthPrefixed(bz, &pool) - shentuSponsor, _ := common.PrefixToShentu(item.sponsorAddr) - require.Equal(t, pool.SponsorAddr, shentuSponsor) - }) - } - - //check for Expiration PurchaseQueue - { - bz := store.Get(types.GetPurchaseExpirationTimeKey(oneHour)) - require.NotNil(t, bz) - var ppPairs types.PoolPurchaserPairs - cdc.MustUnmarshalLengthPrefixed(bz, &ppPairs) - - old := poolPurchaserPairs.Pairs - for i, item := range ppPairs.Pairs { - shentuAddr, _ := common.PrefixToShentu(old[i].Purchaser) - require.Equal(t, item.Purchaser, shentuAddr) - } - } - - // check for Reimbursement - { - bz := store.Get(types.GetReimbursementKey(proposalID)) - var newReimbursement types.Reimbursement - cdc.MustUnmarshalLengthPrefixed(bz, &newReimbursement) - - beneficiary, _ := common.PrefixToShentu(reimbursement.Beneficiary) - require.Equal(t, beneficiary, newReimbursement.Beneficiary) - } - - //check for Withdraws - { - bz := store.Get(types.GetWithdrawCompletionTimeKey(oneHour)) - var newWithdraws types.Withdraws - cdc.MustUnmarshalLengthPrefixed(bz, &newWithdraws) - - for i, withdraw := range newWithdraws.Withdraws { - shentuAddr, _ := common.PrefixToShentu(withdraws[i].Address) - require.Equal(t, shentuAddr, withdraw.Address) - } - } - - { - purchaser, err := sdk.AccAddressFromBech32(shieldStaking.Purchaser) - require.NoError(t, err) - - bz := store.Get(types.GetStakeForShieldKey(shieldStaking.PoolId, purchaser)) - var purchase types.ShieldStaking - cdc.MustUnmarshalLengthPrefixed(bz, &purchase) - - shentuPurchaser, _ := common.PrefixToShentu(shieldStaking.Purchaser) - require.Equal(t, shentuPurchaser, purchase.Purchaser) - } -}