Skip to content

Commit

Permalink
Merge pull request #1521 from orbs-network/bugfix/state-storage-updat…
Browse files Browse the repository at this point in the history
…e-memory-leak

Fix state storage memory leak
  • Loading branch information
Kirill Maksimov authored Jan 15, 2020
2 parents 0ed526e + 063aa84 commit 0525b89
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion services/statestorage/adapter/memory/memory_persistence.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func NewStatePersistence(metricFactory metric.Factory) *InMemoryStatePersistence
fullState: adapter.ChainState{},
height: 0,
ts: 0,
proposer: []byte{},
proposer: []byte{},
merkleRoot: merkleRoot,
}
}
Expand Down
11 changes: 9 additions & 2 deletions services/statestorage/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,15 +188,22 @@ func (s *service) GetStateHash(ctx context.Context, input *services.GetStateHash
func inflateChainState(csd []*protocol.ContractStateDiff) adapter.ChainState {
result := make(adapter.ChainState)
for _, stateDiffs := range csd {
contract := stateDiffs.ContractName()
// copying here is very important to free up the underlying structures
contract := primitives.ContractName(stateDiffs.ContractName().String())
contractMap, ok := result[contract]
if !ok {
contractMap = make(map[string]*protocol.StateRecord)
result[contract] = contractMap
}
for i := stateDiffs.StateDiffsIterator(); i.HasNext(); {
r := i.NextStateDiffs()
contractMap[string(r.Key())] = r

// copying here is very important to free up the underlying structures
detachedBuffer := make([]byte, len(r.Raw()))
copy(detachedBuffer, r.Raw())

diffToApply := protocol.StateRecordReader(detachedBuffer)
contractMap[string(diffToApply.Key())] = diffToApply
}
}
return result
Expand Down
30 changes: 30 additions & 0 deletions services/statestorage/service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package statestorage

import (
"github.com/orbs-network/orbs-spec/types/go/protocol"
"github.com/stretchr/testify/require"
"testing"
)

func Test_inflateChainState(t *testing.T) {
singleDiff := (&protocol.ContractStateDiffBuilder{
ContractName: "Albums",
StateDiffs: []*protocol.StateRecordBuilder{
{
Key: []byte("David Bowie"),
Value: []byte("Station to Station"),
},
},
}).Build()

diffs := []*protocol.ContractStateDiff{
singleDiff,
}

chainState := inflateChainState(diffs)
singleDiff.StateDiffsIterator().NextStateDiffs().MutateValue([]byte("Station of Station"))
singleDiff.MutateContractName("Album1")

require.NotNil(t, chainState["Albums"])
require.EqualValues(t, []byte("Station to Station"), chainState["Albums"]["David Bowie"].Value(), "the underlying buffer was not copied")
}

0 comments on commit 0525b89

Please sign in to comment.