From 842b06003f97d31e4ec83847e9fe8185d51a1fc7 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Wed, 19 May 2021 10:41:42 -0400 Subject: [PATCH] fix: add missing nil check in store.GetStore (#9354) (#9359) * fix: add missing nil check in store.GetStore * check nil in rootmulti as well (cherry picked from commit b065e20f2bfb24312b4aa93091866741df6664d3) Co-authored-by: Robert Zaremba --- store/cachemulti/store.go | 8 ++++++-- store/cachemulti/store_test.go | 23 +++++++++++++++++++++++ store/rootmulti/store.go | 6 +++++- 3 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 store/cachemulti/store_test.go diff --git a/store/cachemulti/store.go b/store/cachemulti/store.go index 59a29c358cc..43bb40ae76c 100644 --- a/store/cachemulti/store.go +++ b/store/cachemulti/store.go @@ -141,13 +141,17 @@ func (cms Store) CacheMultiStoreWithVersion(_ int64) (types.CacheMultiStore, err // GetStore returns an underlying Store by key. func (cms Store) GetStore(key types.StoreKey) types.Store { - return cms.stores[key].(types.Store) + s := cms.stores[key] + if key == nil || s == nil { + panic(fmt.Sprintf("kv store with key %v has not been registered in stores", key)) + } + return s.(types.Store) } // GetKVStore returns an underlying KVStore by key. func (cms Store) GetKVStore(key types.StoreKey) types.KVStore { store := cms.stores[key] - if key == nil { + if key == nil || store == nil { panic(fmt.Sprintf("kv store with key %v has not been registered in stores", key)) } return store.(types.KVStore) diff --git a/store/cachemulti/store_test.go b/store/cachemulti/store_test.go new file mode 100644 index 00000000000..8747df9ef96 --- /dev/null +++ b/store/cachemulti/store_test.go @@ -0,0 +1,23 @@ +package cachemulti + +import ( + "fmt" + "testing" + + "github.com/cosmos/cosmos-sdk/store/types" + "github.com/stretchr/testify/require" +) + +func TestStoreGetKVStore(t *testing.T) { + require := require.New(t) + + s := Store{stores: map[types.StoreKey]types.CacheWrap{}} + key := types.NewKVStoreKey("abc") + errMsg := fmt.Sprintf("kv store with key %v has not been registered in stores", key) + + require.PanicsWithValue(errMsg, + func() { s.GetStore(key) }) + + require.PanicsWithValue(errMsg, + func() { s.GetKVStore(key) }) +} diff --git a/store/rootmulti/store.go b/store/rootmulti/store.go index 1ca43eae9d4..53651091439 100644 --- a/store/rootmulti/store.go +++ b/store/rootmulti/store.go @@ -467,7 +467,11 @@ func (rs *Store) GetStore(key types.StoreKey) types.Store { // NOTE: The returned KVStore may be wrapped in an inter-block cache if it is // set on the root store. func (rs *Store) GetKVStore(key types.StoreKey) types.KVStore { - store := rs.stores[key].(types.KVStore) + s := rs.stores[key] + if s == nil { + panic(fmt.Sprintf("store does not exist for key: %s", key.Name())) + } + store := s.(types.KVStore) if rs.TracingEnabled() { store = tracekv.NewStore(store, rs.traceWriter, rs.traceContext)