Skip to content

Commit

Permalink
Lock mutex on getting element from cache (cosmos#8767)
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-zaremba authored Mar 3, 2021
1 parent 91affb5 commit 0b6833c
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,11 +268,12 @@ func (aa AccAddress) String() string {
}

var key = conv.UnsafeBytesToStr(aa)
accAddrMu.Lock()
defer accAddrMu.Unlock()
if addr, ok := accAddrCache.Get(key); ok {
return addr.(string)
}
return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(),
aa, &accAddrMu, accAddrCache, key)
return cacheBech32Addr(GetConfig().GetBech32AccountAddrPrefix(), aa, accAddrCache, key)
}

// Format implements the fmt.Formatter interface.
Expand Down Expand Up @@ -416,11 +417,12 @@ func (va ValAddress) String() string {
}

var key = conv.UnsafeBytesToStr(va)
valAddrMu.Lock()
defer valAddrMu.Unlock()
if addr, ok := valAddrCache.Get(key); ok {
return addr.(string)
}
return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(),
va, &valAddrMu, valAddrCache, key)
return cacheBech32Addr(GetConfig().GetBech32ValidatorAddrPrefix(), va, valAddrCache, key)
}

// Format implements the fmt.Formatter interface.
Expand Down Expand Up @@ -569,11 +571,12 @@ func (ca ConsAddress) String() string {
}

var key = conv.UnsafeBytesToStr(ca)
consAddrMu.Lock()
defer consAddrMu.Unlock()
if addr, ok := consAddrCache.Get(key); ok {
return addr.(string)
}
return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(),
ca, &consAddrMu, consAddrCache, key)
return cacheBech32Addr(GetConfig().GetBech32ConsensusAddrPrefix(), ca, consAddrCache, key)
}

// Bech32ifyAddressBytes returns a bech32 representation of address bytes.
Expand Down Expand Up @@ -719,13 +722,11 @@ func addressBytesFromHexString(address string) ([]byte, error) {
return hex.DecodeString(address)
}

func cacheBech32Addr(prefix string, addr []byte, m sync.Locker, cache *simplelru.LRU, cacheKey string) string {
func cacheBech32Addr(prefix string, addr []byte, cache *simplelru.LRU, cacheKey string) string {
bech32Addr, err := bech32.ConvertAndEncode(prefix, addr)
if err != nil {
panic(err)
}
m.Lock()
cache.Add(cacheKey, bech32Addr)
m.Unlock()
return bech32Addr
}

0 comments on commit 0b6833c

Please sign in to comment.