diff --git a/cmd/devp2p/internal/ethtest/snap.go b/cmd/devp2p/internal/ethtest/snap.go index 9c1efa0e8e..67c354c527 100644 --- a/cmd/devp2p/internal/ethtest/snap.go +++ b/cmd/devp2p/internal/ethtest/snap.go @@ -800,7 +800,7 @@ func (s *Suite) snapGetAccountRange(t *utesting.T, tc *accRangeTest) error { // Reconstruct a partial trie from the response and verify it keys := make([][]byte, len(hashes)) for i, key := range hashes { - keys[i] = common.CopyBytes(key[:]) + keys[i] = bytes.Clone(key[:]) } nodes := make(trienode.ProofList, len(proof)) for i, node := range proof { diff --git a/cmd/evm/eofparse_test.go b/cmd/evm/eofparse_test.go index a9119916a5..061af86e71 100644 --- a/cmd/evm/eofparse_test.go +++ b/cmd/evm/eofparse_test.go @@ -25,7 +25,6 @@ import ( "strings" "testing" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/vm" ) @@ -62,7 +61,7 @@ func FuzzEofParsing(f *testing.F) { jt = vm.NewEOFInstructionSetForTesting() c vm.Container ) - cpy := common.CopyBytes(data) + cpy := bytes.Clone(data) if err := c.UnmarshalBinary(data, true); err == nil { c.ValidateCode(&jt, true) if have := c.MarshalBinary(); !bytes.Equal(have, data) { diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index d91d6ca5a8..1ea1c387ad 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -526,7 +526,7 @@ func ImportPreimages(db ethdb.Database, fn string) error { return err } // Accumulate the preimages and flush when enough ws gathered - preimages[crypto.Keccak256Hash(blob)] = common.CopyBytes(blob) + preimages[crypto.Keccak256Hash(blob)] = bytes.Clone(blob) if len(preimages) > 1024 { rawdb.WritePreimages(db, preimages) preimages = make(map[common.Hash][]byte) diff --git a/common/bytes.go b/common/bytes.go index d1f5c6c995..bcb40c6e59 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -37,6 +37,7 @@ func FromHex(s string) []byte { } // CopyBytes returns an exact copy of the provided bytes. +// Deprecated: use bytes.Clone instead. func CopyBytes(b []byte) (copiedBytes []byte) { if b == nil { return nil diff --git a/core/chain_makers.go b/core/chain_makers.go index 7a258dc05f..cdef199669 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -17,6 +17,7 @@ package core import ( + "bytes" "fmt" "math/big" @@ -378,7 +379,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { if config.DAOForkSupport { - b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) + b.header.Extra = bytes.Clone(params.DAOForkBlockExtra) } } } diff --git a/core/rawdb/freezer_memory.go b/core/rawdb/freezer_memory.go index 4274546de5..5fc94d62cb 100644 --- a/core/rawdb/freezer_memory.go +++ b/core/rawdb/freezer_memory.go @@ -17,12 +17,12 @@ package rawdb import ( + "bytes" "errors" "fmt" "math" "sync" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" @@ -180,7 +180,7 @@ func (b *memoryBatch) AppendRaw(kind string, number uint64, blob []byte) error { if b.next[kind] != number { return errOutOrderInsertion } - b.data[kind] = append(b.data[kind], common.CopyBytes(blob)) + b.data[kind] = append(b.data[kind], bytes.Clone(blob)) b.next[kind]++ b.size[kind] += int64(len(blob)) return nil diff --git a/core/state/snapshot/conversion.go b/core/state/snapshot/conversion.go index 4b0774f2ae..5004c410b1 100644 --- a/core/state/snapshot/conversion.go +++ b/core/state/snapshot/conversion.go @@ -17,6 +17,7 @@ package snapshot import ( + "bytes" "encoding/binary" "errors" "fmt" @@ -325,7 +326,7 @@ func generateTrieRoot(db ethdb.KeyValueWriter, scheme string, it Iterator, accou } leaf = trieKV{it.Hash(), fullData} } else { - leaf = trieKV{it.Hash(), common.CopyBytes(it.(StorageIterator).Slot())} + leaf = trieKV{it.Hash(), bytes.Clone(it.(StorageIterator).Slot())} } in <- leaf diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index 01fb55ea4c..fcdb22d5c3 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -191,10 +191,10 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [ diskMore = true break } - keys = append(keys, common.CopyBytes(key[len(prefix):])) + keys = append(keys, bytes.Clone(key[len(prefix):])) if valueConvertFn == nil { - vals = append(vals, common.CopyBytes(iter.Value())) + vals = append(vals, bytes.Clone(iter.Value())) } else { val, err := valueConvertFn(iter.Value()) if err != nil { @@ -204,7 +204,7 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [ // // Here append the original value to ensure that the number of key and // value are aligned. - vals = append(vals, common.CopyBytes(iter.Value())) + vals = append(vals, bytes.Clone(iter.Value())) log.Error("Failed to convert account state data", "err", err) } else { vals = append(vals, val) @@ -534,7 +534,7 @@ func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Has return nil } // Loop for re-generating the missing storage slots. - var origin = common.CopyBytes(storeMarker) + var origin = bytes.Clone(storeMarker) for { id := trie.StorageTrieID(stateRoot, account, storageRoot) exhausted, last, err := dl.generateRange(ctx, id, append(rawdb.SnapshotStoragePrefix, account.Bytes()...), snapStorage, origin, storageCheckRange, onStorage, nil) @@ -624,7 +624,7 @@ func generateAccounts(ctx *generatorContext, dl *diskLayer, accMarker []byte) er accMarker = nil return nil } - origin := common.CopyBytes(accMarker) + origin := bytes.Clone(accMarker) for { id := trie.StateTrieID(dl.root) exhausted, last, err := dl.generateRange(ctx, id, rawdb.SnapshotAccountPrefix, snapAccount, origin, accountCheckRange, onAccount, types.FullAccountRLP) diff --git a/core/state/snapshot/holdable_iterator.go b/core/state/snapshot/holdable_iterator.go index 1e86ff9d82..6dfc137397 100644 --- a/core/state/snapshot/holdable_iterator.go +++ b/core/state/snapshot/holdable_iterator.go @@ -17,7 +17,8 @@ package snapshot import ( - "github.com/ethereum/go-ethereum/common" + "bytes" + "github.com/ethereum/go-ethereum/ethdb" ) @@ -42,8 +43,8 @@ func (it *holdableIterator) Hold() { if it.it.Key() == nil { return // nothing to hold } - it.key = common.CopyBytes(it.it.Key()) - it.val = common.CopyBytes(it.it.Value()) + it.key = bytes.Clone(it.it.Key()) + it.val = bytes.Clone(it.it.Value()) it.atHeld = false } diff --git a/core/state/snapshot/iterator_test.go b/core/state/snapshot/iterator_test.go index 2e882f484e..6f62bc3c8b 100644 --- a/core/state/snapshot/iterator_test.go +++ b/core/state/snapshot/iterator_test.go @@ -81,7 +81,7 @@ func TestStorageIteratorBasics(t *testing.T) { for i := 0; i < 100; i++ { crand.Read(value) if rand.Intn(2) == 0 { - accStorage[randomHash()] = common.CopyBytes(value) + accStorage[randomHash()] = bytes.Clone(value) } else { accStorage[randomHash()] = nil // delete slot nilstorage += 1 diff --git a/core/state/snapshot/utils.go b/core/state/snapshot/utils.go index c35c82f67a..c8ca00fcfc 100644 --- a/core/state/snapshot/utils.go +++ b/core/state/snapshot/utils.go @@ -56,7 +56,7 @@ func checkDanglingDiskStorage(chaindb ethdb.KeyValueStore) error { // No need to look up for every slot continue } - lastKey = common.CopyBytes(accKey) + lastKey = bytes.Clone(accKey) if time.Since(lastReport) > time.Second*8 { log.Info("Iterating snap storage", "at", fmt.Sprintf("%#x", accKey), "elapsed", common.PrettyDuration(time.Since(start))) lastReport = time.Now() diff --git a/core/state/statedb.go b/core/state/statedb.go index e3f5b9e1a0..a7855b88fc 100644 --- a/core/state/statedb.go +++ b/core/state/statedb.go @@ -18,6 +18,7 @@ package state import ( + "bytes" "errors" "fmt" "maps" @@ -949,7 +950,7 @@ func (s *StateDB) fastDeleteStorage(snaps *snapshot.Tree, addrHash common.Hash, nodes.AddNode(path, trienode.NewDeleted()) }) for iter.Next() { - slot := common.CopyBytes(iter.Slot()) + slot := bytes.Clone(iter.Slot()) if err := iter.Error(); err != nil { // error might occur after Slot function return nil, nil, nil, err } @@ -991,7 +992,7 @@ func (s *StateDB) slowDeleteStorage(addr common.Address, addrHash common.Hash, r if it.Leaf() { key := common.BytesToHash(it.LeafKey()) storages[key] = nil - storageOrigins[key] = common.CopyBytes(it.LeafBlob()) + storageOrigins[key] = bytes.Clone(it.LeafBlob()) continue } if it.Hash() == (common.Hash{}) { diff --git a/core/state/sync_test.go b/core/state/sync_test.go index 5c8b5a90f7..be51315867 100644 --- a/core/state/sync_test.go +++ b/core/state/sync_test.go @@ -766,7 +766,7 @@ func copyPreimages(srcDb, dstDb ethdb.Database) { preimages := make(map[common.Hash][]byte) for it.Next() { hash := it.Key()[len(rawdb.PreimagePrefix):] - preimages[common.BytesToHash(hash)] = common.CopyBytes(it.Value()) + preimages[common.BytesToHash(hash)] = bytes.Clone(it.Value()) } rawdb.WritePreimages(dstDb, preimages) } diff --git a/core/state_transition.go b/core/state_transition.go index 0f9ee9eea5..a8d4a0f2f6 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -55,7 +55,7 @@ func (result *ExecutionResult) Return() []byte { if result.Err != nil { return nil } - return common.CopyBytes(result.ReturnData) + return bytes.Clone(result.ReturnData) } // Revert returns the concrete revert reason if the execution is aborted by `REVERT` @@ -64,7 +64,7 @@ func (result *ExecutionResult) Revert() []byte { if result.Err != vm.ErrExecutionReverted { return nil } - return common.CopyBytes(result.ReturnData) + return bytes.Clone(result.ReturnData) } // IntrinsicGas computes the 'intrinsic gas' for a message with the given data. diff --git a/core/types/block.go b/core/types/block.go index b284fb3b16..04ae5a66d2 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -18,6 +18,7 @@ package types import ( + "bytes" "crypto/sha256" "encoding/binary" "fmt" @@ -399,7 +400,7 @@ func (b *Block) ParentHash() common.Hash { return b.header.ParentHash } func (b *Block) TxHash() common.Hash { return b.header.TxHash } func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } -func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } +func (b *Block) Extra() []byte { return bytes.Clone(b.header.Extra) } func (b *Block) BaseFee() *big.Int { if b.header.BaseFee == nil { diff --git a/core/types/hashing.go b/core/types/hashing.go index 224d7a87ea..e6efa3cf04 100644 --- a/core/types/hashing.go +++ b/core/types/hashing.go @@ -98,7 +98,7 @@ func encodeForDerive(list DerivableList, i int, buf *bytes.Buffer) []byte { // It's really unfortunate that we need to perform this copy. // StackTrie holds onto the values until Hash is called, so the values // written to it must not alias. - return common.CopyBytes(buf.Bytes()) + return bytes.Clone(buf.Bytes()) } // DeriveSha creates the tree hashes of transactions, receipts, and withdrawals in a block header. diff --git a/core/types/receipt.go b/core/types/receipt.go index e52a0c6477..288c6e1f7f 100644 --- a/core/types/receipt.go +++ b/core/types/receipt.go @@ -106,7 +106,7 @@ type storedReceiptRLP struct { func NewReceipt(root []byte, failed bool, cumulativeGasUsed uint64) *Receipt { r := &Receipt{ Type: LegacyTxType, - PostState: common.CopyBytes(root), + PostState: bytes.Clone(root), CumulativeGasUsed: cumulativeGasUsed, } if failed { diff --git a/core/types/state_account.go b/core/types/state_account.go index 52ef843b35..38f652ef41 100644 --- a/core/types/state_account.go +++ b/core/types/state_account.go @@ -54,7 +54,7 @@ func (acct *StateAccount) Copy() *StateAccount { Nonce: acct.Nonce, Balance: balance, Root: acct.Root, - CodeHash: common.CopyBytes(acct.CodeHash), + CodeHash: bytes.Clone(acct.CodeHash), } } diff --git a/core/types/tx_access_list.go b/core/types/tx_access_list.go index 915de9a8ab..863ba14856 100644 --- a/core/types/tx_access_list.go +++ b/core/types/tx_access_list.go @@ -62,7 +62,7 @@ func (tx *AccessListTx) copy() TxData { cpy := &AccessListTx{ Nonce: tx.Nonce, To: copyAddressPtr(tx.To), - Data: common.CopyBytes(tx.Data), + Data: bytes.Clone(tx.Data), Gas: tx.Gas, // These are copied below. AccessList: make(AccessList, len(tx.AccessList)), diff --git a/core/types/tx_blob.go b/core/types/tx_blob.go index 9b1d53958f..2c9fae127a 100644 --- a/core/types/tx_blob.go +++ b/core/types/tx_blob.go @@ -115,7 +115,7 @@ func (tx *BlobTx) copy() TxData { cpy := &BlobTx{ Nonce: tx.Nonce, To: tx.To, - Data: common.CopyBytes(tx.Data), + Data: bytes.Clone(tx.Data), Gas: tx.Gas, // These are copied below. AccessList: make(AccessList, len(tx.AccessList)), diff --git a/core/types/tx_dynamic_fee.go b/core/types/tx_dynamic_fee.go index bba81464f8..706ef7f432 100644 --- a/core/types/tx_dynamic_fee.go +++ b/core/types/tx_dynamic_fee.go @@ -47,7 +47,7 @@ func (tx *DynamicFeeTx) copy() TxData { cpy := &DynamicFeeTx{ Nonce: tx.Nonce, To: copyAddressPtr(tx.To), - Data: common.CopyBytes(tx.Data), + Data: bytes.Clone(tx.Data), Gas: tx.Gas, // These are copied below. AccessList: make(AccessList, len(tx.AccessList)), diff --git a/core/types/tx_legacy.go b/core/types/tx_legacy.go index 49f0a98809..dcd631e402 100644 --- a/core/types/tx_legacy.go +++ b/core/types/tx_legacy.go @@ -64,7 +64,7 @@ func (tx *LegacyTx) copy() TxData { cpy := &LegacyTx{ Nonce: tx.Nonce, To: copyAddressPtr(tx.To), - Data: common.CopyBytes(tx.Data), + Data: bytes.Clone(tx.Data), Gas: tx.Gas, // These are initialized below. Value: new(big.Int), diff --git a/core/types/tx_setcode.go b/core/types/tx_setcode.go index b8e38ef1f7..6ae816e82c 100644 --- a/core/types/tx_setcode.go +++ b/core/types/tx_setcode.go @@ -142,7 +142,7 @@ func (tx *SetCodeTx) copy() TxData { cpy := &SetCodeTx{ Nonce: tx.Nonce, To: tx.To, - Data: common.CopyBytes(tx.Data), + Data: bytes.Clone(tx.Data), Gas: tx.Gas, // These are copied below. AccessList: make(AccessList, len(tx.AccessList)), diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 06849e65ad..f3634a89c0 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -17,6 +17,7 @@ package vm import ( + "bytes" "crypto/sha256" "encoding/binary" "errors" @@ -311,7 +312,7 @@ func (c *dataCopy) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas } func (c *dataCopy) Run(in []byte) ([]byte, error) { - return common.CopyBytes(in), nil + return bytes.Clone(in), nil } // bigModExp implements a native big integer exponential modular operation. diff --git a/crypto/signature_test.go b/crypto/signature_test.go index 74d683b507..22d6ca1c32 100644 --- a/crypto/signature_test.go +++ b/crypto/signature_test.go @@ -22,7 +22,6 @@ import ( "reflect" "testing" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" ) @@ -62,13 +61,13 @@ func TestVerifySignature(t *testing.T) { if VerifySignature(testpubkey, testmsg, nil) { t.Errorf("nil signature valid") } - if VerifySignature(testpubkey, testmsg, append(common.CopyBytes(sig), 1, 2, 3)) { + if VerifySignature(testpubkey, testmsg, append(bytes.Clone(sig), 1, 2, 3)) { t.Errorf("signature valid with extra bytes at the end") } if VerifySignature(testpubkey, testmsg, sig[:len(sig)-2]) { t.Errorf("signature valid even though it's incomplete") } - wrongkey := common.CopyBytes(testpubkey) + wrongkey := bytes.Clone(testpubkey) wrongkey[10]++ if VerifySignature(wrongkey, testmsg, sig) { t.Errorf("signature valid with wrong public key") @@ -99,7 +98,7 @@ func TestDecompressPubkey(t *testing.T) { if _, err := DecompressPubkey(testpubkeyc[:5]); err == nil { t.Errorf("no error for incomplete pubkey") } - if _, err := DecompressPubkey(append(common.CopyBytes(testpubkeyc), 1, 2, 3)); err == nil { + if _, err := DecompressPubkey(append(bytes.Clone(testpubkeyc), 1, 2, 3)); err == nil { t.Errorf("no error for pubkey with extra bytes at the end") } } diff --git a/eth/protocols/snap/handler.go b/eth/protocols/snap/handler.go index 924aff7ac9..3984ffa7bb 100644 --- a/eth/protocols/snap/handler.go +++ b/eth/protocols/snap/handler.go @@ -290,7 +290,7 @@ func ServiceGetAccountRangeQuery(chain *core.BlockChain, req *GetAccountRangePac last common.Hash ) for it.Next() { - hash, account := it.Hash(), common.CopyBytes(it.Account()) + hash, account := it.Hash(), bytes.Clone(it.Account()) // Track the returned interval for the Merkle proofs last = hash @@ -374,7 +374,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP abort = true break } - hash, slot := it.Hash(), common.CopyBytes(it.Slot()) + hash, slot := it.Hash(), bytes.Clone(it.Slot()) // Track the returned interval for the Merkle proofs last = hash diff --git a/eth/protocols/snap/sync.go b/eth/protocols/snap/sync.go index 9e079f540f..01898595b6 100644 --- a/eth/protocols/snap/sync.go +++ b/eth/protocols/snap/sync.go @@ -2546,7 +2546,7 @@ func (s *Syncer) OnAccounts(peer SyncPeer, id uint64, hashes []common.Hash, acco // Reconstruct a partial trie from the response and verify it keys := make([][]byte, len(hashes)) for i, key := range hashes { - keys[i] = common.CopyBytes(key[:]) + keys[i] = bytes.Clone(key[:]) } nodes := make(trienode.ProofList, len(proof)) for i, node := range proof { @@ -2792,7 +2792,7 @@ func (s *Syncer) OnStorage(peer SyncPeer, id uint64, hashes [][]common.Hash, slo // Convert the keys and proofs into an internal format keys := make([][]byte, len(hashes[i])) for j, key := range hashes[i] { - keys[j] = common.CopyBytes(key[:]) + keys[j] = bytes.Clone(key[:]) } nodes := make(trienode.ProofList, 0, len(proof)) if i == len(hashes)-1 { diff --git a/eth/protocols/snap/sync_test.go b/eth/protocols/snap/sync_test.go index d318077d99..a2cb631179 100644 --- a/eth/protocols/snap/sync_test.go +++ b/eth/protocols/snap/sync_test.go @@ -1475,7 +1475,7 @@ var ( // getCodeHash returns a pseudo-random code hash func getCodeHash(i uint64) []byte { h := codehashes[int(i)%len(codehashes)] - return common.CopyBytes(h[:]) + return bytes.Clone(h[:]) } // getCodeByHash convenience function to lookup the code from the code hash diff --git a/eth/tracers/js/goja.go b/eth/tracers/js/goja.go index 227ea57226..d5b37ee214 100644 --- a/eth/tracers/js/goja.go +++ b/eth/tracers/js/goja.go @@ -17,6 +17,7 @@ package js import ( + "bytes" "encoding/json" "errors" "fmt" @@ -397,7 +398,7 @@ func (t *jsTracer) OnEnter(depth int, typ byte, from common.Address, to common.A t.frame.typ = vm.OpCode(typ).String() t.frame.from = from t.frame.to = to - t.frame.input = common.CopyBytes(input) + t.frame.input = bytes.Clone(input) t.frame.gas = uint(gas) t.frame.value = nil if value != nil { @@ -424,7 +425,7 @@ func (t *jsTracer) OnExit(depth int, output []byte, gasUsed uint64, err error, r } t.frameResult.gasUsed = uint(gasUsed) - t.frameResult.output = common.CopyBytes(output) + t.frameResult.output = bytes.Clone(output) t.frameResult.err = err if _, err := t.exit(t.obj, t.frameResultValue); err != nil { @@ -534,7 +535,7 @@ func (t *jsTracer) setBuiltinFunctions() { vm.Interrupt(err) return nil } - code = common.CopyBytes(code) + code = bytes.Clone(code) codeHash := crypto.Keccak256(code) b := crypto.CreateAddress2(addr, common.HexToHash(salt), codeHash).Bytes() res, err := t.toBuf(vm, b) @@ -869,7 +870,7 @@ func (co *contractObj) GetValue() goja.Value { } func (co *contractObj) GetInput() goja.Value { - input := common.CopyBytes(co.scope.CallInput()) + input := bytes.Clone(co.scope.CallInput()) res, err := co.toBuf(co.vm, input) if err != nil { co.vm.Interrupt(err) diff --git a/eth/tracers/logger/logger.go b/eth/tracers/logger/logger.go index a28cecf138..bcf88a2b75 100644 --- a/eth/tracers/logger/logger.go +++ b/eth/tracers/logger/logger.go @@ -17,6 +17,7 @@ package logger import ( + "bytes" "encoding/hex" "encoding/json" "errors" @@ -348,7 +349,7 @@ func (l *StructLogger) GetResult() (json.RawMessage, error) { return nil, l.reason } failed := l.err != nil - returnData := common.CopyBytes(l.output) + returnData := bytes.Clone(l.output) // Return data when successful and revert reason when reverted, otherwise empty. if failed && !errors.Is(l.err, vm.ErrExecutionReverted) { returnData = []byte{} diff --git a/eth/tracers/native/call.go b/eth/tracers/native/call.go index c2247d1ce4..e94420244d 100644 --- a/eth/tracers/native/call.go +++ b/eth/tracers/native/call.go @@ -17,6 +17,7 @@ package native import ( + "bytes" "encoding/json" "errors" "math/big" @@ -74,7 +75,7 @@ func (f callFrame) failed() bool { } func (f *callFrame) processOutput(output []byte, err error, reverted bool) { - output = common.CopyBytes(output) + output = bytes.Clone(output) // Clear error if tx wasn't reverted. This happened // for pre-homestead contract storage OOG. if err != nil && !reverted { @@ -170,7 +171,7 @@ func (t *callTracer) OnEnter(depth int, typ byte, from common.Address, to common Type: vm.OpCode(typ), From: from, To: &toCopy, - Input: common.CopyBytes(input), + Input: bytes.Clone(input), Gas: gas, Value: value, } diff --git a/ethdb/memorydb/memorydb.go b/ethdb/memorydb/memorydb.go index a797275e92..080ffea660 100644 --- a/ethdb/memorydb/memorydb.go +++ b/ethdb/memorydb/memorydb.go @@ -18,12 +18,12 @@ package memorydb import ( + "bytes" "errors" "sort" "strings" "sync" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" ) @@ -92,7 +92,7 @@ func (db *Database) Get(key []byte) ([]byte, error) { return nil, errMemorydbClosed } if entry, ok := db.db[string(key)]; ok { - return common.CopyBytes(entry), nil + return bytes.Clone(entry), nil } return nil, errMemorydbNotFound } @@ -105,7 +105,7 @@ func (db *Database) Put(key []byte, value []byte) error { if db.db == nil { return errMemorydbClosed } - db.db[string(key)] = common.CopyBytes(value) + db.db[string(key)] = bytes.Clone(value) return nil } @@ -228,7 +228,7 @@ type batch struct { // Put inserts the given value into the batch for later committing. func (b *batch) Put(key, value []byte) error { - b.writes = append(b.writes, keyvalue{string(key), common.CopyBytes(value), false}) + b.writes = append(b.writes, keyvalue{string(key), bytes.Clone(value), false}) b.size += len(key) + len(value) return nil } diff --git a/p2p/transport.go b/p2p/transport.go index 87d3013f11..66af72ae23 100644 --- a/p2p/transport.go +++ b/p2p/transport.go @@ -26,7 +26,6 @@ import ( "sync" "time" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/bitutil" "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/p2p/rlpx" @@ -67,7 +66,7 @@ func (t *rlpxTransport) ReadMsg() (Msg, error) { // Protocol messages are dispatched to subprotocol handlers asynchronously, // but package rlpx may reuse the returned 'data' buffer on the next call // to Read. Copy the message data to avoid this being an issue. - data = common.CopyBytes(data) + data = bytes.Clone(data) msg = Msg{ ReceivedAt: time.Now(), Code: code, diff --git a/trie/iterator_test.go b/trie/iterator_test.go index 74a1aa378c..236c771aa1 100644 --- a/trie/iterator_test.go +++ b/trie/iterator_test.go @@ -140,8 +140,8 @@ func testNodeIteratorCoverage(t *testing.T, scheme string) { if it.Hash() != (common.Hash{}) { elements[it.Hash()] = iterationElement{ hash: it.Hash(), - path: common.CopyBytes(it.Path()), - blob: common.CopyBytes(it.NodeBlob()), + path: bytes.Clone(it.Path()), + blob: bytes.Clone(it.NodeBlob()), } } } @@ -618,7 +618,7 @@ func isTrieNode(scheme string, key, val []byte) (bool, []byte, common.Hash) { if !ok { return false, nil, common.Hash{} } - path = common.CopyBytes(remain) + path = bytes.Clone(remain) hash = crypto.Keccak256Hash(val) } return true, path, hash diff --git a/trie/node.go b/trie/node.go index 96f077ebbb..bab7731b70 100644 --- a/trie/node.go +++ b/trie/node.go @@ -17,6 +17,7 @@ package trie import ( + "bytes" "fmt" "io" "strings" @@ -87,7 +88,7 @@ type nodeFlag struct { func (n nodeFlag) copy() nodeFlag { return nodeFlag{ - hash: common.CopyBytes(n.hash), + hash: bytes.Clone(n.hash), dirty: n.dirty, } } @@ -150,7 +151,7 @@ func mustDecodeNodeUnsafe(hash, buf []byte) node { // scenarios with low performance requirements and hard to determine whether the // byte slice be modified or not. func decodeNode(hash, buf []byte) (node, error) { - return decodeNodeUnsafe(hash, common.CopyBytes(buf)) + return decodeNodeUnsafe(hash, bytes.Clone(buf)) } // decodeNodeUnsafe parses the RLP encoding of a trie node. The passed byte slice diff --git a/trie/proof_test.go b/trie/proof_test.go index fab3a97650..e08640a054 100644 --- a/trie/proof_test.go +++ b/trie/proof_test.go @@ -213,7 +213,7 @@ func TestRangeProofWithNonExistentProof(t *testing.T) { proof := memorydb.New() // Short circuit if the decreased key is same with the previous key - first := decreaseKey(common.CopyBytes(entries[start].k)) + first := decreaseKey(bytes.Clone(entries[start].k)) if start != 0 && bytes.Equal(first, entries[start-1].k) { continue } @@ -252,7 +252,7 @@ func TestRangeProofWithInvalidNonExistentProof(t *testing.T) { // Case 1 start, end := 100, 200 - first := decreaseKey(common.CopyBytes(entries[start].k)) + first := decreaseKey(bytes.Clone(entries[start].k)) proof := memorydb.New() if err := trie.Prove(first, proof); err != nil { @@ -299,7 +299,7 @@ func TestOneElementRangeProof(t *testing.T) { // One element with left non-existent edge proof start = 1000 - first := decreaseKey(common.CopyBytes(entries[start].k)) + first := decreaseKey(bytes.Clone(entries[start].k)) proof = memorydb.New() if err := trie.Prove(first, proof); err != nil { t.Fatalf("Failed to prove the first node %v", err) @@ -314,7 +314,7 @@ func TestOneElementRangeProof(t *testing.T) { // One element with right non-existent edge proof start = 1000 - last := increaseKey(common.CopyBytes(entries[start].k)) + last := increaseKey(bytes.Clone(entries[start].k)) proof = memorydb.New() if err := trie.Prove(entries[start].k, proof); err != nil { t.Fatalf("Failed to prove the first node %v", err) @@ -329,7 +329,7 @@ func TestOneElementRangeProof(t *testing.T) { // One element with two non-existent edge proofs start = 1000 - first, last = decreaseKey(common.CopyBytes(entries[start].k)), increaseKey(common.CopyBytes(entries[start].k)) + first, last = decreaseKey(bytes.Clone(entries[start].k)), increaseKey(bytes.Clone(entries[start].k)) proof = memorydb.New() if err := trie.Prove(first, proof); err != nil { t.Fatalf("Failed to prove the first node %v", err) @@ -560,7 +560,7 @@ func TestSameSideProofs(t *testing.T) { slices.SortFunc(entries, (*kv).cmp) pos := 1000 - first := common.CopyBytes(entries[0].k) + first := bytes.Clone(entries[0].k) proof := memorydb.New() if err := trie.Prove(first, proof); err != nil { @@ -574,8 +574,8 @@ func TestSameSideProofs(t *testing.T) { t.Fatalf("Expected error, got nil") } - first = increaseKey(common.CopyBytes(entries[pos].k)) - last := increaseKey(common.CopyBytes(entries[pos].k)) + first = increaseKey(bytes.Clone(entries[pos].k)) + last := increaseKey(bytes.Clone(entries[pos].k)) last = increaseKey(last) proof = memorydb.New() @@ -671,7 +671,7 @@ func TestEmptyRangeProof(t *testing.T) { } for _, c := range cases { proof := memorydb.New() - first := increaseKey(common.CopyBytes(entries[c.pos].k)) + first := increaseKey(bytes.Clone(entries[c.pos].k)) if err := trie.Prove(first, proof); err != nil { t.Fatalf("Failed to prove the first node %v", err) } @@ -733,7 +733,7 @@ func TestEmptyValueRangeProof(t *testing.T) { // Create a new entry with a slightly modified key mid := len(entries) / 2 - key := common.CopyBytes(entries[mid-1].k) + key := bytes.Clone(entries[mid-1].k) for n := len(key) - 1; n >= 0; n-- { if key[n] < 0xff { key[n]++ @@ -777,7 +777,7 @@ func TestAllElementsEmptyValueRangeProof(t *testing.T) { // Create a new entry with a slightly modified key mid := len(entries) / 2 - key := common.CopyBytes(entries[mid-1].k) + key := bytes.Clone(entries[mid-1].k) for n := len(key) - 1; n >= 0; n-- { if key[n] < 0xff { key[n]++ diff --git a/trie/secure_trie.go b/trie/secure_trie.go index 45d5fd63e7..b7298fda12 100644 --- a/trie/secure_trie.go +++ b/trie/secure_trie.go @@ -17,6 +17,8 @@ package trie import ( + "bytes" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" @@ -159,7 +161,7 @@ func (t *StateTrie) GetNode(path []byte) ([]byte, int, error) { func (t *StateTrie) MustUpdate(key, value []byte) { hk := t.hashKey(key) t.trie.MustUpdate(hk, value) - t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) + t.getSecKeyCache()[string(hk)] = bytes.Clone(key) } // UpdateStorage associates key with value in the trie. Subsequent calls to @@ -177,7 +179,7 @@ func (t *StateTrie) UpdateStorage(_ common.Address, key, value []byte) error { if err != nil { return err } - t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) + t.getSecKeyCache()[string(hk)] = bytes.Clone(key) return nil } diff --git a/trie/stacktrie_fuzzer_test.go b/trie/stacktrie_fuzzer_test.go index 7ff6ef0235..e37b4c1b15 100644 --- a/trie/stacktrie_fuzzer_test.go +++ b/trie/stacktrie_fuzzer_test.go @@ -109,7 +109,7 @@ func fuzz(data []byte, debugging bool) { if crypto.Keccak256Hash(blob) != hash { panic("invalid node blob") } - nodeset[string(path)] = common.CopyBytes(blob) + nodeset[string(path)] = bytes.Clone(blob) }) checked int ) diff --git a/trie/stacktrie_test.go b/trie/stacktrie_test.go index 7e342e64bf..fc1bb7f4ed 100644 --- a/trie/stacktrie_test.go +++ b/trie/stacktrie_test.go @@ -341,7 +341,7 @@ func TestStacktrieNotModifyValues(t *testing.T) { // so if the stacktrie tries to append, it won't have to realloc value := make([]byte, 1, 100) value[0] = 0x2 - want := common.CopyBytes(value) + want := bytes.Clone(value) st.Update([]byte{0x01}, value) st.Hash() if have := value; !bytes.Equal(have, want) { diff --git a/trie/sync_test.go b/trie/sync_test.go index 2ff02576d4..2a1038f034 100644 --- a/trie/sync_test.go +++ b/trie/sync_test.go @@ -836,7 +836,7 @@ func testPivotMove(t *testing.T, scheme string, tiny bool) { } } tr.Update(key, val) - states[string(key)] = common.CopyBytes(val) + states[string(key)] = bytes.Clone(val) } ) stateA := make(map[string][]byte) @@ -933,7 +933,7 @@ func testSyncAbort(t *testing.T, scheme string) { val = randBytes(32) } tr.Update(key, val) - states[string(key)] = common.CopyBytes(val) + states[string(key)] = bytes.Clone(val) } ) var ( diff --git a/trie/tracer.go b/trie/tracer.go index 90b9666f0b..55c4be892e 100644 --- a/trie/tracer.go +++ b/trie/tracer.go @@ -17,9 +17,8 @@ package trie import ( + "bytes" "maps" - - "github.com/ethereum/go-ethereum/common" ) // tracer tracks the changes of trie nodes. During the trie operations, @@ -96,7 +95,7 @@ func (t *tracer) reset() { func (t *tracer) copy() *tracer { accessList := make(map[string][]byte, len(t.accessList)) for path, blob := range t.accessList { - accessList[path] = common.CopyBytes(blob) + accessList[path] = bytes.Clone(blob) } return &tracer{ inserts: maps.Clone(t.inserts), diff --git a/trie/tracer_test.go b/trie/tracer_test.go index 852a706021..1b9e3cc60c 100644 --- a/trie/tracer_test.go +++ b/trie/tracer_test.go @@ -308,7 +308,7 @@ func forNodes(tr *Trie) map[string][]byte { if it.Leaf() { continue } - nodes[string(it.Path())] = common.CopyBytes(it.NodeBlob()) + nodes[string(it.Path())] = bytes.Clone(it.NodeBlob()) } return nodes } @@ -327,7 +327,7 @@ func forHashedNodes(tr *Trie) map[string][]byte { if it.Hash() == (common.Hash{}) { continue } - nodes[string(it.Path())] = common.CopyBytes(it.NodeBlob()) + nodes[string(it.Path())] = bytes.Clone(it.NodeBlob()) } return nodes } diff --git a/trie/trie.go b/trie/trie.go index fdb4da9be4..c3bae470fe 100644 --- a/trie/trie.go +++ b/trie/trie.go @@ -576,12 +576,12 @@ func copyNode(n node) node { case nil: return nil case valueNode: - return valueNode(common.CopyBytes(n)) + return valueNode(bytes.Clone(n)) case *shortNode: return &shortNode{ flags: n.flags.copy(), - Key: common.CopyBytes(n.Key), + Key: bytes.Clone(n.Key), Val: copyNode(n.Val), } case *fullNode: diff --git a/trie/trie_test.go b/trie/trie_test.go index 54d1b083d8..f8fd24a34f 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -136,7 +136,7 @@ func testMissingNode(t *testing.T, memonly bool, scheme string) { ) for p, n := range nodes.Nodes { if n.Hash == hash { - path = common.CopyBytes([]byte(p)) + path = bytes.Clone([]byte(p)) break } } @@ -1274,7 +1274,7 @@ func TestCommitCorrect(t *testing.T) { key := testrand.Bytes(32) val := testrand.Bytes(32) paraTrie.Update(key, val) - refTrie.Update(common.CopyBytes(key), common.CopyBytes(val)) + refTrie.Update(bytes.Clone(key), bytes.Clone(val)) } paraTrie.Hash() refTrie.Hash() diff --git a/trie/trienode/proof.go b/trie/trienode/proof.go index 01a07c05b0..e818e5266d 100644 --- a/trie/trienode/proof.go +++ b/trie/trienode/proof.go @@ -17,10 +17,10 @@ package trienode import ( + "bytes" "errors" "sync" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/rlp" @@ -53,7 +53,7 @@ func (db *ProofSet) Put(key []byte, value []byte) error { } keystr := string(key) - db.nodes[keystr] = common.CopyBytes(value) + db.nodes[keystr] = bytes.Clone(value) db.order = append(db.order, keystr) db.dataSize += len(value) diff --git a/triedb/pathdb/database_test.go b/triedb/pathdb/database_test.go index c85d7832ee..5219a87fff 100644 --- a/triedb/pathdb/database_test.go +++ b/triedb/pathdb/database_test.go @@ -697,7 +697,7 @@ func TestTailTruncateHistory(t *testing.T) { func copyAccounts(set map[common.Hash][]byte) map[common.Hash][]byte { copied := make(map[common.Hash][]byte, len(set)) for key, val := range set { - copied[key] = common.CopyBytes(val) + copied[key] = bytes.Clone(val) } return copied } @@ -708,7 +708,7 @@ func copyStorages(set map[common.Hash]map[common.Hash][]byte) map[common.Hash]ma for addrHash, subset := range set { copied[addrHash] = make(map[common.Hash][]byte, len(subset)) for key, val := range subset { - copied[addrHash][key] = common.CopyBytes(val) + copied[addrHash][key] = bytes.Clone(val) } } return copied diff --git a/triedb/pathdb/difflayer_test.go b/triedb/pathdb/difflayer_test.go index 83ed833486..6958d9f1f9 100644 --- a/triedb/pathdb/difflayer_test.go +++ b/triedb/pathdb/difflayer_test.go @@ -72,8 +72,8 @@ func benchmarkSearch(b *testing.B, depth int, total int) { ) nodes[common.Hash{}][string(path)] = node if npath == nil && depth == index { - npath = common.CopyBytes(path) - nblob = common.CopyBytes(blob) + npath = bytes.Clone(path) + nblob = bytes.Clone(blob) } } return newDiffLayer(parent, common.Hash{}, 0, 0, newNodeSet(nodes), NewStateSetWithOrigin(nil, nil, nil, nil, false)) diff --git a/triedb/pathdb/holdable_iterator.go b/triedb/pathdb/holdable_iterator.go index 1f8e6b7068..108c18d9a8 100644 --- a/triedb/pathdb/holdable_iterator.go +++ b/triedb/pathdb/holdable_iterator.go @@ -17,7 +17,8 @@ package pathdb import ( - "github.com/ethereum/go-ethereum/common" + "bytes" + "github.com/ethereum/go-ethereum/ethdb" ) @@ -42,8 +43,8 @@ func (it *holdableIterator) Hold() { if it.it.Key() == nil { return // nothing to hold } - it.key = common.CopyBytes(it.it.Key()) - it.val = common.CopyBytes(it.it.Value()) + it.key = bytes.Clone(it.it.Key()) + it.val = bytes.Clone(it.it.Value()) it.atHeld = false }