*: replace slice.Copy with bytes.Clone

And refactor some code a bit, don't use bytes.Clone where type-specific
helpers may be used instead.

Close #2907.

Signed-off-by: Anna Shaleva <shaleva.ann@nspcc.ru>
This commit is contained in:
Anna Shaleva 2024-03-04 21:09:36 +03:00
parent b030c331b0
commit 8162e9033d
26 changed files with 68 additions and 89 deletions

View file

@ -1,12 +1,12 @@
package wallet package wallet
import ( import (
"bytes"
"crypto/elliptic" "crypto/elliptic"
"encoding/hex" "encoding/hex"
"testing" "testing"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys" "github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -36,27 +36,27 @@ func TestParseMultisigContract(t *testing.T) {
testParseMultisigContract(t, s, 1, pub) testParseMultisigContract(t, s, 1, pub)
}) })
t.Run("bad, no check multisig", func(t *testing.T) { t.Run("bad, no check multisig", func(t *testing.T) {
sBad := slice.Copy(s) sBad := bytes.Clone(s)
sBad[len(sBad)-1] ^= 0xFF sBad[len(sBad)-1] ^= 0xFF
testParseMultisigContract(t, sBad, 0) testParseMultisigContract(t, sBad, 0)
}) })
t.Run("bad, invalid number of keys", func(t *testing.T) { t.Run("bad, invalid number of keys", func(t *testing.T) {
sBad := slice.Copy(s) sBad := bytes.Clone(s)
sBad[len(sBad)-2] = opPush1 + 1 sBad[len(sBad)-2] = opPush1 + 1
testParseMultisigContract(t, sBad, 0) testParseMultisigContract(t, sBad, 0)
}) })
t.Run("bad, invalid first instruction", func(t *testing.T) { t.Run("bad, invalid first instruction", func(t *testing.T) {
sBad := slice.Copy(s) sBad := bytes.Clone(s)
sBad[0] = 0xFF sBad[0] = 0xFF
testParseMultisigContract(t, sBad, 0) testParseMultisigContract(t, sBad, 0)
}) })
t.Run("bad, invalid public key", func(t *testing.T) { t.Run("bad, invalid public key", func(t *testing.T) {
sBad := slice.Copy(s) sBad := bytes.Clone(s)
sBad[2] = 0xFF sBad[2] = 0xFF
testParseMultisigContract(t, sBad, 0) testParseMultisigContract(t, sBad, 0)
}) })
t.Run("bad, many sigs", func(t *testing.T) { t.Run("bad, many sigs", func(t *testing.T) {
sBad := slice.Copy(s) sBad := bytes.Clone(s)
sBad[0] = opPush1 + 1 sBad[0] = opPush1 + 1
testParseMultisigContract(t, sBad, 0) testParseMultisigContract(t, sBad, 0)
}) })

View file

@ -36,7 +36,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm" "github.com/nspcc-dev/neo-go/pkg/vm"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate" "github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
@ -1172,7 +1171,7 @@ func (bc *Blockchain) resetTransfers(cache *dao.Simple, height uint32) error {
trInfo = nil trInfo = nil
removeFollowing = false removeFollowing = false
} else if removeFollowing { } else if removeFollowing {
cache.Store.Delete(slice.Copy(k)) cache.Store.Delete(bytes.Clone(k))
return seekErr == nil return seekErr == nil
} }

View file

@ -1,6 +1,7 @@
package core package core
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"strings" "strings"
@ -17,7 +18,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/opcode" "github.com/nspcc-dev/neo-go/pkg/vm/opcode"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -175,9 +175,9 @@ func TestBlockchain_InitWithIncompleteStateJump(t *testing.T) {
bPrefix := make([]byte, 1) bPrefix := make([]byte, 1)
bPrefix[0] = byte(bcSpout.dao.Version.StoragePrefix) bPrefix[0] = byte(bcSpout.dao.Version.StoragePrefix)
bcSpout.dao.Store.Seek(storage.SeekRange{Prefix: bPrefix}, func(k, v []byte) bool { bcSpout.dao.Store.Seek(storage.SeekRange{Prefix: bPrefix}, func(k, v []byte) bool {
key := slice.Copy(k) key := bytes.Clone(k)
key[0] = byte(tempPrefix) key[0] = byte(tempPrefix)
value := slice.Copy(v) value := bytes.Clone(v)
batch.Put(key, value) batch.Put(key, value)
return true return true
}) })

