Skip to content

Commit

Permalink
wip hash migration
Browse files Browse the repository at this point in the history
  • Loading branch information
samricotta committed Apr 25, 2024
1 parent f75c982 commit 9f3fc57
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
37 changes: 37 additions & 0 deletions testutil/dec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package testutil

import (
"crypto/sha256"
"encoding/hex"
"fmt"

storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

func DiffDecimalsMigration(
ctx sdk.Context,
storeKey *storetypes.KVStoreKey,
iterations int,
migrateDec func(int64),
targetHash string,
) error {
for i := int64(0); i < int64(iterations); i++ {
migrateDec(i)
}

h := sha256.New()
it := ctx.KVStore(storeKey).Iterator(nil, nil)
defer it.Close()
for ; it.Valid(); it.Next() {
h.Write(it.Key())
h.Write(it.Value())
}

hash := h.Sum(nil)
if hex.EncodeToString(hash) != targetHash {
return fmt.Errorf("hashes don't match: %s != %s", hex.EncodeToString(hash), targetHash)
}

return nil
}
45 changes: 45 additions & 0 deletions testutil/math_utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package testutil_test

import (
"crypto/sha256"
"encoding/hex"
"fmt"
"testing"

math "cosmossdk.io/math"
storetypes "cosmossdk.io/store/types"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
)

func TestDiffDecimalsMigration(t *testing.T) {
key := storetypes.NewKVStoreKey("test")
ctx := testutil.DefaultContext(key, storetypes.NewTransientStoreKey("transient"))
for i := int64(0); i < 5; i++ {
legacyDec := math.LegacyNewDec(i)
dec := math.NewDecFromInt64(i)

Check failure on line 21 in testutil/math_utils_test.go

View workflow job for this annotation

GitHub Actions / golangci-lint

undefined: math.NewDecFromInt64 (typecheck)

Check failure on line 21 in testutil/math_utils_test.go

View workflow job for this annotation

GitHub Actions / tests (02)

undefined: math.NewDecFromInt64
ctx.KVStore(key).Set([]byte(fmt.Sprintf("legacy_%d", i)), []byte(legacyDec.String()))
ctx.KVStore(key).Set([]byte(fmt.Sprintf("new_%d", i)), []byte(dec.String()))
}

hashLegacy := computeHash(ctx, key, "legacy_")
hashNew := computeHash(ctx, key, "new_")
require.Equal(t, hashLegacy, hashNew, "Hashes do not match")
}

func computeHash(ctx sdk.Context, key storetypes.StoreKey, prefix string) string {
h := sha256.New()
start, end := prefixRange(prefix)
it := ctx.KVStore(key).Iterator(start, end)
defer it.Close()
for ; it.Valid(); it.Next() {
h.Write(it.Key())
h.Write(it.Value())
}
return hex.EncodeToString(h.Sum(nil))
}

func prefixRange(prefix string) (start, end []byte) {
return []byte(prefix), append([]byte(prefix), 0xFF)
}

0 comments on commit 9f3fc57

Please sign in to comment.