Skip to content

Commit

Permalink
fix panics on concurrent use (concurrent map writes)
Browse files Browse the repository at this point in the history
  • Loading branch information
pk910 committed Aug 5, 2024
1 parent d89ce22 commit 651d1ad
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions dynssz.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ package dynssz
import (
"fmt"
"reflect"
"sync"
)

type DynSsz struct {
fastsszCompatMutex sync.Mutex
fastsszCompatCache map[reflect.Type]*fastsszCompatibility
typeSizeMutex sync.RWMutex
typeSizeCache map[reflect.Type]*cachedSszSize
specValues map[string]any
specValueCache map[string]*cachedSpecValue
Expand Down
3 changes: 3 additions & 0 deletions fastssz.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ type fastsszCompatibility struct {
// that would prevent the use of fastssz for encoding or decoding.

func (d *DynSsz) getFastsszCompatibility(targetType reflect.Type, sizeHints []sszSizeHint) (*fastsszCompatibility, error) {
d.fastsszCompatMutex.Lock()
defer d.fastsszCompatMutex.Unlock()

if cachedCompatibility := d.fastsszCompatCache[targetType]; cachedCompatibility != nil {
return cachedCompatibility, nil
}
Expand Down
5 changes: 5 additions & 0 deletions sszsize.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,12 @@ func (d *DynSsz) getSszSize(targetType reflect.Type, sizeHints []sszSizeHint) (i
}

// get size from cache if not influenced by a parent sizeHint
d.typeSizeMutex.RLock()
if cachedSize := d.typeSizeCache[targetType]; cachedSize != nil && len(sizeHints) == 0 {
d.typeSizeMutex.RUnlock()
return cachedSize.size, cachedSize.specval, nil
}
d.typeSizeMutex.RUnlock()

switch targetType.Kind() {
case reflect.Struct:
Expand Down Expand Up @@ -126,10 +129,12 @@ func (d *DynSsz) getSszSize(targetType reflect.Type, sizeHints []sszSizeHint) (i
staticSize = -1
} else if len(sizeHints) == 0 {
// cache size if it's static and not influenced by a parent sizeHint
d.typeSizeMutex.Lock()
d.typeSizeCache[targetType] = &cachedSszSize{
size: staticSize,
specval: hasSpecValue,
}
d.typeSizeMutex.Unlock()
}

return staticSize, hasSpecValue, nil
Expand Down

0 comments on commit 651d1ad

Please sign in to comment.