diff --git a/pkg/core/native/native_gas.go b/pkg/core/native/native_gas.go index 761b14ccf..2903e10f9 100644 --- a/pkg/core/native/native_gas.go +++ b/pkg/core/native/native_gas.go @@ -59,7 +59,7 @@ func (g *GAS) increaseBalance(_ *interop.Context, _ util.Uint160, si *state.Stor } acc.Balance.Add(&acc.Balance, amount) if acc.Balance.Sign() != 0 { - *si = acc.Bytes() + *si = acc.Bytes(nil) } else { *si = nil } diff --git a/pkg/core/state/native_state.go b/pkg/core/state/native_state.go index 5a59d1699..605dc1691 100644 --- a/pkg/core/state/native_state.go +++ b/pkg/core/state/native_state.go @@ -7,6 +7,7 @@ import ( "math/big" "github.com/nspcc-dev/neo-go/pkg/crypto/keys" + "github.com/nspcc-dev/neo-go/pkg/encoding/bigint" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) @@ -33,8 +34,20 @@ func NEP17BalanceFromBytes(b []byte) (*NEP17Balance, error) { } // Bytes returns serialized NEP17Balance. -func (s *NEP17Balance) Bytes() []byte { - return balanceToBytes(s) +func (s *NEP17Balance) Bytes(buf []byte) []byte { + if cap(buf) < 4+bigint.MaxBytesLen { + buf = make([]byte, 4, 4+bigint.MaxBytesLen) + } else { + buf = buf[:4] + } + buf[0] = byte(stackitem.StructT) + buf[1] = 1 + buf[2] = byte(stackitem.IntegerT) + + data := bigint.ToPreallocatedBytes(&s.Balance, buf[4:]) + buf[3] = byte(len(data)) // max is 33, so we are ok here + buf = append(buf, data...) + return buf } func balanceFromBytes(b []byte, item stackitem.Convertible) error { diff --git a/pkg/core/state/native_state_test.go b/pkg/core/state/native_state_test.go new file mode 100644 index 000000000..b590f93b1 --- /dev/null +++ b/pkg/core/state/native_state_test.go @@ -0,0 +1,50 @@ +package state + +import ( + "testing" + + "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" + "github.com/stretchr/testify/require" +) + +func TestNEP17Balance_Bytes(t *testing.T) { + var b NEP17Balance + b.Balance.SetInt64(0x12345678910) + + data, err := stackitem.SerializeConvertible(&b) + require.NoError(t, err) + require.Equal(t, data, b.Bytes(nil)) + + t.Run("reuse buffer", func(t *testing.T) { + buf := make([]byte, 100) + ret := b.Bytes(buf[:0]) + require.Equal(t, ret, buf[:len(ret)]) + }) +} + +func BenchmarkNEP17BalanceBytes(b *testing.B) { + var bl NEP17Balance + bl.Balance.SetInt64(0x12345678910) + + b.Run("stackitem", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _, _ = stackitem.SerializeConvertible(&bl) + } + }) + b.Run("bytes", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = bl.Bytes(nil) + } + }) + b.Run("bytes, prealloc", func(b *testing.B) { + bs := bl.Bytes(nil) + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = bl.Bytes(bs[:0]) + } + }) +}