diff --git a/types/address.go b/types/address.go index 35a8982465..d46299868a 100644 --- a/types/address.go +++ b/types/address.go @@ -122,15 +122,19 @@ func SetBech32Cache(size int64) { func (cache *Bech32Cache) GetAddr(bech32Addr string) ([]byte, bool) { if cache.bech32ToAddrCache != nil { rawAddr, ok := cache.bech32ToAddrCache.Get(bech32Addr) - return rawAddr.([]byte), ok + if ok { + return rawAddr.([]byte), ok + } } return nil, false } func (cache *Bech32Cache) GetBech32(rawAddr []byte) (string, bool) { - if cache.bech32ToAddrCache != nil { - bech32Addr, ok := cache.bech32ToAddrCache.Get(rawAddr) - return bech32Addr.(string), ok + if cache.addrToBech32Cache != nil { + bech32Addr, ok := cache.addrToBech32Cache.Get(string(rawAddr)) + if ok { + return bech32Addr.(string), ok + } } return "", false } diff --git a/types/address_test.go b/types/address_test.go index ddc6980319..ddd8d679a8 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -520,3 +520,35 @@ func (s *addressTestSuite) TestGetFromBech32() { s.Require().Error(err) s.Require().Equal("invalid Bech32 prefix; expected x, got cosmos", err.Error()) } + +func (s *addressTestSuite) TestBech32Cache() { + pubBz := make([]byte, ed25519.PubKeySize) + pub := &ed25519.PubKey{Key: pubBz} + + s.T().Log("access bech32ToAddrCache before access addrToBech32Cache") + { + rand.Read(pub.Key) + addr := types.AccAddress(pub.Address()) + bech32Addr := addr.String() + types.SetBech32Cache(types.DefaultBech32CacheSize) + + rawAddr, err := types.AccAddressFromBech32(bech32Addr) + s.Require().Nil(err) + require.Equal(s.T(), addr, rawAddr) + + require.Equal(s.T(), bech32Addr, addr.String()) + } + s.T().Log("access addrToBech32Cache before access bech32ToAddrCache") + { + rand.Read(pub.Key) + addr := types.AccAddress(pub.Address()) + bech32Addr := addr.String() + types.SetBech32Cache(types.DefaultBech32CacheSize) + + require.Equal(s.T(), bech32Addr, addr.String()) + + rawAddr, err := types.AccAddressFromBech32(bech32Addr) + s.Require().Nil(err) + require.Equal(s.T(), addr, rawAddr) + } +}