Skip to content

Commit

Permalink
Fix MT cache data race (0xPolygonHermez#650)
Browse files Browse the repository at this point in the history
  • Loading branch information
fgimenez authored May 17, 2022
1 parent f5ad582 commit df7bc4b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
9 changes: 6 additions & 3 deletions state/tree/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ func newNodeCache() *nodeCache {
func (nc *nodeCache) get(key []uint64) ([]uint64, error) {
keyStr := h4ToString(key)

nc.lock.Lock()
defer nc.lock.Unlock()

item, ok := nc.data[keyStr]
if !ok {
return nil, errMTNodeCacheItemNotFound
Expand All @@ -64,14 +67,14 @@ func (nc *nodeCache) get(key []uint64) ([]uint64, error) {

// set inserts a new MT node cache entry.
func (nc *nodeCache) set(key []uint64, value []uint64) error {
nc.lock.Lock()
defer nc.lock.Unlock()

if len(nc.data) >= maxMTNodeCacheEntries {
return errors.New("MT node cache is full")
}
keyStr := h4ToString(key)

nc.lock.Lock()
defer nc.lock.Unlock()

nc.data[keyStr] = value

return nil
Expand Down
33 changes: 33 additions & 0 deletions state/tree/cache_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tree

import (
"sync"
"testing"

"github.com/hermeznetwork/hermez-core/test/testutils"
Expand Down Expand Up @@ -145,3 +146,35 @@ func TestMTNodeCacheClear(t *testing.T) {

require.Zero(t, len(subject.data))
}

func TestConcurrentAccess(t *testing.T) {
subject := newNodeCache()
var wg sync.WaitGroup

const totalItems = 10
for i := 0; i < totalItems; i++ {
wg.Add(1)

go func(i int) {
defer wg.Done()

err := subject.set([]uint64{1, 1, 1, uint64(i)}, []uint64{uint64(i)})
require.NoError(t, err)
}(i)
}
wg.Wait()

for i := 0; i < totalItems; i++ {
wg.Add(1)

go func(i int) {
defer wg.Done()

value, err := subject.get([]uint64{1, 1, 1, uint64(i)})
require.NoError(t, err)

require.Equal(t, value, []uint64{uint64(i)})
}(i)
}
wg.Wait()
}

0 comments on commit df7bc4b

Please sign in to comment.