View file

@ -1,6 +1,7 @@
package dao package dao
import ( import (
"bytes"
"context" "context"
"encoding/binary" "encoding/binary"
"errors" "errors"
@ -19,7 +20,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
) )
@ -383,7 +383,7 @@ func (dao *Simple) DeleteStorageItem(id int32, key []byte) {
// may not be copied. Seek continues iterating until false is returned from f. A requested prefix // may not be copied. Seek continues iterating until false is returned from f. A requested prefix
// (if any non-empty) is trimmed before passing to f. // (if any non-empty) is trimmed before passing to f.
func (dao *Simple) Seek(id int32, rng storage.SeekRange, f func(k, v []byte) bool) { func (dao *Simple) Seek(id int32, rng storage.SeekRange, f func(k, v []byte) bool) {
rng.Prefix = slice.Copy(dao.makeStorageItemKey(id, rng.Prefix)) // f() can use dao too. rng.Prefix = bytes.Clone(dao.makeStorageItemKey(id, rng.Prefix)) // f() can use dao too.
dao.Store.Seek(rng, func(k, v []byte) bool { dao.Store.Seek(rng, func(k, v []byte) bool {
return f(k[len(rng.Prefix):], v) return f(k[len(rng.Prefix):], v)
}) })
@ -393,7 +393,7 @@ func (dao *Simple) Seek(id int32, rng storage.SeekRange, f func(k, v []byte) boo
// starting from the point specified) to a channel and returns the channel. // starting from the point specified) to a channel and returns the channel.
// Resulting keys and values may not be copied. // Resulting keys and values may not be copied.
func (dao *Simple) SeekAsync(ctx context.Context, id int32, rng storage.SeekRange) chan storage.KeyValue { func (dao *Simple) SeekAsync(ctx context.Context, id int32, rng storage.SeekRange) chan storage.KeyValue {
rng.Prefix = slice.Copy(dao.makeStorageItemKey(id, rng.Prefix)) rng.Prefix = bytes.Clone(dao.makeStorageItemKey(id, rng.Prefix))
return dao.Store.SeekAsync(ctx, rng, true) return dao.Store.SeekAsync(ctx, rng, true)
} }

View file

@ -1,6 +1,7 @@
package contract_test package contract_test
import ( import (
"bytes"
"math" "math"
"math/big" "math/big"
"testing" "testing"
@ -15,7 +16,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/neotest/chain" "github.com/nspcc-dev/neo-go/pkg/neotest/chain"
"github.com/nspcc-dev/neo-go/pkg/smartcontract" "github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/emit" "github.com/nspcc-dev/neo-go/pkg/vm/emit"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -136,13 +136,13 @@ func TestCreateAccount_HFAspidochelone(t *testing.T) {
emit.Int(w.BinWriter, int64(2)) emit.Int(w.BinWriter, int64(2))
emit.Syscall(w.BinWriter, interopnames.SystemContractCreateMultisigAccount) emit.Syscall(w.BinWriter, interopnames.SystemContractCreateMultisigAccount)
require.NoError(t, w.Err) require.NoError(t, w.Err)
multisigScript := slice.Copy(w.Bytes()) multisigScript := bytes.Clone(w.Bytes())
w.Reset() w.Reset()
emit.Bytes(w.BinWriter, pub.Bytes()) emit.Bytes(w.BinWriter, pub.Bytes())
emit.Syscall(w.BinWriter, interopnames.SystemContractCreateStandardAccount) emit.Syscall(w.BinWriter, interopnames.SystemContractCreateStandardAccount)
require.NoError(t, w.Err) require.NoError(t, w.Err)
standardScript := slice.Copy(w.Bytes()) standardScript := bytes.Clone(w.Bytes())
createAccTx := func(t *testing.T, script []byte) *transaction.Transaction { createAccTx := func(t *testing.T, script []byte) *transaction.Transaction {
tx := e.PrepareInvocation(t, script, []neotest.Signer{e.Committee}, bc.BlockHeight()+1) tx := e.PrepareInvocation(t, script, []neotest.Signer{e.Committee}, bc.BlockHeight()+1)

View file

@ -1,12 +1,12 @@
package storage package storage
import ( import (
"bytes"
"context" "context"
"fmt" "fmt"
"github.com/nspcc-dev/neo-go/pkg/core/interop" "github.com/nspcc-dev/neo-go/pkg/core/interop"
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
) )
@ -42,7 +42,7 @@ func NewIterator(seekCh chan storage.KeyValue, prefix []byte, opts int64) *Itera
return &Iterator{ return &Iterator{
seekCh: seekCh, seekCh: seekCh,
opts: opts, opts: opts,
prefix: slice.Copy(prefix), prefix: bytes.Clone(prefix),
} }
} }
@ -61,7 +61,7 @@ func (s *Iterator) Value() stackitem.Item {
} }
key := s.curr.Key key := s.curr.Key
if s.opts&FindRemovePrefix == 0 { if s.opts&FindRemovePrefix == 0 {
key = append(slice.Copy(s.prefix), key...) key = append(bytes.Clone(s.prefix), key...)
} }
if s.opts&FindKeysOnly != 0 { if s.opts&FindKeysOnly != 0 {
return stackitem.NewByteArray(key) return stackitem.NewByteArray(key)

View file

@ -9,7 +9,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
var ( var (
@ -230,7 +229,7 @@ func (b *Billet) traverse(curr Node, path, from []byte, process func(pathToNode
return b.traverse(r, path, from, process, ignoreStorageErr, backwards) return b.traverse(r, path, from, process, ignoreStorageErr, backwards)
} }
if len(from) == 0 { if len(from) == 0 {
bytes := slice.Copy(curr.Bytes()) bytes := bytes.Clone(curr.Bytes())
if process(fromNibbles(path), curr, bytes) { if process(fromNibbles(path), curr, bytes) {
return curr, errStop return curr, errStop
} }

View file

@ -7,7 +7,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
// GetProof returns a proof that the key belongs to t. // GetProof returns a proof that the key belongs to t.
@ -30,11 +29,11 @@ func (t *Trie) getProof(curr Node, path []byte, proofs *[][]byte) (Node, error)
switch n := curr.(type) { switch n := curr.(type) {
case *LeafNode: case *LeafNode:
if len(path) == 0 { if len(path) == 0 {
*proofs = append(*proofs, slice.Copy(n.Bytes())) *proofs = append(*proofs, bytes.Clone(n.Bytes()))
return n, nil return n, nil
} }
case *BranchNode: case *BranchNode:
*proofs = append(*proofs, slice.Copy(n.Bytes())) *proofs = append(*proofs, bytes.Clone(n.Bytes()))
i, path := splitPath(path) i, path := splitPath(path)
r, err := t.getProof(n.Children[i], path, proofs) r, err := t.getProof(n.Children[i], path, proofs)
if err != nil { if err != nil {
@ -44,7 +43,7 @@ func (t *Trie) getProof(curr Node, path []byte, proofs *[][]byte) (Node, error)
return n, nil return n, nil
case *ExtensionNode: case *ExtensionNode:
if bytes.HasPrefix(path, n.key) { if bytes.HasPrefix(path, n.key) {
*proofs = append(*proofs, slice.Copy(n.Bytes())) *proofs = append(*proofs, bytes.Clone(n.Bytes()))
r, err := t.getProof(n.next, path[len(n.key):], proofs) r, err := t.getProof(n.next, path[len(n.key):], proofs)
if err != nil { if err != nil {
return nil, err return nil, err
@ -75,5 +74,5 @@ func VerifyProof(rh util.Uint256, key []byte, proofs [][]byte) ([]byte, bool) {
if err != nil { if err != nil {
return nil, false return nil, false
} }
return slice.Copy(leaf.(*LeafNode).value), true return bytes.Clone(leaf.(*LeafNode).value), true
} }

View file

@ -9,7 +9,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
// TrieMode is the storage mode of a trie, it affects the DB scheme. // TrieMode is the storage mode of a trie, it affects the DB scheme.
@ -84,7 +83,7 @@ func (t *Trie) Get(key []byte) ([]byte, error) {
return nil, err return nil, err
} }
t.root = r t.root = r
return slice.Copy(leaf.(*LeafNode).value), nil return bytes.Clone(leaf.(*LeafNode).value), nil
} }
// getWithPath returns the current node with all hash nodes along the path replaced // getWithPath returns the current node with all hash nodes along the path replaced
@ -221,7 +220,7 @@ func (t *Trie) putIntoExtension(curr *ExtensionNode, path []byte, val Node) (Nod
t.addRef(b.Hash(), b.bytes) t.addRef(b.Hash(), b.bytes)
if lp > 0 { if lp > 0 {
e := NewExtensionNode(slice.Copy(pref), b) e := NewExtensionNode(bytes.Clone(pref), b)
t.addRef(e.Hash(), e.bytes) t.addRef(e.Hash(), e.bytes)
return e, nil return e, nil
} }
@ -617,8 +616,8 @@ func (t *Trie) Find(prefix, from []byte, max int) ([]storage.KeyValue, error) {
if leaf, ok := node.(*LeafNode); ok { if leaf, ok := node.(*LeafNode); ok {
if from == nil || !bytes.Equal(pathToNode, from) { // (*Billet).traverse includes `from` path into result if so. Need to filter out manually. if from == nil || !bytes.Equal(pathToNode, from) { // (*Billet).traverse includes `from` path into result if so. Need to filter out manually.
res = append(res, storage.KeyValue{ res = append(res, storage.KeyValue{
Key: append(slice.Copy(prefix), pathToNode...), Key: append(bytes.Clone(prefix), pathToNode...),
Value: slice.Copy(leaf.value), Value: bytes.Clone(leaf.value),
}) })
count++ count++
} }

View file

@ -7,7 +7,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
// TrieStore is an MPT-based storage implementation for storing and retrieving // TrieStore is an MPT-based storage implementation for storing and retrieving
@ -101,8 +100,8 @@ func (m *TrieStore) Seek(rng storage.SeekRange, f func(k, v []byte) bool) {
if leaf, ok := node.(*LeafNode); ok { if leaf, ok := node.(*LeafNode); ok {
// (*Billet).traverse includes `from` path into the result if so. It's OK for Seek, so shouldn't be filtered out. // (*Billet).traverse includes `from` path into the result if so. It's OK for Seek, so shouldn't be filtered out.
kv := storage.KeyValue{ kv := storage.KeyValue{
Key: append(slice.Copy(rng.Prefix), pathToNode...), // Do not cut prefix. Key: append(bytes.Clone(rng.Prefix), pathToNode...), // Do not cut prefix.
Value: slice.Copy(leaf.value), Value: bytes.Clone(leaf.value),
} }
return !f(kv.Key, kv.Value) // Should return whether to stop. return !f(kv.Key, kv.Value) // Should return whether to stop.
} }

View file

@ -1,6 +1,7 @@
package native package native
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt" "fmt"
@ -25,7 +26,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag" "github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
) )
@ -160,7 +160,7 @@ func newOracle() *Oracle {
// GetOracleResponseScript returns a script for the transaction with an oracle response. // GetOracleResponseScript returns a script for the transaction with an oracle response.
func (o *Oracle) GetOracleResponseScript() []byte { func (o *Oracle) GetOracleResponseScript() []byte {
return slice.Copy(o.oracleScript) return bytes.Clone(o.oracleScript)
} }
// OnPersist implements the Contract interface. // OnPersist implements the Contract interface.
@ -395,7 +395,7 @@ func (o *Oracle) RequestInternal(ic *interop.Context, url string, filter *string
if len(data) > maxUserDataLength { if len(data) > maxUserDataLength {
return ErrBigArgument return ErrBigArgument
} }
data = slice.Copy(data) // Serialization context will be used in PutRequestInternal again. data = bytes.Clone(data) // Serialization context will be used in PutRequestInternal again.
var filterNotif stackitem.Item var filterNotif stackitem.Item
if filter != nil { if filter != nil {

View file

@ -177,7 +177,7 @@ func (s *Std) serialize(ic *interop.Context, args []stackitem.Item) stackitem.It
panic(errors.New("too big item")) panic(errors.New("too big item"))
} }
return stackitem.NewByteArray(slice.Copy(data)) // Serialization context can be reused. return stackitem.NewByteArray(bytes.Clone(data)) // Serialization context can be reused.
} }
func (s *Std) deserialize(_ *interop.Context, args []stackitem.Item) stackitem.Item { func (s *Std) deserialize(_ *interop.Context, args []stackitem.Item) stackitem.Item {

View file

@ -1,6 +1,7 @@
package statesync package statesync
import ( import (
"bytes"
"fmt" "fmt"
"testing" "testing"
@ -8,7 +9,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/mpt" "github.com/nspcc-dev/neo-go/pkg/core/mpt"
"github.com/nspcc-dev/neo-go/pkg/core/storage" "github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest"
) )
@ -33,8 +33,8 @@ func TestModule_PR2019_discussion_r689629704(t *testing.T) {
expectedItems []storage.KeyValue expectedItems []storage.KeyValue
) )
expectedStorage.Seek(storage.SeekRange{Prefix: []byte{byte(storage.DataMPT)}}, func(k, v []byte) bool { expectedStorage.Seek(storage.SeekRange{Prefix: []byte{byte(storage.DataMPT)}}, func(k, v []byte) bool {
key := slice.Copy(k) key := bytes.Clone(k)
value := slice.Copy(v) value := bytes.Clone(v)
expectedItems = append(expectedItems, storage.KeyValue{ expectedItems = append(expectedItems, storage.KeyValue{
Key: key, Key: key,
Value: value, Value: value,
@ -97,8 +97,8 @@ func TestModule_PR2019_discussion_r689629704(t *testing.T) {
// Compare resulting storage items and refcounts. // Compare resulting storage items and refcounts.
var actualItems []storage.KeyValue var actualItems []storage.KeyValue
expectedStorage.Seek(storage.SeekRange{Prefix: []byte{byte(storage.DataMPT)}}, func(k, v []byte) bool { expectedStorage.Seek(storage.SeekRange{Prefix: []byte{byte(storage.DataMPT)}}, func(k, v []byte) bool {
key := slice.Copy(k) key := bytes.Clone(k)
value := slice.Copy(v) value := bytes.Clone(v)
actualItems = append(actualItems, storage.KeyValue{ actualItems = append(actualItems, storage.KeyValue{
Key: key, Key: key,
Value: value, Value: value,

View file

@ -1,6 +1,7 @@
package statesync_test package statesync_test
import ( import (
"bytes"
"testing" "testing"
"github.com/nspcc-dev/neo-go/internal/basicchain" "github.com/nspcc-dev/neo-go/internal/basicchain"
@ -11,7 +12,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/neotest" "github.com/nspcc-dev/neo-go/pkg/neotest"
"github.com/nspcc-dev/neo-go/pkg/neotest/chain" "github.com/nspcc-dev/neo-go/pkg/neotest/chain"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -230,7 +230,7 @@ func TestStateSyncModule_Init(t *testing.T) {
alreadyRequested[unknownHashes[0]] = struct{}{} alreadyRequested[unknownHashes[0]] = struct{}{}
var callbackCalled bool var callbackCalled bool
err := bcSpout.GetStateSyncModule().Traverse(unknownHashes[0], func(node mpt.Node, nodeBytes []byte) bool { err := bcSpout.GetStateSyncModule().Traverse(unknownHashes[0], func(node mpt.Node, nodeBytes []byte) bool {
require.NoError(t, module.AddMPTNodes([][]byte{slice.Copy(nodeBytes)})) require.NoError(t, module.AddMPTNodes([][]byte{bytes.Clone(nodeBytes)}))
callbackCalled = true callbackCalled = true
return true // add nodes one-by-one return true // add nodes one-by-one
}) })
@ -435,8 +435,8 @@ func TestStateSyncModule_RestoreBasicChain(t *testing.T) {
fetchStorage := func(ps storage.Store, storagePrefix byte) []storage.KeyValue { fetchStorage := func(ps storage.Store, storagePrefix byte) []storage.KeyValue {
var kv []storage.KeyValue var kv []storage.KeyValue
ps.Seek(storage.SeekRange{Prefix: []byte{storagePrefix}}, func(k, v []byte) bool { ps.Seek(storage.SeekRange{Prefix: []byte{storagePrefix}}, func(k, v []byte) bool {
key := slice.Copy(k) key := bytes.Clone(k)
value := slice.Copy(v) value := bytes.Clone(v)
if key[0] == byte(storage.STTempStorage) { if key[0] == byte(storage.STTempStorage) {
key[0] = byte(storage.STStorage) key[0] = byte(storage.STStorage)
} }

View file

@ -9,7 +9,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig" "github.com/nspcc-dev/neo-go/pkg/core/storage/dbconfig"
"github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"go.etcd.io/bbolt" "go.etcd.io/bbolt"
) )
@ -81,7 +80,7 @@ func (s *BoltDBStore) Get(key []byte) (val []byte, err error) {
val = b.Get(key) val = b.Get(key)
// Value from Get is only valid for the lifetime of transaction, #1482 // Value from Get is only valid for the lifetime of transaction, #1482
if val != nil { if val != nil {
val = slice.Copy(val) val = bytes.Clone(val)
} }
return nil return nil
}) })

View file

@ -6,8 +6,6 @@ import (
"sort" "sort"
"strings" "strings"
"sync" "sync"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
// MemCachedStore is a wrapper around persistent store that caches all changes // MemCachedStore is a wrapper around persistent store that caches all changes
@ -107,7 +105,7 @@ func (s *MemCachedStore) Get(key []byte) ([]byte, error) {
// Put puts new KV pair into the store. // Put puts new KV pair into the store.
func (s *MemCachedStore) Put(key, value []byte) { func (s *MemCachedStore) Put(key, value []byte) {
newKey := string(key) newKey := string(key)
vcopy := slice.Copy(value) vcopy := bytes.Clone(value)
s.lock() s.lock()
put(s.chooseMap(key), newKey, vcopy) put(s.chooseMap(key), newKey, vcopy)
s.unlock() s.unlock()
@ -259,8 +257,8 @@ func performSeek(ctx context.Context, ps Store, memRes []KeyValueExists, rng See
return false return false
} }
kvPs := KeyValue{ kvPs := KeyValue{
Key: slice.Copy(k), Key: bytes.Clone(k),
Value: slice.Copy(v), Value: bytes.Clone(v),
} }
for { for {
select { select {

View file

@ -7,7 +7,6 @@ import (
"testing" "testing"
"github.com/nspcc-dev/neo-go/internal/random" "github.com/nspcc-dev/neo-go/internal/random"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -420,7 +419,7 @@ func TestCachedSeekSorting(t *testing.T) {
} }
var foundKVs []KeyValue var foundKVs []KeyValue
ts.Seek(SeekRange{Prefix: goodPrefix}, func(k, v []byte) bool { ts.Seek(SeekRange{Prefix: goodPrefix}, func(k, v []byte) bool {
foundKVs = append(foundKVs, KeyValue{Key: slice.Copy(k), Value: slice.Copy(v)}) foundKVs = append(foundKVs, KeyValue{Key: bytes.Clone(k), Value: bytes.Clone(v)})
return true return true
}) })
assert.Equal(t, len(foundKVs), len(lowerKVs)+len(updatedKVs)) assert.Equal(t, len(foundKVs), len(lowerKVs)+len(updatedKVs))

View file

@ -7,7 +7,6 @@ import (
"sort" "sort"
"testing" "testing"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -70,8 +69,8 @@ func testStoreSeek(t *testing.T, s Store) {
actual := make([]KeyValue, 0, len(goodkvs)) actual := make([]KeyValue, 0, len(goodkvs))
s.Seek(rng, func(k, v []byte) bool { s.Seek(rng, func(k, v []byte) bool {
actual = append(actual, KeyValue{ actual = append(actual, KeyValue{
Key: slice.Copy(k), Key: bytes.Clone(k),
Value: slice.Copy(v), Value: bytes.Clone(v),
}) })
if cont == nil { if cont == nil {
return true return true

View file

@ -20,7 +20,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/io" "github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/network/payload" "github.com/nspcc-dev/neo-go/pkg/network/payload"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm" "github.com/nspcc-dev/neo-go/pkg/vm"
"github.com/nspcc-dev/neo-go/pkg/vm/opcode" "github.com/nspcc-dev/neo-go/pkg/vm/opcode"
"github.com/nspcc-dev/neo-go/pkg/wallet" "github.com/nspcc-dev/neo-go/pkg/wallet"
@ -354,8 +353,8 @@ func safeCopy(tx *transaction.Transaction) *transaction.Transaction {
cp.Scripts = make([]transaction.Witness, len(tx.Scripts)) cp.Scripts = make([]transaction.Witness, len(tx.Scripts))
for i := range cp.Scripts { for i := range cp.Scripts {
cp.Scripts[i] = transaction.Witness{ cp.Scripts[i] = transaction.Witness{
InvocationScript: slice.Copy(tx.Scripts[i].InvocationScript), InvocationScript: bytes.Clone(tx.Scripts[i].InvocationScript),
VerificationScript: slice.Copy(tx.Scripts[i].VerificationScript), VerificationScript: bytes.Clone(tx.Scripts[i].VerificationScript),
} }
} }
return &cp return &cp

View file

@ -1,6 +1,7 @@
package oracle package oracle
import ( import (
"bytes"
"errors" "errors"
"net/http" "net/http"
"sync" "sync"
@ -16,7 +17,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster" "github.com/nspcc-dev/neo-go/pkg/services/oracle/broadcaster"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/wallet" "github.com/nspcc-dev/neo-go/pkg/wallet"
"go.uber.org/zap" "go.uber.org/zap"
) )
@ -277,8 +277,8 @@ drain:
// UpdateNativeContract updates native oracle contract info for tx verification. // UpdateNativeContract updates native oracle contract info for tx verification.
func (o *Oracle) UpdateNativeContract(script, resp []byte, h util.Uint160, verifyOffset int) { func (o *Oracle) UpdateNativeContract(script, resp []byte, h util.Uint160, verifyOffset int) {
o.oracleScript = slice.Copy(script) o.oracleScript = bytes.Clone(script)
o.oracleResponse = slice.Copy(resp) o.oracleResponse = bytes.Clone(resp)
o.oracleHash = h o.oracleHash = h
o.verifyOffset = verifyOffset o.verifyOffset = verifyOffset

View file

@ -30,7 +30,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/services/oracle" "github.com/nspcc-dev/neo-go/pkg/services/oracle"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem" "github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
"github.com/nspcc-dev/neo-go/pkg/wallet" "github.com/nspcc-dev/neo-go/pkg/wallet"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -163,8 +162,8 @@ func TestOracle(t *testing.T) {
md := nativeOracleState.Manifest.ABI.GetMethod(manifest.MethodVerify, -1) md := nativeOracleState.Manifest.ABI.GetMethod(manifest.MethodVerify, -1)
require.NotNil(t, md) require.NotNil(t, md)
oracleRespScript := native.CreateOracleResponseScript(nativeOracleH) oracleRespScript := native.CreateOracleResponseScript(nativeOracleH)
orc1.UpdateNativeContract(nativeOracleState.NEF.Script, slice.Copy(oracleRespScript), nativeOracleH, md.Offset) orc1.UpdateNativeContract(nativeOracleState.NEF.Script, bytes.Clone(oracleRespScript), nativeOracleH, md.Offset)
orc2.UpdateNativeContract(nativeOracleState.NEF.Script, slice.Copy(oracleRespScript), nativeOracleH, md.Offset) orc2.UpdateNativeContract(nativeOracleState.NEF.Script, bytes.Clone(oracleRespScript), nativeOracleH, md.Offset)
cs := contracts.GetOracleContractState(t, pathToInternalContracts, validator.ScriptHash(), 0) cs := contracts.GetOracleContractState(t, pathToInternalContracts, validator.ScriptHash(), 0)
rawManifest, err := json.Marshal(cs.Manifest) rawManifest, err := json.Marshal(cs.Manifest)

View file

@ -52,7 +52,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest/standard" "github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest/standard"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger" "github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
"github.com/nspcc-dev/neo-go/pkg/vm" "github.com/nspcc-dev/neo-go/pkg/vm"
"github.com/nspcc-dev/neo-go/pkg/vm/emit" "github.com/nspcc-dev/neo-go/pkg/vm/emit"
"github.com/nspcc-dev/neo-go/pkg/vm/opcode" "github.com/nspcc-dev/neo-go/pkg/vm/opcode"
@ -1760,7 +1759,7 @@ func (s *Server) findStorageInternal(id int32, prefix []byte, start, take int, s
} }
if i < end { if i < end {
res.Results = append(res.Results, result.KeyValue{ res.Results = append(res.Results, result.KeyValue{
Key: slice.Copy(append(prefix, k...)), // Don't strip prefix, as it is done in C#. Key: bytes.Clone(append(prefix, k...)), // Don't strip prefix, as it is done in C#.
Value: v, Value: v,
}) })
i++ i++

View file

@ -22,13 +22,6 @@ func reverse(dst []byte, src []byte) {
} }
} }
// Copy copies the byte slice into new slice (make/copy).
func Copy(b []byte) []byte {
d := make([]byte, len(b))
copy(d, b)
return d
}
// Clean wipes the data in b by filling it with zeros. // Clean wipes the data in b by filling it with zeros.
func Clean(b []byte) { func Clean(b []byte) {
for i := range b { for i := range b {

View file

@ -1,6 +1,7 @@
package slice package slice
import ( import (
"bytes"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -30,7 +31,7 @@ var testCases = []struct {
func TestCopyReverse(t *testing.T) { func TestCopyReverse(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
arg := Copy(tc.arr) arg := bytes.Clone(tc.arr)
require.Equal(t, tc.arr, arg) require.Equal(t, tc.arr, arg)
have := CopyReverse(arg) have := CopyReverse(arg)
@ -52,7 +53,7 @@ func TestCopyReverse(t *testing.T) {
func TestClean(t *testing.T) { func TestClean(t *testing.T) {
for _, tc := range testCases[1:] { // Empty one will be equal. for _, tc := range testCases[1:] { // Empty one will be equal.
cp := Copy(tc.arr) cp := bytes.Clone(tc.arr)
Clean(cp) Clean(cp)
require.NotEqual(t, tc.arr, cp) require.NotEqual(t, tc.arr, cp)
} }

View file

@ -14,7 +14,6 @@ import (
"github.com/nspcc-dev/neo-go/pkg/crypto/hash" "github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/encoding/bigint" "github.com/nspcc-dev/neo-go/pkg/encoding/bigint"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/util/slice"
) )
const ( const (
@ -197,7 +196,7 @@ func convertPrimitive(item Item, typ Type) (Item, error) {
return nil, err return nil, err
} }
if typ == BufferT { if typ == BufferT {
return NewBuffer(slice.Copy(b)), nil return NewBuffer(bytes.Clone(b)), nil
} }
// ByteArray can't really be changed, so it's OK to reuse `b`. // ByteArray can't really be changed, so it's OK to reuse `b`.
return NewByteArray(b), nil return NewByteArray(b), nil
@ -687,7 +686,7 @@ func (i *ByteArray) equalsLimited(s Item, limit *int) bool {
// Dup implements the Item interface. // Dup implements the Item interface.
func (i *ByteArray) Dup() Item { func (i *ByteArray) Dup() Item {
ba := slice.Copy(*i) ba := bytes.Clone(*i)
return (*ByteArray)(&ba) return (*ByteArray)(&ba)
} }
@ -1186,7 +1185,7 @@ func (i *Buffer) Convert(typ Type) (Item, error) {
case BufferT: case BufferT:
return i, nil return i, nil
case ByteArrayT: case ByteArrayT:
return NewByteArray(slice.Copy(*i)), nil return NewByteArray(bytes.Clone(*i)), nil
case IntegerT: case IntegerT:
if len(*i) > MaxBigIntegerSizeBits/8 { if len(*i) > MaxBigIntegerSizeBits/8 {
return nil, errTooBigInteger return nil, errTooBigInteger
@ -1248,12 +1247,12 @@ func deepCopy(item Item, seen map[Item]Item, asImmutable bool) Item {
bi := new(big.Int).Set(it.Big()) bi := new(big.Int).Set(it.Big())
return (*BigInteger)(bi) return (*BigInteger)(bi)
case *ByteArray: case *ByteArray:
return NewByteArray(slice.Copy(*it)) return NewByteArray(bytes.Clone(*it))
case *Buffer: case *Buffer:
if asImmutable { if asImmutable {
return NewByteArray(slice.Copy(*it)) return NewByteArray(bytes.Clone(*it))
} }
return NewBuffer(slice.Copy(*it)) return NewBuffer(bytes.Clone(*it))
case Bool: case Bool:
return it return it
case *Pointer: case *Pointer:

View file

@ -3,7 +3,6 @@ package vm
import ( import (
"crypto/elliptic" "crypto/elliptic"
"encoding/binary" "encoding/binary"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -223,7 +222,7 @@ func (v *VM) PrintOps(out io.Writer) {
// if the parameter is a 20-byte value. // if the parameter is a 20-byte value.
u, err := util.Uint160DecodeBytesBE(parameter) u, err := util.Uint160DecodeBytesBE(parameter)
if err == nil { if err == nil {
desc = fmt.Sprintf("%x (%q, %q)", parameter, address.Uint160ToString(u), "0x"+hex.EncodeToString(slice.CopyReverse(parameter))) desc = fmt.Sprintf("%x (%q, %q)", parameter, address.Uint160ToString(u), "0x"+u.StringLE())
} else { } else {
desc = fmt.Sprintf("%x", parameter) desc = fmt.Sprintf("%x", parameter)
} }