common: deprecated CopyBytes

This commit is contained in:
Felix Lange 2025-04-02 15:17:24 +02:00
parent d2176f463b
commit eab7b5b092
48 changed files with 105 additions and 95 deletions

View file

@ -800,7 +800,7 @@ func (s *Suite) snapGetAccountRange(t *utesting.T, tc *accRangeTest) error {
// Reconstruct a partial trie from the response and verify it // Reconstruct a partial trie from the response and verify it
keys := make([][]byte, len(hashes)) keys := make([][]byte, len(hashes))
for i, key := range hashes { for i, key := range hashes {
keys[i] = common.CopyBytes(key[:]) keys[i] = bytes.Clone(key[:])
} }
nodes := make(trienode.ProofList, len(proof)) nodes := make(trienode.ProofList, len(proof))
for i, node := range proof { for i, node := range proof {

View file

@ -25,7 +25,6 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
) )
@ -62,7 +61,7 @@ func FuzzEofParsing(f *testing.F) {
jt = vm.NewEOFInstructionSetForTesting() jt = vm.NewEOFInstructionSetForTesting()
c vm.Container c vm.Container
) )
cpy := common.CopyBytes(data) cpy := bytes.Clone(data)
if err := c.UnmarshalBinary(data, true); err == nil { if err := c.UnmarshalBinary(data, true); err == nil {
c.ValidateCode(&jt, true) c.ValidateCode(&jt, true)
if have := c.MarshalBinary(); !bytes.Equal(have, data) { if have := c.MarshalBinary(); !bytes.Equal(have, data) {

View file

@ -526,7 +526,7 @@ func ImportPreimages(db ethdb.Database, fn string) error {
return err return err
} }
// Accumulate the preimages and flush when enough ws gathered // 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 { if len(preimages) > 1024 {
rawdb.WritePreimages(db, preimages) rawdb.WritePreimages(db, preimages)
preimages = make(map[common.Hash][]byte) preimages = make(map[common.Hash][]byte)

View file

@ -37,6 +37,7 @@ func FromHex(s string) []byte {
} }
// CopyBytes returns an exact copy of the provided bytes. // CopyBytes returns an exact copy of the provided bytes.
// Deprecated: use bytes.Clone instead.
func CopyBytes(b []byte) (copiedBytes []byte) { func CopyBytes(b []byte) (copiedBytes []byte) {
if b == nil { if b == nil {
return nil return nil

View file

@ -17,6 +17,7 @@
package core package core
import ( import (
"bytes"
"fmt" "fmt"
"math/big" "math/big"
@ -378,7 +379,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 { if b.header.Number.Cmp(daoBlock) >= 0 && b.header.Number.Cmp(limit) < 0 {
if config.DAOForkSupport { if config.DAOForkSupport {
b.header.Extra = common.CopyBytes(params.DAOForkBlockExtra) b.header.Extra = bytes.Clone(params.DAOForkBlockExtra)
} }
} }
} }

View file

@ -17,12 +17,12 @@
package rawdb package rawdb
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"math" "math"
"sync" "sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp" "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 { if b.next[kind] != number {
return errOutOrderInsertion 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.next[kind]++
b.size[kind] += int64(len(blob)) b.size[kind] += int64(len(blob))
return nil return nil

View file

@ -17,6 +17,7 @@
package snapshot package snapshot
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"errors" "errors"
"fmt" "fmt"
@ -325,7 +326,7 @@ func generateTrieRoot(db ethdb.KeyValueWriter, scheme string, it Iterator, accou
} }
leaf = trieKV{it.Hash(), fullData} leaf = trieKV{it.Hash(), fullData}
} else { } else {
leaf = trieKV{it.Hash(), common.CopyBytes(it.(StorageIterator).Slot())} leaf = trieKV{it.Hash(), bytes.Clone(it.(StorageIterator).Slot())}
} }
in <- leaf in <- leaf

View file

@ -191,10 +191,10 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [
diskMore = true diskMore = true
break break
} }
keys = append(keys, common.CopyBytes(key[len(prefix):])) keys = append(keys, bytes.Clone(key[len(prefix):]))
if valueConvertFn == nil { if valueConvertFn == nil {
vals = append(vals, common.CopyBytes(iter.Value())) vals = append(vals, bytes.Clone(iter.Value()))
} else { } else {
val, err := valueConvertFn(iter.Value()) val, err := valueConvertFn(iter.Value())
if err != nil { 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 // Here append the original value to ensure that the number of key and
// value are aligned. // 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) log.Error("Failed to convert account state data", "err", err)
} else { } else {
vals = append(vals, val) vals = append(vals, val)
@ -534,7 +534,7 @@ func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Has
return nil return nil
} }
// Loop for re-generating the missing storage slots. // Loop for re-generating the missing storage slots.
var origin = common.CopyBytes(storeMarker) var origin = bytes.Clone(storeMarker)
for { for {
id := trie.StorageTrieID(stateRoot, account, storageRoot) id := trie.StorageTrieID(stateRoot, account, storageRoot)
exhausted, last, err := dl.generateRange(ctx, id, append(rawdb.SnapshotStoragePrefix, account.Bytes()...), snapStorage, origin, storageCheckRange, onStorage, nil) 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 accMarker = nil
return nil return nil
} }
origin := common.CopyBytes(accMarker) origin := bytes.Clone(accMarker)
for { for {
id := trie.StateTrieID(dl.root) id := trie.StateTrieID(dl.root)
exhausted, last, err := dl.generateRange(ctx, id, rawdb.SnapshotAccountPrefix, snapAccount, origin, accountCheckRange, onAccount, types.FullAccountRLP) exhausted, last, err := dl.generateRange(ctx, id, rawdb.SnapshotAccountPrefix, snapAccount, origin, accountCheckRange, onAccount, types.FullAccountRLP)

View file

@ -17,7 +17,8 @@
package snapshot package snapshot
import ( import (
"github.com/ethereum/go-ethereum/common" "bytes"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
) )
@ -42,8 +43,8 @@ func (it *holdableIterator) Hold() {
if it.it.Key() == nil { if it.it.Key() == nil {
return // nothing to hold return // nothing to hold
} }
it.key = common.CopyBytes(it.it.Key()) it.key = bytes.Clone(it.it.Key())
it.val = common.CopyBytes(it.it.Value()) it.val = bytes.Clone(it.it.Value())
it.atHeld = false it.atHeld = false
} }

View file

@ -81,7 +81,7 @@ func TestStorageIteratorBasics(t *testing.T) {
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
crand.Read(value) crand.Read(value)
if rand.Intn(2) == 0 { if rand.Intn(2) == 0 {
accStorage[randomHash()] = common.CopyBytes(value) accStorage[randomHash()] = bytes.Clone(value)
} else { } else {
accStorage[randomHash()] = nil // delete slot accStorage[randomHash()] = nil // delete slot
nilstorage += 1 nilstorage += 1

View file

@ -56,7 +56,7 @@ func checkDanglingDiskStorage(chaindb ethdb.KeyValueStore) error {
// No need to look up for every slot // No need to look up for every slot
continue continue
} }
lastKey = common.CopyBytes(accKey) lastKey = bytes.Clone(accKey)
if time.Since(lastReport) > time.Second*8 { if time.Since(lastReport) > time.Second*8 {
log.Info("Iterating snap storage", "at", fmt.Sprintf("%#x", accKey), "elapsed", common.PrettyDuration(time.Since(start))) log.Info("Iterating snap storage", "at", fmt.Sprintf("%#x", accKey), "elapsed", common.PrettyDuration(time.Since(start)))
lastReport = time.Now() lastReport = time.Now()

View file

@ -18,6 +18,7 @@
package state package state
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"maps" "maps"
@ -949,7 +950,7 @@ func (s *StateDB) fastDeleteStorage(snaps *snapshot.Tree, addrHash common.Hash,
nodes.AddNode(path, trienode.NewDeleted()) nodes.AddNode(path, trienode.NewDeleted())
}) })
for iter.Next() { 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 if err := iter.Error(); err != nil { // error might occur after Slot function
return nil, nil, nil, err return nil, nil, nil, err
} }
@ -991,7 +992,7 @@ func (s *StateDB) slowDeleteStorage(addr common.Address, addrHash common.Hash, r
if it.Leaf() { if it.Leaf() {
key := common.BytesToHash(it.LeafKey()) key := common.BytesToHash(it.LeafKey())
storages[key] = nil storages[key] = nil
storageOrigins[key] = common.CopyBytes(it.LeafBlob()) storageOrigins[key] = bytes.Clone(it.LeafBlob())
continue continue
} }
if it.Hash() == (common.Hash{}) { if it.Hash() == (common.Hash{}) {

View file

@ -766,7 +766,7 @@ func copyPreimages(srcDb, dstDb ethdb.Database) {
preimages := make(map[common.Hash][]byte) preimages := make(map[common.Hash][]byte)
for it.Next() { for it.Next() {
hash := it.Key()[len(rawdb.PreimagePrefix):] 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) rawdb.WritePreimages(dstDb, preimages)
} }

View file

@ -55,7 +55,7 @@ func (result *ExecutionResult) Return() []byte {
if result.Err != nil { if result.Err != nil {
return 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` // 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 { if result.Err != vm.ErrExecutionReverted {
return nil return nil
} }
return common.CopyBytes(result.ReturnData) return bytes.Clone(result.ReturnData)
} }
// IntrinsicGas computes the 'intrinsic gas' for a message with the given data. // IntrinsicGas computes the 'intrinsic gas' for a message with the given data.

View file

@ -18,6 +18,7 @@
package types package types
import ( import (
"bytes"
"crypto/sha256" "crypto/sha256"
"encoding/binary" "encoding/binary"
"fmt" "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) TxHash() common.Hash { return b.header.TxHash }
func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash }
func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } 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 { func (b *Block) BaseFee() *big.Int {
if b.header.BaseFee == nil { if b.header.BaseFee == nil {

View file

@ -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. // It's really unfortunate that we need to perform this copy.
// StackTrie holds onto the values until Hash is called, so the values // StackTrie holds onto the values until Hash is called, so the values
// written to it must not alias. // 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. // DeriveSha creates the tree hashes of transactions, receipts, and withdrawals in a block header.

View file

@ -106,7 +106,7 @@ type storedReceiptRLP struct {
func NewReceipt(root []byte, failed bool, cumulativeGasUsed uint64) *Receipt { func NewReceipt(root []byte, failed bool, cumulativeGasUsed uint64) *Receipt {
r := &Receipt{ r := &Receipt{
Type: LegacyTxType, Type: LegacyTxType,
PostState: common.CopyBytes(root), PostState: bytes.Clone(root),
CumulativeGasUsed: cumulativeGasUsed, CumulativeGasUsed: cumulativeGasUsed,
} }
if failed { if failed {

View file

@ -54,7 +54,7 @@ func (acct *StateAccount) Copy() *StateAccount {
Nonce: acct.Nonce, Nonce: acct.Nonce,
Balance: balance, Balance: balance,
Root: acct.Root, Root: acct.Root,
CodeHash: common.CopyBytes(acct.CodeHash), CodeHash: bytes.Clone(acct.CodeHash),
} }
} }

View file

@ -62,7 +62,7 @@ func (tx *AccessListTx) copy() TxData {
cpy := &AccessListTx{ cpy := &AccessListTx{
Nonce: tx.Nonce, Nonce: tx.Nonce,
To: copyAddressPtr(tx.To), To: copyAddressPtr(tx.To),
Data: common.CopyBytes(tx.Data), Data: bytes.Clone(tx.Data),
Gas: tx.Gas, Gas: tx.Gas,
// These are copied below. // These are copied below.
AccessList: make(AccessList, len(tx.AccessList)), AccessList: make(AccessList, len(tx.AccessList)),

View file

@ -115,7 +115,7 @@ func (tx *BlobTx) copy() TxData {
cpy := &BlobTx{ cpy := &BlobTx{
Nonce: tx.Nonce, Nonce: tx.Nonce,
To: tx.To, To: tx.To,
Data: common.CopyBytes(tx.Data), Data: bytes.Clone(tx.Data),
Gas: tx.Gas, Gas: tx.Gas,
// These are copied below. // These are copied below.
AccessList: make(AccessList, len(tx.AccessList)), AccessList: make(AccessList, len(tx.AccessList)),

View file

@ -47,7 +47,7 @@ func (tx *DynamicFeeTx) copy() TxData {
cpy := &DynamicFeeTx{ cpy := &DynamicFeeTx{
Nonce: tx.Nonce, Nonce: tx.Nonce,
To: copyAddressPtr(tx.To), To: copyAddressPtr(tx.To),
Data: common.CopyBytes(tx.Data), Data: bytes.Clone(tx.Data),
Gas: tx.Gas, Gas: tx.Gas,
// These are copied below. // These are copied below.
AccessList: make(AccessList, len(tx.AccessList)), AccessList: make(AccessList, len(tx.AccessList)),

View file

@ -64,7 +64,7 @@ func (tx *LegacyTx) copy() TxData {
cpy := &LegacyTx{ cpy := &LegacyTx{
Nonce: tx.Nonce, Nonce: tx.Nonce,
To: copyAddressPtr(tx.To), To: copyAddressPtr(tx.To),
Data: common.CopyBytes(tx.Data), Data: bytes.Clone(tx.Data),
Gas: tx.Gas, Gas: tx.Gas,
// These are initialized below. // These are initialized below.
Value: new(big.Int), Value: new(big.Int),

View file

@ -142,7 +142,7 @@ func (tx *SetCodeTx) copy() TxData {
cpy := &SetCodeTx{ cpy := &SetCodeTx{
Nonce: tx.Nonce, Nonce: tx.Nonce,
To: tx.To, To: tx.To,
Data: common.CopyBytes(tx.Data), Data: bytes.Clone(tx.Data),
Gas: tx.Gas, Gas: tx.Gas,
// These are copied below. // These are copied below.
AccessList: make(AccessList, len(tx.AccessList)), AccessList: make(AccessList, len(tx.AccessList)),

View file

@ -17,6 +17,7 @@
package vm package vm
import ( import (
"bytes"
"crypto/sha256" "crypto/sha256"
"encoding/binary" "encoding/binary"
"errors" "errors"
@ -311,7 +312,7 @@ func (c *dataCopy) RequiredGas(input []byte) uint64 {
return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
} }
func (c *dataCopy) Run(in []byte) ([]byte, error) { 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. // bigModExp implements a native big integer exponential modular operation.

View file

@ -22,7 +22,6 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
) )
@ -62,13 +61,13 @@ func TestVerifySignature(t *testing.T) {
if VerifySignature(testpubkey, testmsg, nil) { if VerifySignature(testpubkey, testmsg, nil) {
t.Errorf("nil signature valid") 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") t.Errorf("signature valid with extra bytes at the end")
} }
if VerifySignature(testpubkey, testmsg, sig[:len(sig)-2]) { if VerifySignature(testpubkey, testmsg, sig[:len(sig)-2]) {
t.Errorf("signature valid even though it's incomplete") t.Errorf("signature valid even though it's incomplete")
} }
wrongkey := common.CopyBytes(testpubkey) wrongkey := bytes.Clone(testpubkey)
wrongkey[10]++ wrongkey[10]++
if VerifySignature(wrongkey, testmsg, sig) { if VerifySignature(wrongkey, testmsg, sig) {
t.Errorf("signature valid with wrong public key") t.Errorf("signature valid with wrong public key")
@ -99,7 +98,7 @@ func TestDecompressPubkey(t *testing.T) {
if _, err := DecompressPubkey(testpubkeyc[:5]); err == nil { if _, err := DecompressPubkey(testpubkeyc[:5]); err == nil {
t.Errorf("no error for incomplete pubkey") 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") t.Errorf("no error for pubkey with extra bytes at the end")
} }
} }

View file

@ -290,7 +290,7 @@ func ServiceGetAccountRangeQuery(chain *core.BlockChain, req *GetAccountRangePac
last common.Hash last common.Hash
) )
for it.Next() { 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 // Track the returned interval for the Merkle proofs
last = hash last = hash
@ -374,7 +374,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP
abort = true abort = true
break 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 // Track the returned interval for the Merkle proofs
last = hash last = hash

View file

@ -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 // Reconstruct a partial trie from the response and verify it
keys := make([][]byte, len(hashes)) keys := make([][]byte, len(hashes))
for i, key := range hashes { for i, key := range hashes {
keys[i] = common.CopyBytes(key[:]) keys[i] = bytes.Clone(key[:])
} }
nodes := make(trienode.ProofList, len(proof)) nodes := make(trienode.ProofList, len(proof))
for i, node := range 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 // Convert the keys and proofs into an internal format
keys := make([][]byte, len(hashes[i])) keys := make([][]byte, len(hashes[i]))
for j, key := range 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)) nodes := make(trienode.ProofList, 0, len(proof))
if i == len(hashes)-1 { if i == len(hashes)-1 {

View file

@ -1475,7 +1475,7 @@ var (
// getCodeHash returns a pseudo-random code hash // getCodeHash returns a pseudo-random code hash
func getCodeHash(i uint64) []byte { func getCodeHash(i uint64) []byte {
h := codehashes[int(i)%len(codehashes)] 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 // getCodeByHash convenience function to lookup the code from the code hash

View file

@ -17,6 +17,7 @@
package js package js
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "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.typ = vm.OpCode(typ).String()
t.frame.from = from t.frame.from = from
t.frame.to = to t.frame.to = to
t.frame.input = common.CopyBytes(input) t.frame.input = bytes.Clone(input)
t.frame.gas = uint(gas) t.frame.gas = uint(gas)
t.frame.value = nil t.frame.value = nil
if 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.gasUsed = uint(gasUsed)
t.frameResult.output = common.CopyBytes(output) t.frameResult.output = bytes.Clone(output)
t.frameResult.err = err t.frameResult.err = err
if _, err := t.exit(t.obj, t.frameResultValue); err != nil { if _, err := t.exit(t.obj, t.frameResultValue); err != nil {
@ -534,7 +535,7 @@ func (t *jsTracer) setBuiltinFunctions() {
vm.Interrupt(err) vm.Interrupt(err)
return nil return nil
} }
code = common.CopyBytes(code) code = bytes.Clone(code)
codeHash := crypto.Keccak256(code) codeHash := crypto.Keccak256(code)
b := crypto.CreateAddress2(addr, common.HexToHash(salt), codeHash).Bytes() b := crypto.CreateAddress2(addr, common.HexToHash(salt), codeHash).Bytes()
res, err := t.toBuf(vm, b) res, err := t.toBuf(vm, b)
@ -869,7 +870,7 @@ func (co *contractObj) GetValue() goja.Value {
} }
func (co *contractObj) GetInput() 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) res, err := co.toBuf(co.vm, input)
if err != nil { if err != nil {
co.vm.Interrupt(err) co.vm.Interrupt(err)

View file

@ -17,6 +17,7 @@
package logger package logger
import ( import (
"bytes"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
@ -348,7 +349,7 @@ func (l *StructLogger) GetResult() (json.RawMessage, error) {
return nil, l.reason return nil, l.reason
} }
failed := l.err != nil 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. // Return data when successful and revert reason when reverted, otherwise empty.
if failed && !errors.Is(l.err, vm.ErrExecutionReverted) { if failed && !errors.Is(l.err, vm.ErrExecutionReverted) {
returnData = []byte{} returnData = []byte{}

View file

@ -17,6 +17,7 @@
package native package native
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"math/big" "math/big"
@ -74,7 +75,7 @@ func (f callFrame) failed() bool {
} }
func (f *callFrame) processOutput(output []byte, err error, reverted 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 // Clear error if tx wasn't reverted. This happened
// for pre-homestead contract storage OOG. // for pre-homestead contract storage OOG.
if err != nil && !reverted { 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), Type: vm.OpCode(typ),
From: from, From: from,
To: &toCopy, To: &toCopy,
Input: common.CopyBytes(input), Input: bytes.Clone(input),
Gas: gas, Gas: gas,
Value: value, Value: value,
} }

View file

@ -18,12 +18,12 @@
package memorydb package memorydb
import ( import (
"bytes"
"errors" "errors"
"sort" "sort"
"strings" "strings"
"sync" "sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
) )
@ -92,7 +92,7 @@ func (db *Database) Get(key []byte) ([]byte, error) {
return nil, errMemorydbClosed return nil, errMemorydbClosed
} }
if entry, ok := db.db[string(key)]; ok { if entry, ok := db.db[string(key)]; ok {
return common.CopyBytes(entry), nil return bytes.Clone(entry), nil
} }
return nil, errMemorydbNotFound return nil, errMemorydbNotFound
} }
@ -105,7 +105,7 @@ func (db *Database) Put(key []byte, value []byte) error {
if db.db == nil { if db.db == nil {
return errMemorydbClosed return errMemorydbClosed
} }
db.db[string(key)] = common.CopyBytes(value) db.db[string(key)] = bytes.Clone(value)
return nil return nil
} }
@ -228,7 +228,7 @@ type batch struct {
// Put inserts the given value into the batch for later committing. // Put inserts the given value into the batch for later committing.
func (b *batch) Put(key, value []byte) error { 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) b.size += len(key) + len(value)
return nil return nil
} }

View file

@ -26,7 +26,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/bitutil" "github.com/ethereum/go-ethereum/common/bitutil"
"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/p2p/rlpx" "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, // Protocol messages are dispatched to subprotocol handlers asynchronously,
// but package rlpx may reuse the returned 'data' buffer on the next call // 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. // to Read. Copy the message data to avoid this being an issue.
data = common.CopyBytes(data) data = bytes.Clone(data)
msg = Msg{ msg = Msg{
ReceivedAt: time.Now(), ReceivedAt: time.Now(),
Code: code, Code: code,

View file

@ -140,8 +140,8 @@ func testNodeIteratorCoverage(t *testing.T, scheme string) {
if it.Hash() != (common.Hash{}) { if it.Hash() != (common.Hash{}) {
elements[it.Hash()] = iterationElement{ elements[it.Hash()] = iterationElement{
hash: it.Hash(), hash: it.Hash(),
path: common.CopyBytes(it.Path()), path: bytes.Clone(it.Path()),
blob: common.CopyBytes(it.NodeBlob()), blob: bytes.Clone(it.NodeBlob()),
} }
} }
} }
@ -618,7 +618,7 @@ func isTrieNode(scheme string, key, val []byte) (bool, []byte, common.Hash) {
if !ok { if !ok {
return false, nil, common.Hash{} return false, nil, common.Hash{}
} }
path = common.CopyBytes(remain) path = bytes.Clone(remain)
hash = crypto.Keccak256Hash(val) hash = crypto.Keccak256Hash(val)
} }
return true, path, hash return true, path, hash

View file

@ -17,6 +17,7 @@
package trie package trie
import ( import (
"bytes"
"fmt" "fmt"
"io" "io"
"strings" "strings"
@ -87,7 +88,7 @@ type nodeFlag struct {
func (n nodeFlag) copy() nodeFlag { func (n nodeFlag) copy() nodeFlag {
return nodeFlag{ return nodeFlag{
hash: common.CopyBytes(n.hash), hash: bytes.Clone(n.hash),
dirty: n.dirty, dirty: n.dirty,
} }
} }
@ -150,7 +151,7 @@ func mustDecodeNodeUnsafe(hash, buf []byte) node {
// scenarios with low performance requirements and hard to determine whether the // scenarios with low performance requirements and hard to determine whether the
// byte slice be modified or not. // byte slice be modified or not.
func decodeNode(hash, buf []byte) (node, error) { 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 // decodeNodeUnsafe parses the RLP encoding of a trie node. The passed byte slice

View file

@ -213,7 +213,7 @@ func TestRangeProofWithNonExistentProof(t *testing.T) {
proof := memorydb.New() proof := memorydb.New()
// Short circuit if the decreased key is same with the previous key // 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) { if start != 0 && bytes.Equal(first, entries[start-1].k) {
continue continue
} }
@ -252,7 +252,7 @@ func TestRangeProofWithInvalidNonExistentProof(t *testing.T) {
// Case 1 // Case 1
start, end := 100, 200 start, end := 100, 200
first := decreaseKey(common.CopyBytes(entries[start].k)) first := decreaseKey(bytes.Clone(entries[start].k))
proof := memorydb.New() proof := memorydb.New()
if err := trie.Prove(first, proof); err != nil { 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 // One element with left non-existent edge proof
start = 1000 start = 1000
first := decreaseKey(common.CopyBytes(entries[start].k)) first := decreaseKey(bytes.Clone(entries[start].k))
proof = memorydb.New() proof = memorydb.New()
if err := trie.Prove(first, proof); err != nil { if err := trie.Prove(first, proof); err != nil {
t.Fatalf("Failed to prove the first node %v", err) 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 // One element with right non-existent edge proof
start = 1000 start = 1000
last := increaseKey(common.CopyBytes(entries[start].k)) last := increaseKey(bytes.Clone(entries[start].k))
proof = memorydb.New() proof = memorydb.New()
if err := trie.Prove(entries[start].k, proof); err != nil { if err := trie.Prove(entries[start].k, proof); err != nil {
t.Fatalf("Failed to prove the first node %v", err) 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 // One element with two non-existent edge proofs
start = 1000 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() proof = memorydb.New()
if err := trie.Prove(first, proof); err != nil { if err := trie.Prove(first, proof); err != nil {
t.Fatalf("Failed to prove the first node %v", err) t.Fatalf("Failed to prove the first node %v", err)
@ -560,7 +560,7 @@ func TestSameSideProofs(t *testing.T) {
slices.SortFunc(entries, (*kv).cmp) slices.SortFunc(entries, (*kv).cmp)
pos := 1000 pos := 1000
first := common.CopyBytes(entries[0].k) first := bytes.Clone(entries[0].k)
proof := memorydb.New() proof := memorydb.New()
if err := trie.Prove(first, proof); err != nil { if err := trie.Prove(first, proof); err != nil {
@ -574,8 +574,8 @@ func TestSameSideProofs(t *testing.T) {
t.Fatalf("Expected error, got nil") t.Fatalf("Expected error, got nil")
} }
first = increaseKey(common.CopyBytes(entries[pos].k)) first = increaseKey(bytes.Clone(entries[pos].k))
last := increaseKey(common.CopyBytes(entries[pos].k)) last := increaseKey(bytes.Clone(entries[pos].k))
last = increaseKey(last) last = increaseKey(last)
proof = memorydb.New() proof = memorydb.New()
@ -671,7 +671,7 @@ func TestEmptyRangeProof(t *testing.T) {
} }
for _, c := range cases { for _, c := range cases {
proof := memorydb.New() 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 { if err := trie.Prove(first, proof); err != nil {
t.Fatalf("Failed to prove the first node %v", err) 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 // Create a new entry with a slightly modified key
mid := len(entries) / 2 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-- { for n := len(key) - 1; n >= 0; n-- {
if key[n] < 0xff { if key[n] < 0xff {
key[n]++ key[n]++
@ -777,7 +777,7 @@ func TestAllElementsEmptyValueRangeProof(t *testing.T) {
// Create a new entry with a slightly modified key // Create a new entry with a slightly modified key
mid := len(entries) / 2 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-- { for n := len(key) - 1; n >= 0; n-- {
if key[n] < 0xff { if key[n] < 0xff {
key[n]++ key[n]++

View file

@ -17,6 +17,8 @@
package trie package trie
import ( import (
"bytes"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rlp" "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) { func (t *StateTrie) MustUpdate(key, value []byte) {
hk := t.hashKey(key) hk := t.hashKey(key)
t.trie.MustUpdate(hk, value) 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 // 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 { if err != nil {
return err return err
} }
t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) t.getSecKeyCache()[string(hk)] = bytes.Clone(key)
return nil return nil
} }

View file

@ -109,7 +109,7 @@ func fuzz(data []byte, debugging bool) {
if crypto.Keccak256Hash(blob) != hash { if crypto.Keccak256Hash(blob) != hash {
panic("invalid node blob") panic("invalid node blob")
} }
nodeset[string(path)] = common.CopyBytes(blob) nodeset[string(path)] = bytes.Clone(blob)
}) })
checked int checked int
) )

View file

@ -341,7 +341,7 @@ func TestStacktrieNotModifyValues(t *testing.T) {
// so if the stacktrie tries to append, it won't have to realloc // so if the stacktrie tries to append, it won't have to realloc
value := make([]byte, 1, 100) value := make([]byte, 1, 100)
value[0] = 0x2 value[0] = 0x2
want := common.CopyBytes(value) want := bytes.Clone(value)
st.Update([]byte{0x01}, value) st.Update([]byte{0x01}, value)
st.Hash() st.Hash()
if have := value; !bytes.Equal(have, want) { if have := value; !bytes.Equal(have, want) {

View file

@ -836,7 +836,7 @@ func testPivotMove(t *testing.T, scheme string, tiny bool) {
} }
} }
tr.Update(key, val) tr.Update(key, val)
states[string(key)] = common.CopyBytes(val) states[string(key)] = bytes.Clone(val)
} }
) )
stateA := make(map[string][]byte) stateA := make(map[string][]byte)
@ -933,7 +933,7 @@ func testSyncAbort(t *testing.T, scheme string) {
val = randBytes(32) val = randBytes(32)
} }
tr.Update(key, val) tr.Update(key, val)
states[string(key)] = common.CopyBytes(val) states[string(key)] = bytes.Clone(val)
} }
) )
var ( var (

View file

@ -17,9 +17,8 @@
package trie package trie
import ( import (
"bytes"
"maps" "maps"
"github.com/ethereum/go-ethereum/common"
) )
// tracer tracks the changes of trie nodes. During the trie operations, // tracer tracks the changes of trie nodes. During the trie operations,
@ -96,7 +95,7 @@ func (t *tracer) reset() {
func (t *tracer) copy() *tracer { func (t *tracer) copy() *tracer {
accessList := make(map[string][]byte, len(t.accessList)) accessList := make(map[string][]byte, len(t.accessList))
for path, blob := range t.accessList { for path, blob := range t.accessList {
accessList[path] = common.CopyBytes(blob) accessList[path] = bytes.Clone(blob)
} }
return &tracer{ return &tracer{
inserts: maps.Clone(t.inserts), inserts: maps.Clone(t.inserts),

View file

@ -308,7 +308,7 @@ func forNodes(tr *Trie) map[string][]byte {
if it.Leaf() { if it.Leaf() {
continue continue
} }
nodes[string(it.Path())] = common.CopyBytes(it.NodeBlob()) nodes[string(it.Path())] = bytes.Clone(it.NodeBlob())
} }
return nodes return nodes
} }
@ -327,7 +327,7 @@ func forHashedNodes(tr *Trie) map[string][]byte {
if it.Hash() == (common.Hash{}) { if it.Hash() == (common.Hash{}) {
continue continue
} }
nodes[string(it.Path())] = common.CopyBytes(it.NodeBlob()) nodes[string(it.Path())] = bytes.Clone(it.NodeBlob())
} }
return nodes return nodes
} }

View file

@ -576,12 +576,12 @@ func copyNode(n node) node {
case nil: case nil:
return nil return nil
case valueNode: case valueNode:
return valueNode(common.CopyBytes(n)) return valueNode(bytes.Clone(n))
case *shortNode: case *shortNode:
return &shortNode{ return &shortNode{
flags: n.flags.copy(), flags: n.flags.copy(),
Key: common.CopyBytes(n.Key), Key: bytes.Clone(n.Key),
Val: copyNode(n.Val), Val: copyNode(n.Val),
} }
case *fullNode: case *fullNode:

View file

@ -136,7 +136,7 @@ func testMissingNode(t *testing.T, memonly bool, scheme string) {
) )
for p, n := range nodes.Nodes { for p, n := range nodes.Nodes {
if n.Hash == hash { if n.Hash == hash {
path = common.CopyBytes([]byte(p)) path = bytes.Clone([]byte(p))
break break
} }
} }
@ -1274,7 +1274,7 @@ func TestCommitCorrect(t *testing.T) {
key := testrand.Bytes(32) key := testrand.Bytes(32)
val := testrand.Bytes(32) val := testrand.Bytes(32)
paraTrie.Update(key, val) paraTrie.Update(key, val)
refTrie.Update(common.CopyBytes(key), common.CopyBytes(val)) refTrie.Update(bytes.Clone(key), bytes.Clone(val))
} }
paraTrie.Hash() paraTrie.Hash()
refTrie.Hash() refTrie.Hash()

View file

@ -17,10 +17,10 @@
package trienode package trienode
import ( import (
"bytes"
"errors" "errors"
"sync" "sync"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -53,7 +53,7 @@ func (db *ProofSet) Put(key []byte, value []byte) error {
} }
keystr := string(key) keystr := string(key)
db.nodes[keystr] = common.CopyBytes(value) db.nodes[keystr] = bytes.Clone(value)
db.order = append(db.order, keystr) db.order = append(db.order, keystr)
db.dataSize += len(value) db.dataSize += len(value)

View file

@ -697,7 +697,7 @@ func TestTailTruncateHistory(t *testing.T) {
func copyAccounts(set map[common.Hash][]byte) map[common.Hash][]byte { func copyAccounts(set map[common.Hash][]byte) map[common.Hash][]byte {
copied := make(map[common.Hash][]byte, len(set)) copied := make(map[common.Hash][]byte, len(set))
for key, val := range set { for key, val := range set {
copied[key] = common.CopyBytes(val) copied[key] = bytes.Clone(val)
} }
return copied 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 { for addrHash, subset := range set {
copied[addrHash] = make(map[common.Hash][]byte, len(subset)) copied[addrHash] = make(map[common.Hash][]byte, len(subset))
for key, val := range subset { for key, val := range subset {
copied[addrHash][key] = common.CopyBytes(val) copied[addrHash][key] = bytes.Clone(val)
} }
} }
return copied return copied

View file

@ -72,8 +72,8 @@ func benchmarkSearch(b *testing.B, depth int, total int) {
) )
nodes[common.Hash{}][string(path)] = node nodes[common.Hash{}][string(path)] = node
if npath == nil && depth == index { if npath == nil && depth == index {
npath = common.CopyBytes(path) npath = bytes.Clone(path)
nblob = common.CopyBytes(blob) nblob = bytes.Clone(blob)
} }
} }
return newDiffLayer(parent, common.Hash{}, 0, 0, newNodeSet(nodes), NewStateSetWithOrigin(nil, nil, nil, nil, false)) return newDiffLayer(parent, common.Hash{}, 0, 0, newNodeSet(nodes), NewStateSetWithOrigin(nil, nil, nil, nil, false))

View file

@ -17,7 +17,8 @@
package pathdb package pathdb
import ( import (
"github.com/ethereum/go-ethereum/common" "bytes"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
) )
@ -42,8 +43,8 @@ func (it *holdableIterator) Hold() {
if it.it.Key() == nil { if it.it.Key() == nil {
return // nothing to hold return // nothing to hold
} }
it.key = common.CopyBytes(it.it.Key()) it.key = bytes.Clone(it.it.Key())
it.val = common.CopyBytes(it.it.Value()) it.val = bytes.Clone(it.it.Value())
it.atHeld = false it.atHeld = false
} }