Skip to content

Commit

Permalink
fix: fix bech32 cache to get bech32 from proper cache (#219)
Browse files Browse the repository at this point in the history
* fix: fix bech32 cache to execute type casting if only values exists

* test: add unit tests

* fix: fix bech32 cache to get bech32 from proper cache
  • Loading branch information
wetcod authored Jun 1, 2021
1 parent f904f13 commit 9c2db65
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
12 changes: 8 additions & 4 deletions types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
32 changes: 32 additions & 0 deletions types/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 9c2db65

Please sign in to comment.