From f506aa1c27708079a990565e4aa0b28eeddaff52 Mon Sep 17 00:00:00 2001 From: cuiweixie Date: Wed, 7 Jan 2026 15:35:28 +0800 Subject: [PATCH] gofmt -w -r 'interface {} -> any' . --- accounts/abi/abi.go | 8 +- accounts/abi/abi_test.go | 18 ++-- accounts/abi/abifuzzer_test.go | 4 +- accounts/abi/abigen/bind.go | 2 +- accounts/abi/abigen/bindv2.go | 2 +- accounts/abi/bind/old.go | 2 +- accounts/abi/bind/v2/base_test.go | 20 ++-- accounts/abi/error.go | 2 +- accounts/abi/error_handling.go | 2 +- accounts/abi/event_test.go | 30 +++--- accounts/abi/packing_test.go | 2 +- accounts/abi/reflect.go | 2 +- accounts/abi/reflect_test.go | 2 +- accounts/abi/selector_parser.go | 12 +-- accounts/abi/selector_parser_test.go | 2 +- accounts/abi/topics.go | 14 +-- accounts/abi/topics_test.go | 96 +++++++++---------- accounts/abi/type_test.go | 2 +- accounts/abi/unpack.go | 10 +- accounts/abi/unpack_test.go | 54 +++++------ accounts/keystore/key.go | 12 +-- accounts/keystore/passphrase.go | 6 +- accounts/usbwallet/ledger.go | 8 +- beacon/engine/errors.go | 2 +- beacon/light/test_helpers.go | 2 +- build/ci.go | 2 +- cmd/abidump/main.go | 2 +- cmd/clef/main.go | 4 +- cmd/devp2p/enrcmd.go | 2 +- cmd/devp2p/internal/v5test/framework.go | 8 +- cmd/devp2p/main.go | 2 +- cmd/devp2p/nodesetcmd.go | 2 +- cmd/ethkey/utils.go | 2 +- cmd/evm/internal/t8ntool/transition.go | 8 +- cmd/evm/internal/t8ntool/utils.go | 2 +- cmd/evm/t8n_test.go | 2 +- cmd/rlpdump/main.go | 10 +- cmd/utils/cmd.go | 2 +- common/compiler/helpers.go | 22 ++--- common/compiler/solidity.go | 8 +- common/debug.go | 2 +- common/hexutil/hexutil_test.go | 4 +- common/hexutil/json.go | 6 +- common/mclock/simclock.go | 4 +- common/prque/lazyqueue_test.go | 6 +- common/test_utils.go | 2 +- common/types.go | 8 +- common/types_test.go | 4 +- consensus/clique/clique.go | 2 +- consensus/ethash/consensus.go | 2 +- console/bridge.go | 8 +- core/blockchain.go | 8 +- core/blockchain_insert.go | 14 +-- core/headerchain.go | 6 +- core/rawdb/chain_freezer.go | 4 +- core/rawdb/freezer_batch.go | 4 +- core/rawdb/freezer_memory.go | 2 +- core/state/snapshot/context.go | 12 +-- core/state/snapshot/conversion.go | 12 +-- core/state/snapshot/generate.go | 2 +- core/state/statedb_test.go | 2 +- core/txpool/legacypool/list.go | 8 +- core/types/block.go | 2 +- core/types/block_test.go | 8 +- core/types/hashing.go | 8 +- core/types/rlp_fuzzer_test.go | 10 +- core/types/transaction_test.go | 4 +- core/types/types_test.go | 2 +- core/vm/program/program_test.go | 2 +- core/vm/stack.go | 2 +- crypto/crypto.go | 2 +- eth/api_debug.go | 12 +-- eth/backend.go | 2 +- eth/catalyst/api.go | 6 +- eth/downloader/api.go | 22 ++--- eth/downloader/queue.go | 8 +- eth/downloader/skeleton.go | 2 +- eth/ethconfig/gen_config.go | 4 +- eth/fetcher/tx_fetcher_test.go | 60 ++++++------ eth/filters/api.go | 14 +-- eth/handler_eth.go | 2 +- eth/handler_eth_test.go | 2 +- eth/handler_snap.go | 2 +- eth/protocols/eth/dispatcher.go | 12 +-- eth/protocols/eth/handler.go | 8 +- eth/protocols/eth/handler_test.go | 4 +- eth/protocols/eth/handlers.go | 6 +- eth/protocols/eth/handshake_test.go | 4 +- eth/protocols/eth/protocol_test.go | 2 +- eth/protocols/snap/handler.go | 6 +- eth/protocols/snap/handler_fuzzing_test.go | 10 +- eth/tracers/api.go | 8 +- .../internal/tracetest/flat_calltrace_test.go | 2 +- .../internal/tracetest/prestate_test.go | 2 +- eth/tracers/internal/tracetest/supply_test.go | 2 +- ethclient/ethclient.go | 12 +-- ethclient/gethclient/gethclient.go | 4 +- ethclient/types_test.go | 10 +- ethdb/database.go | 2 +- ethdb/leveldb/leveldb.go | 2 +- ethdb/pebble/pebble.go | 6 +- ethstats/ethstats.go | 36 +++---- event/event.go | 6 +- event/event_test.go | 2 +- event/feed.go | 16 ++-- graphql/graphql.go | 2 +- graphql/graphql_test.go | 4 +- graphql/service.go | 6 +- interfaces.go | 2 +- internal/build/util.go | 6 +- internal/cmdtest/test_cmd.go | 8 +- internal/debug/flags.go | 2 +- internal/debug/loudpanic.go | 2 +- internal/ethapi/api.go | 40 ++++---- internal/ethapi/api_test.go | 10 +- internal/ethapi/errors.go | 10 +- internal/jsre/jsre.go | 10 +- internal/jsre/pretty.go | 2 +- internal/testlog/testlog.go | 20 ++-- internal/utesting/utesting.go | 12 +-- log/logger.go | 32 +++---- log/root.go | 14 +-- metrics/exp/exp.go | 2 +- metrics/influxdb/influxdb.go | 20 ++-- metrics/influxdb/influxdbv1.go | 2 +- metrics/influxdb/influxdbv2.go | 2 +- metrics/log.go | 4 +- metrics/opentsdb.go | 2 +- metrics/prometheus/collector.go | 6 +- metrics/prometheus/collector_test.go | 2 +- metrics/prometheus/prometheus.go | 2 +- metrics/registry.go | 58 +++++------ metrics/registry_test.go | 26 ++--- metrics/syslog.go | 2 +- metrics/writer.go | 4 +- miner/ordering.go | 4 +- node/jwt_handler.go | 4 +- node/rpcstack.go | 2 +- node/rpcstack_test.go | 4 +- p2p/config_toml.go | 4 +- p2p/discover/table_test.go | 2 +- p2p/discover/v4_udp_test.go | 2 +- p2p/discover/v4wire/v4wire_test.go | 2 +- p2p/discover/v5_udp.go | 2 +- p2p/discover/v5_udp_test.go | 2 +- p2p/discover/v5wire/msg.go | 18 ++-- p2p/dnsdisc/client.go | 4 +- p2p/enode/node_test.go | 2 +- p2p/enr/enr.go | 4 +- p2p/enr/entries.go | 4 +- p2p/message.go | 8 +- p2p/netutil/net.go | 4 +- p2p/peer.go | 6 +- p2p/peer_error.go | 2 +- p2p/protocol.go | 4 +- p2p/rlpx/rlpx.go | 4 +- p2p/server.go | 8 +- p2p/transport_test.go | 2 +- p2p/util.go | 10 +- rlp/decode.go | 8 +- rlp/decode_test.go | 30 +++--- rlp/encbuffer.go | 4 +- rlp/encode.go | 6 +- rlp/encode_test.go | 24 ++--- rlp/rlpgen/main.go | 2 +- rpc/client.go | 22 ++--- rpc/client_test.go | 16 ++-- rpc/errors.go | 4 +- rpc/http.go | 12 +-- rpc/json.go | 32 +++---- rpc/server.go | 2 +- rpc/service.go | 4 +- rpc/subscription.go | 4 +- rpc/subscription_test.go | 8 +- rpc/testservice_test.go | 14 +-- rpc/types.go | 14 +-- rpc/websocket.go | 4 +- rpc/websocket_test.go | 12 +-- signer/core/api.go | 4 +- .../apitypes/signed_data_internal_test.go | 12 +-- signer/core/apitypes/types.go | 44 ++++----- signer/core/auditlog.go | 2 +- signer/core/signed_data.go | 8 +- signer/core/signed_data_test.go | 8 +- signer/core/stdioui.go | 4 +- signer/fourbyte/abi.go | 2 +- signer/fourbyte/abi_test.go | 12 +-- signer/rules/rules.go | 2 +- tests/init_test.go | 12 +-- tests/rlp_test_util.go | 16 ++-- tests/state_test_util.go | 2 +- trie/hasher.go | 2 +- trie/iterator.go | 10 +- trie/node_test.go | 4 +- triedb/pathdb/config.go | 4 +- triedb/pathdb/context.go | 12 +-- triedb/pathdb/generate.go | 2 +- triedb/pathdb/verifier.go | 12 +-- 198 files changed, 836 insertions(+), 836 deletions(-) diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index f75278c8b1..dc9cbec830 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -60,7 +60,7 @@ func JSON(reader io.Reader) (ABI, error) { // of 4 bytes and arguments are all 32 bytes. // Method ids are created from the first 4 bytes of the hash of the // methods string signature. (signature = baz(uint32,string32)) -func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { +func (abi ABI) Pack(name string, args ...any) ([]byte, error) { // Fetch the ABI of the requested method if name == "" { // constructor @@ -105,7 +105,7 @@ func (abi ABI) getArguments(name string, data []byte) (Arguments, error) { } // Unpack unpacks the output according to the abi specification. -func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) { +func (abi ABI) Unpack(name string, data []byte) ([]any, error) { args, err := abi.getArguments(name, data) if err != nil { return nil, err @@ -116,7 +116,7 @@ func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) { // UnpackIntoInterface unpacks the output in v according to the abi specification. // It performs an additional copy. Please only use, if you want to unpack into a // structure that does not strictly conform to the abi structure (e.g. has additional arguments) -func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error { +func (abi ABI) UnpackIntoInterface(v any, name string, data []byte) error { args, err := abi.getArguments(name, data) if err != nil { return err @@ -129,7 +129,7 @@ func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) erro } // UnpackIntoMap unpacks a log into the provided map[string]interface{}. -func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) { +func (abi ABI) UnpackIntoMap(v map[string]any, name string, data []byte) (err error) { args, err := abi.getArguments(name, data) if err != nil { return err diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index db9a4c55a5..44d63959e0 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -839,8 +839,8 @@ func TestUnpackEventIntoMap(t *testing.T) { t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) } - receivedMap := map[string]interface{}{} - expectedReceivedMap := map[string]interface{}{ + receivedMap := map[string]any{} + expectedReceivedMap := map[string]any{ "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), "memo": []byte{88}, @@ -861,7 +861,7 @@ func TestUnpackEventIntoMap(t *testing.T) { t.Error("unpacked `received` map does not match expected map") } - receivedAddrMap := map[string]interface{}{} + receivedAddrMap := map[string]any{} if err = abi.UnpackIntoMap(receivedAddrMap, "receivedAddr", data); err != nil { t.Error(err) } @@ -890,7 +890,7 @@ func TestUnpackMethodIntoMap(t *testing.T) { } // Tests a method with no outputs - receiveMap := map[string]interface{}{} + receiveMap := map[string]any{} if err = abi.UnpackIntoMap(receiveMap, "receive", data); err != nil { t.Error(err) } @@ -899,7 +899,7 @@ func TestUnpackMethodIntoMap(t *testing.T) { } // Tests a method with only outputs - sendMap := map[string]interface{}{} + sendMap := map[string]any{} if err = abi.UnpackIntoMap(sendMap, "send", data); err != nil { t.Error(err) } @@ -911,7 +911,7 @@ func TestUnpackMethodIntoMap(t *testing.T) { } // Tests a method with outputs and inputs - getMap := map[string]interface{}{} + getMap := map[string]any{} if err = abi.UnpackIntoMap(getMap, "get", data); err != nil { t.Error(err) } @@ -940,7 +940,7 @@ func TestUnpackIntoMapNamingConflict(t *testing.T) { if len(data)%32 == 0 { t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) } - getMap := map[string]interface{}{} + getMap := map[string]any{} if err = abi.UnpackIntoMap(getMap, "get", data); err == nil { t.Error("naming conflict between two methods; error expected") } @@ -959,7 +959,7 @@ func TestUnpackIntoMapNamingConflict(t *testing.T) { if len(data)%32 == 0 { t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) } - receivedMap := map[string]interface{}{} + receivedMap := map[string]any{} if err = abi.UnpackIntoMap(receivedMap, "received", data); err != nil { t.Error("naming conflict between two events; no error expected") } @@ -986,7 +986,7 @@ func TestUnpackIntoMapNamingConflict(t *testing.T) { if len(data)%32 == 0 { t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) } - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), "memo": []byte{88}, diff --git a/accounts/abi/abifuzzer_test.go b/accounts/abi/abifuzzer_test.go index dbf6ab6c54..e9188105fd 100644 --- a/accounts/abi/abifuzzer_test.go +++ b/accounts/abi/abifuzzer_test.go @@ -61,7 +61,7 @@ var ( "bytes32", "bytes"} ) -func unpackPack(abi ABI, method string, input []byte) ([]interface{}, bool) { +func unpackPack(abi ABI, method string, input []byte) ([]any, bool) { if out, err := abi.Unpack(method, input); err == nil { _, err := abi.Pack(method, out...) if err != nil { @@ -77,7 +77,7 @@ func unpackPack(abi ABI, method string, input []byte) ([]interface{}, bool) { return nil, false } -func packUnpack(abi ABI, method string, input *[]interface{}) bool { +func packUnpack(abi ABI, method string, input *[]any) bool { if packed, err := abi.Pack(method, input); err == nil { outptr := reflect.New(reflect.TypeOf(input)) err := abi.UnpackIntoInterface(outptr.Interface(), method, packed) diff --git a/accounts/abi/abigen/bind.go b/accounts/abi/abigen/bind.go index 08624b04ba..9b758642c5 100644 --- a/accounts/abi/abigen/bind.go +++ b/accounts/abi/abigen/bind.go @@ -279,7 +279,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string] } buffer := new(bytes.Buffer) - funcs := map[string]interface{}{ + funcs := map[string]any{ "bindtype": bindType, "bindtopictype": bindTopicType, "capitalise": abi.ToCamelCase, diff --git a/accounts/abi/abigen/bindv2.go b/accounts/abi/abigen/bindv2.go index ef4b769bb4..112bc09b91 100644 --- a/accounts/abi/abigen/bindv2.go +++ b/accounts/abi/abigen/bindv2.go @@ -352,7 +352,7 @@ func BindV2(types []string, abis []string, bytecodes []string, pkg string, libs } } buffer := new(bytes.Buffer) - funcs := map[string]interface{}{ + funcs := map[string]any{ "bindtype": bindType, "bindtopictype": bindTopicType, "capitalise": abi.ToCamelCase, diff --git a/accounts/abi/bind/old.go b/accounts/abi/bind/old.go index b09f5f3c7a..518ab56e27 100644 --- a/accounts/abi/bind/old.go +++ b/accounts/abi/bind/old.go @@ -226,7 +226,7 @@ func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller return bind2.NewBoundContract(address, abi, caller, transactor, filterer) } -func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { +func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...any) (common.Address, *types.Transaction, *BoundContract, error) { packed, err := abi.Pack("", params...) if err != nil { return common.Address{}, nil, nil, err diff --git a/accounts/abi/bind/v2/base_test.go b/accounts/abi/bind/v2/base_test.go index 80d0f22f2c..b8fa325ca1 100644 --- a/accounts/abi/bind/v2/base_test.go +++ b/accounts/abi/bind/v2/base_test.go @@ -199,7 +199,7 @@ func TestUnpackIndexedStringTyLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "name": hash, "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), @@ -216,7 +216,7 @@ func TestUnpackAnonymousLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - var received map[string]interface{} + var received map[string]any err := bc.UnpackLogIntoMap(received, "received", mockLog) if err == nil { t.Error("unpacking anonymous event is not supported") @@ -243,7 +243,7 @@ func TestUnpackIndexedSliceTyLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "names": hash, "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), @@ -269,7 +269,7 @@ func TestUnpackIndexedArrayTyLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "addresses": hash, "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), @@ -296,7 +296,7 @@ func TestUnpackIndexedFuncTyLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "function": functionTy, "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), @@ -319,7 +319,7 @@ func TestUnpackIndexedBytesTyLogIntoMap(t *testing.T) { parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - expectedReceivedMap := map[string]interface{}{ + expectedReceivedMap := map[string]any{ "content": hash, "sender": common.HexToAddress("0x376c47978271565f56DEB45495afa69E59c16Ab2"), "amount": big.NewInt(1), @@ -374,8 +374,8 @@ func TestTransactGasFee(t *testing.T) { assert.True(mt.suggestGasPriceCalled) } -func unpackAndCheck(t *testing.T, bc *bind.BoundContract, expected map[string]interface{}, mockLog types.Log) { - received := make(map[string]interface{}) +func unpackAndCheck(t *testing.T, bc *bind.BoundContract, expected map[string]any, mockLog types.Log) { + received := make(map[string]any) if err := bc.UnpackLogIntoMap(received, "received", mockLog); err != nil { t.Error(err) } @@ -411,7 +411,7 @@ func TestCall(t *testing.T) { name, method string opts *bind.CallOpts mc bind.ContractCaller - results *[]interface{} + results *[]any wantErr bool wantErrExact error }{{ @@ -547,7 +547,7 @@ func TestCall(t *testing.T) { codeAtBytes: []byte{0}, }, method: method, - results: &[]interface{}{0}, + results: &[]any{0}, wantErr: true, }} for _, test := range tests { diff --git a/accounts/abi/error.go b/accounts/abi/error.go index 8e50112ec5..dbd08bd772 100644 --- a/accounts/abi/error.go +++ b/accounts/abi/error.go @@ -81,7 +81,7 @@ func (e Error) String() string { return e.str } -func (e *Error) Unpack(data []byte) (interface{}, error) { +func (e *Error) Unpack(data []byte) (any, error) { if len(data) < 4 { return "", fmt.Errorf("insufficient data for unpacking: have %d, want at least 4", len(data)) } diff --git a/accounts/abi/error_handling.go b/accounts/abi/error_handling.go index 9ef96c571b..ca2ffb18b2 100644 --- a/accounts/abi/error_handling.go +++ b/accounts/abi/error_handling.go @@ -85,6 +85,6 @@ func typeCheck(t Type, value reflect.Value) error { } // typeErr returns a formatted type casting error. -func typeErr(expected, got interface{}) error { +func typeErr(expected, got any) error { return fmt.Errorf("abi: cannot use %v as type %v as argument", got, expected) } diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index c548fd8db6..9b3d30090c 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -215,8 +215,8 @@ func TestEventTupleUnpack(t *testing.T) { addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268") var testCases = []struct { data string - dest interface{} - expected interface{} + dest any + expected any jsonLog []byte error string name string @@ -229,8 +229,8 @@ func TestEventTupleUnpack(t *testing.T) { "Can unpack ERC20 Transfer event into structure", }, { transferData1, - &[]interface{}{&bigint}, - &[]interface{}{&bigintExpected}, + &[]any{&bigint}, + &[]any{&bigintExpected}, jsonEventTransfer, "", "Can unpack ERC20 Transfer event into slice", @@ -274,8 +274,8 @@ func TestEventTupleUnpack(t *testing.T) { "Can unpack Pledge event into structure", }, { pledgeData1, - &[]interface{}{&common.Address{}, &bigint, &[3]byte{}}, - &[]interface{}{ + &[]any{&common.Address{}, &bigint, &[3]byte{}}, + &[]any{ &addr, &bigintExpected2, &[3]byte{'u', 's', 'd'}}, @@ -284,8 +284,8 @@ func TestEventTupleUnpack(t *testing.T) { "Can unpack Pledge event into slice", }, { pledgeData1, - &[3]interface{}{&common.Address{}, &bigint, &[3]byte{}}, - &[3]interface{}{ + &[3]any{&common.Address{}, &bigint, &[3]byte{}}, + &[3]any{ &addr, &bigintExpected2, &[3]byte{'u', 's', 'd'}}, @@ -294,8 +294,8 @@ func TestEventTupleUnpack(t *testing.T) { "Can unpack Pledge event into an array", }, { pledgeData1, - &[]interface{}{new(int), 0, 0}, - &[]interface{}{}, + &[]any{new(int), 0, 0}, + &[]any{}, jsonEventPledge, "abi: cannot unmarshal common.Address in to int", "Can not unpack Pledge event into slice with wrong types", @@ -308,15 +308,15 @@ func TestEventTupleUnpack(t *testing.T) { "Can not unpack Pledge event into struct with wrong filed types", }, { pledgeData1, - &[]interface{}{common.Address{}, new(big.Int)}, - &[]interface{}{}, + &[]any{common.Address{}, new(big.Int)}, + &[]any{}, jsonEventPledge, "abi: insufficient number of arguments for unpack, want 3, got 2", "Can not unpack Pledge event into too short slice", }, { pledgeData1, - new(map[string]interface{}), - &[]interface{}{}, + new(map[string]any), + &[]any{}, jsonEventPledge, "abi:[2] cannot unmarshal tuple in to map[string]interface {}", "Can not unpack Pledge event into map", @@ -343,7 +343,7 @@ func TestEventTupleUnpack(t *testing.T) { } } -func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error { +func unpackTestEventData(dest any, hexData string, jsonEvent []byte, assert *assert.Assertions) error { data, err := hex.DecodeString(hexData) assert.NoError(err, "Hex data should be a correct hex-string") var e Event diff --git a/accounts/abi/packing_test.go b/accounts/abi/packing_test.go index eae3b0df20..9a56899016 100644 --- a/accounts/abi/packing_test.go +++ b/accounts/abi/packing_test.go @@ -24,7 +24,7 @@ import ( type packUnpackTest struct { def string - unpacked interface{} + unpacked any packed string } diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go index f6696ea978..fe0789a467 100644 --- a/accounts/abi/reflect.go +++ b/accounts/abi/reflect.go @@ -38,7 +38,7 @@ import ( // into: // // type TupleT struct { X *big.Int } -func ConvertType(in interface{}, proto interface{}) interface{} { +func ConvertType(in any, proto any) any { protoType := reflect.TypeOf(proto) if reflect.TypeOf(in).ConvertibleTo(protoType) { return reflect.ValueOf(in).Convert(protoType).Interface() diff --git a/accounts/abi/reflect_test.go b/accounts/abi/reflect_test.go index f5e509c52f..66d98d7af5 100644 --- a/accounts/abi/reflect_test.go +++ b/accounts/abi/reflect_test.go @@ -25,7 +25,7 @@ import ( type reflectTest struct { name string args []string - struc interface{} + struc any want map[string]string err string } diff --git a/accounts/abi/selector_parser.go b/accounts/abi/selector_parser.go index b8ddd7d656..e0f6f070bb 100644 --- a/accounts/abi/selector_parser.go +++ b/accounts/abi/selector_parser.go @@ -84,7 +84,7 @@ func parseElementaryType(unescapedSelector string) (string, string, error) { return parsedType, rest, nil } -func parseCompositeType(unescapedSelector string) ([]interface{}, string, error) { +func parseCompositeType(unescapedSelector string) ([]any, string, error) { if len(unescapedSelector) == 0 || unescapedSelector[0] != '(' { return nil, "", fmt.Errorf("expected '(', got %c", unescapedSelector[0]) } @@ -92,7 +92,7 @@ func parseCompositeType(unescapedSelector string) ([]interface{}, string, error) if err != nil { return nil, "", fmt.Errorf("failed to parse type: %v", err) } - result := []interface{}{parsedType} + result := []any{parsedType} for len(rest) > 0 && rest[0] != ')' { parsedType, rest, err = parseType(rest[1:]) if err != nil { @@ -109,7 +109,7 @@ func parseCompositeType(unescapedSelector string) ([]interface{}, string, error) return result, rest[1:], nil } -func parseType(unescapedSelector string) (interface{}, string, error) { +func parseType(unescapedSelector string) (any, string, error) { if len(unescapedSelector) == 0 { return nil, "", errors.New("empty type") } @@ -120,14 +120,14 @@ func parseType(unescapedSelector string) (interface{}, string, error) { } } -func assembleArgs(args []interface{}) ([]ArgumentMarshaling, error) { +func assembleArgs(args []any) ([]ArgumentMarshaling, error) { arguments := make([]ArgumentMarshaling, 0) for i, arg := range args { // generate dummy name to avoid unmarshal issues name := fmt.Sprintf("name%d", i) if s, ok := arg.(string); ok { arguments = append(arguments, ArgumentMarshaling{name, s, s, nil, false}) - } else if components, ok := arg.([]interface{}); ok { + } else if components, ok := arg.([]any); ok { subArgs, err := assembleArgs(components) if err != nil { return nil, fmt.Errorf("failed to assemble components: %v", err) @@ -154,7 +154,7 @@ func ParseSelector(unescapedSelector string) (SelectorMarshaling, error) { if err != nil { return SelectorMarshaling{}, fmt.Errorf("failed to parse selector '%s': %v", unescapedSelector, err) } - args := []interface{}{} + args := []any{} if len(rest) >= 2 && rest[0] == '(' && rest[1] == ')' { rest = rest[2:] } else { diff --git a/accounts/abi/selector_parser_test.go b/accounts/abi/selector_parser_test.go index 6cb0ae0e70..7b0c92f233 100644 --- a/accounts/abi/selector_parser_test.go +++ b/accounts/abi/selector_parser_test.go @@ -25,7 +25,7 @@ import ( func TestParseSelector(t *testing.T) { t.Parallel() - mkType := func(types ...interface{}) []ArgumentMarshaling { + mkType := func(types ...any) []ArgumentMarshaling { var result []ArgumentMarshaling for i, typeOrComponents := range types { name := fmt.Sprintf("name%d", i) diff --git a/accounts/abi/topics.go b/accounts/abi/topics.go index 4819334ae6..5590ef793d 100644 --- a/accounts/abi/topics.go +++ b/accounts/abi/topics.go @@ -29,7 +29,7 @@ import ( ) // MakeTopics converts a filter query argument list into a filter topic set. -func MakeTopics(query ...[]interface{}) ([][]common.Hash, error) { +func MakeTopics(query ...[]any) ([][]common.Hash, error) { topics := make([][]common.Hash, len(query)) for i, filter := range query { for _, rule := range filter { @@ -112,18 +112,18 @@ func genIntType(rule int64, size uint) []byte { } // ParseTopics converts the indexed topic fields into actual log field values. -func ParseTopics(out interface{}, fields Arguments, topics []common.Hash) error { +func ParseTopics(out any, fields Arguments, topics []common.Hash) error { return parseTopicWithSetter(fields, topics, - func(arg Argument, reconstr interface{}) { + func(arg Argument, reconstr any) { field := reflect.ValueOf(out).Elem().FieldByName(ToCamelCase(arg.Name)) field.Set(reflect.ValueOf(reconstr)) }) } // ParseTopicsIntoMap converts the indexed topic field-value pairs into map key-value pairs. -func ParseTopicsIntoMap(out map[string]interface{}, fields Arguments, topics []common.Hash) error { +func ParseTopicsIntoMap(out map[string]any, fields Arguments, topics []common.Hash) error { return parseTopicWithSetter(fields, topics, - func(arg Argument, reconstr interface{}) { + func(arg Argument, reconstr any) { out[arg.Name] = reconstr }) } @@ -133,7 +133,7 @@ func ParseTopicsIntoMap(out map[string]interface{}, fields Arguments, topics []c // // Note, dynamic types cannot be reconstructed since they get mapped to Keccak256 // hashes as the topic value! -func parseTopicWithSetter(fields Arguments, topics []common.Hash, setter func(Argument, interface{})) error { +func parseTopicWithSetter(fields Arguments, topics []common.Hash, setter func(Argument, any)) error { // Sanity check that the fields and topics match up if len(fields) != len(topics) { return errors.New("topic/field count mismatch") @@ -143,7 +143,7 @@ func parseTopicWithSetter(fields Arguments, topics []common.Hash, setter func(Ar if !arg.Indexed { return errors.New("non-indexed field in topic reconstruction") } - var reconstr interface{} + var reconstr any switch arg.Type.T { case TupleTy: return errors.New("tuple type in topic reconstruction") diff --git a/accounts/abi/topics_test.go b/accounts/abi/topics_test.go index 161867e2d9..649970fd3f 100644 --- a/accounts/abi/topics_test.go +++ b/accounts/abi/topics_test.go @@ -29,7 +29,7 @@ import ( func TestMakeTopics(t *testing.T) { t.Parallel() type args struct { - query [][]interface{} + query [][]any } tests := []struct { name string @@ -39,25 +39,25 @@ func TestMakeTopics(t *testing.T) { }{ { "support fixed byte types, right padded to 32 bytes", - args{[][]interface{}{{[5]byte{1, 2, 3, 4, 5}}}}, + args{[][]any{{[5]byte{1, 2, 3, 4, 5}}}}, [][]common.Hash{{common.Hash{1, 2, 3, 4, 5}}}, false, }, { "support common hash types in topics", - args{[][]interface{}{{common.Hash{1, 2, 3, 4, 5}}}}, + args{[][]any{{common.Hash{1, 2, 3, 4, 5}}}}, [][]common.Hash{{common.Hash{1, 2, 3, 4, 5}}}, false, }, { "support address types in topics", - args{[][]interface{}{{common.Address{1, 2, 3, 4, 5}}}}, + args{[][]any{{common.Address{1, 2, 3, 4, 5}}}}, [][]common.Hash{{common.Hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5}}}, false, }, { "support positive *big.Int types in topics", - args{[][]interface{}{ + args{[][]any{ {big.NewInt(1)}, {big.NewInt(1).Lsh(big.NewInt(2), 254)}, }}, @@ -69,7 +69,7 @@ func TestMakeTopics(t *testing.T) { }, { "support negative *big.Int types in topics", - args{[][]interface{}{ + args{[][]any{ {big.NewInt(-1)}, {big.NewInt(math.MinInt64)}, }}, @@ -81,7 +81,7 @@ func TestMakeTopics(t *testing.T) { }, { "support boolean types in topics", - args{[][]interface{}{ + args{[][]any{ {true}, {false}, }}, @@ -93,7 +93,7 @@ func TestMakeTopics(t *testing.T) { }, { "support int/uint(8/16/32/64) types in topics", - args{[][]interface{}{ + args{[][]any{ {int8(-2)}, {int16(-3)}, {int32(-4)}, @@ -125,13 +125,13 @@ func TestMakeTopics(t *testing.T) { }, { "support string types in topics", - args{[][]interface{}{{"hello world"}}}, + args{[][]any{{"hello world"}}}, [][]common.Hash{{crypto.Keccak256Hash([]byte("hello world"))}}, false, }, { "support byte slice types in topics", - args{[][]interface{}{{[]byte{1, 2, 3}}}}, + args{[][]any{{[]byte{1, 2, 3}}}}, [][]common.Hash{{crypto.Keccak256Hash([]byte{1, 2, 3})}}, false, }, @@ -155,7 +155,7 @@ func TestMakeTopics(t *testing.T) { want := [][]common.Hash{{common.HexToHash("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")}} in := big.NewInt(-1) - got, err := MakeTopics([]interface{}{in}) + got, err := MakeTopics([]any{in}) if err != nil { t.Fatalf("makeTopics() error = %v", err) } @@ -169,9 +169,9 @@ func TestMakeTopics(t *testing.T) { } type args struct { - createObj func() interface{} - resultObj func() interface{} - resultMap func() map[string]interface{} + createObj func() any + resultObj func() any + resultMap func() map[string]any fields Arguments topics []common.Hash } @@ -212,10 +212,10 @@ func setupTopicsTests() []topicTest { { name: "support fixed byte types, right padded to 32 bytes", args: args{ - createObj: func() interface{} { return &bytesStruct{} }, - resultObj: func() interface{} { return &bytesStruct{StaticBytes: [5]byte{1, 2, 3, 4, 5}} }, - resultMap: func() map[string]interface{} { - return map[string]interface{}{"staticBytes": [5]byte{1, 2, 3, 4, 5}} + createObj: func() any { return &bytesStruct{} }, + resultObj: func() any { return &bytesStruct{StaticBytes: [5]byte{1, 2, 3, 4, 5}} }, + resultMap: func() map[string]any { + return map[string]any{"staticBytes": [5]byte{1, 2, 3, 4, 5}} }, fields: Arguments{Argument{ Name: "staticBytes", @@ -231,10 +231,10 @@ func setupTopicsTests() []topicTest { { name: "int8 with negative value", args: args{ - createObj: func() interface{} { return &int8Struct{} }, - resultObj: func() interface{} { return &int8Struct{Int8Value: -1} }, - resultMap: func() map[string]interface{} { - return map[string]interface{}{"int8Value": int8(-1)} + createObj: func() any { return &int8Struct{} }, + resultObj: func() any { return &int8Struct{Int8Value: -1} }, + resultMap: func() map[string]any { + return map[string]any{"int8Value": int8(-1)} }, fields: Arguments{Argument{ Name: "int8Value", @@ -251,10 +251,10 @@ func setupTopicsTests() []topicTest { { name: "int256 with negative value", args: args{ - createObj: func() interface{} { return &int256Struct{} }, - resultObj: func() interface{} { return &int256Struct{Int256Value: big.NewInt(-1)} }, - resultMap: func() map[string]interface{} { - return map[string]interface{}{"int256Value": big.NewInt(-1)} + createObj: func() any { return &int256Struct{} }, + resultObj: func() any { return &int256Struct{Int256Value: big.NewInt(-1)} }, + resultMap: func() map[string]any { + return map[string]any{"int256Value": big.NewInt(-1)} }, fields: Arguments{Argument{ Name: "int256Value", @@ -271,10 +271,10 @@ func setupTopicsTests() []topicTest { { name: "hash type", args: args{ - createObj: func() interface{} { return &hashStruct{} }, - resultObj: func() interface{} { return &hashStruct{crypto.Keccak256Hash([]byte("stringtopic"))} }, - resultMap: func() map[string]interface{} { - return map[string]interface{}{"hashValue": crypto.Keccak256Hash([]byte("stringtopic"))} + createObj: func() any { return &hashStruct{} }, + resultObj: func() any { return &hashStruct{crypto.Keccak256Hash([]byte("stringtopic"))} }, + resultMap: func() map[string]any { + return map[string]any{"hashValue": crypto.Keccak256Hash([]byte("stringtopic"))} }, fields: Arguments{Argument{ Name: "hashValue", @@ -290,13 +290,13 @@ func setupTopicsTests() []topicTest { { name: "function type", args: args{ - createObj: func() interface{} { return &funcStruct{} }, - resultObj: func() interface{} { + createObj: func() any { return &funcStruct{} }, + resultObj: func() any { return &funcStruct{[24]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}} }, - resultMap: func() map[string]interface{} { - return map[string]interface{}{"funcValue": [24]byte{255, 255, 255, 255, 255, 255, 255, 255, + resultMap: func() map[string]any { + return map[string]any{"funcValue": [24]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}} }, fields: Arguments{Argument{ @@ -314,9 +314,9 @@ func setupTopicsTests() []topicTest { { name: "error on topic/field count mismatch", args: args{ - createObj: func() interface{} { return nil }, - resultObj: func() interface{} { return nil }, - resultMap: func() map[string]interface{} { return make(map[string]interface{}) }, + createObj: func() any { return nil }, + resultObj: func() any { return nil }, + resultMap: func() map[string]any { return make(map[string]any) }, fields: Arguments{Argument{ Name: "tupletype", Type: tupleType, @@ -329,9 +329,9 @@ func setupTopicsTests() []topicTest { { name: "error on unindexed arguments", args: args{ - createObj: func() interface{} { return &int256Struct{} }, - resultObj: func() interface{} { return &int256Struct{} }, - resultMap: func() map[string]interface{} { return make(map[string]interface{}) }, + createObj: func() any { return &int256Struct{} }, + resultObj: func() any { return &int256Struct{} }, + resultMap: func() map[string]any { return make(map[string]any) }, fields: Arguments{Argument{ Name: "int256Value", Type: int256Type, @@ -347,9 +347,9 @@ func setupTopicsTests() []topicTest { { name: "error on tuple in topic reconstruction", args: args{ - createObj: func() interface{} { return &tupleType }, - resultObj: func() interface{} { return &tupleType }, - resultMap: func() map[string]interface{} { return make(map[string]interface{}) }, + createObj: func() any { return &tupleType }, + resultObj: func() any { return &tupleType }, + resultMap: func() map[string]any { return make(map[string]any) }, fields: Arguments{Argument{ Name: "tupletype", Type: tupleType, @@ -362,10 +362,10 @@ func setupTopicsTests() []topicTest { { name: "error on improper encoded function", args: args{ - createObj: func() interface{} { return &funcStruct{} }, - resultObj: func() interface{} { return &funcStruct{} }, - resultMap: func() map[string]interface{} { - return make(map[string]interface{}) + createObj: func() any { return &funcStruct{} }, + resultObj: func() any { return &funcStruct{} }, + resultMap: func() map[string]any { + return make(map[string]any) }, fields: Arguments{Argument{ Name: "funcValue", @@ -410,7 +410,7 @@ func TestParseTopicsIntoMap(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - outMap := make(map[string]interface{}) + outMap := make(map[string]any) if err := ParseTopicsIntoMap(outMap, tt.args.fields, tt.args.topics); (err != nil) != tt.wantErr { t.Errorf("parseTopicsIntoMap() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/accounts/abi/type_test.go b/accounts/abi/type_test.go index 95922548c4..1208436180 100644 --- a/accounts/abi/type_test.go +++ b/accounts/abi/type_test.go @@ -122,7 +122,7 @@ func TestTypeCheck(t *testing.T) { for i, test := range []struct { typ string components []ArgumentMarshaling - input interface{} + input any err string }{ {"uint", nil, big.NewInt(1), "unsupported arg type: uint"}, diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index 905b5ce629..48b9d6c205 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -35,7 +35,7 @@ var ( ) // ReadInteger reads the integer based on its kind and returns the appropriate value. -func ReadInteger(typ Type, b []byte) (interface{}, error) { +func ReadInteger(typ Type, b []byte) (any, error) { ret := new(big.Int).SetBytes(b) if typ.T == UintTy { @@ -137,7 +137,7 @@ func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { } // ReadFixedBytes uses reflection to create a fixed array to be read from. -func ReadFixedBytes(t Type, word []byte) (interface{}, error) { +func ReadFixedBytes(t Type, word []byte) (any, error) { if t.T != FixedBytesTy { return nil, errors.New("abi: invalid type in call to make fixed byte array") } @@ -149,7 +149,7 @@ func ReadFixedBytes(t Type, word []byte) (interface{}, error) { } // forEachUnpack iteratively unpack elements. -func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) { +func forEachUnpack(t Type, output []byte, start, size int) (any, error) { if size < 0 { return nil, fmt.Errorf("cannot marshal input to array, size is negative (%d)", size) } @@ -189,7 +189,7 @@ func forEachUnpack(t Type, output []byte, start, size int) (interface{}, error) return refSlice.Interface(), nil } -func forTupleUnpack(t Type, output []byte) (interface{}, error) { +func forTupleUnpack(t Type, output []byte) (any, error) { retval := reflect.New(t.GetType()).Elem() virtualArgs := 0 for index, elem := range t.TupleElems { @@ -221,7 +221,7 @@ func forTupleUnpack(t Type, output []byte) (interface{}, error) { // toGoType parses the output bytes and recursively assigns the value of these bytes // into a go type with accordance with the ABI spec. -func toGoType(index int, t Type, output []byte) (interface{}, error) { +func toGoType(index int, t Type, output []byte) (any, error) { if index+32 > len(output) { return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), index+32) } diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 90713c03ca..1075fb9e3b 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -99,10 +99,10 @@ func TestUnpack(t *testing.T) { } type unpackTest struct { - def string // ABI definition JSON - enc string // evm return data - want interface{} // the expected output - err string // empty or error if expected + def string // ABI definition JSON + enc string // evm return data + want any // the expected output + err string // empty or error if expected } func (test unpackTest) checkError(err error) error { @@ -370,16 +370,16 @@ func TestMethodMultiReturn(t *testing.T) { Int *big.Int } - newInterfaceSlice := func(len int) interface{} { - slice := make([]interface{}, len) + newInterfaceSlice := func(len int) any { + slice := make([]any, len) return &slice } abi, data, expected := methodMultiReturn(require.New(t)) bigint := new(big.Int) var testCases = []struct { - dest interface{} - expected interface{} + dest any + expected any error string name string }{{ @@ -393,38 +393,38 @@ func TestMethodMultiReturn(t *testing.T) { "", "Can unpack into reversed structure", }, { - &[]interface{}{&bigint, new(string)}, - &[]interface{}{&expected.Int, &expected.String}, + &[]any{&bigint, new(string)}, + &[]any{&expected.Int, &expected.String}, "", "Can unpack into a slice", }, { - &[]interface{}{&bigint, ""}, - &[]interface{}{&expected.Int, expected.String}, + &[]any{&bigint, ""}, + &[]any{&expected.Int, expected.String}, "", "Can unpack into a slice without indirection", }, { - &[2]interface{}{&bigint, new(string)}, - &[2]interface{}{&expected.Int, &expected.String}, + &[2]any{&bigint, new(string)}, + &[2]any{&expected.Int, &expected.String}, "", "Can unpack into an array", }, { - &[2]interface{}{}, - &[2]interface{}{expected.Int, expected.String}, + &[2]any{}, + &[2]any{expected.Int, expected.String}, "", "Can unpack into interface array", }, { newInterfaceSlice(2), - &[]interface{}{expected.Int, expected.String}, + &[]any{expected.Int, expected.String}, "", "Can unpack into interface slice", }, { - &[]interface{}{new(int), new(int)}, - &[]interface{}{&expected.Int, &expected.String}, + &[]any{new(int), new(int)}, + &[]any{&expected.Int, &expected.String}, "abi: cannot unmarshal *big.Int in to int", "Can not unpack into a slice with wrong types", }, { - &[]interface{}{new(int)}, - &[]interface{}{}, + &[]any{new(int)}, + &[]any{}, "abi: insufficient number of arguments for unpack, want 2, got 1", "Can not unpack into a slice with wrong types", }} @@ -455,7 +455,7 @@ func TestMultiReturnWithArray(t *testing.T) { ret1, ret1Exp := new([3]uint64), [3]uint64{9, 9, 9} ret2, ret2Exp := new(uint64), uint64(8) - if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil { + if err := abi.UnpackIntoInterface(&[]any{ret1, ret2}, "multi", buff.Bytes()); err != nil { t.Fatal(err) } if !reflect.DeepEqual(*ret1, ret1Exp) { @@ -480,7 +480,7 @@ func TestMultiReturnWithStringArray(t *testing.T) { ret2, ret2Exp := new(common.Address), common.HexToAddress("ab1257528b3782fb40d7ed5f72e624b744dffb2f") ret3, ret3Exp := new([2]string), [2]string{"Ethereum", "Hello, Ethereum!"} ret4, ret4Exp := new(bool), false - if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2, ret3, ret4}, "multi", buff.Bytes()); err != nil { + if err := abi.UnpackIntoInterface(&[]any{ret1, ret2, ret3, ret4}, "multi", buff.Bytes()); err != nil { t.Fatal(err) } if !reflect.DeepEqual(*ret1, ret1Exp) { @@ -519,7 +519,7 @@ func TestMultiReturnWithStringSlice(t *testing.T) { buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000065")) // output[1][1] value ret1, ret1Exp := new([]string), []string{"ethereum", "go-ethereum"} ret2, ret2Exp := new([]*big.Int), []*big.Int{big.NewInt(100), big.NewInt(101)} - if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil { + if err := abi.UnpackIntoInterface(&[]any{ret1, ret2}, "multi", buff.Bytes()); err != nil { t.Fatal(err) } if !reflect.DeepEqual(*ret1, ret1Exp) { @@ -560,7 +560,7 @@ func TestMultiReturnWithDeeplyNestedArray(t *testing.T) { {{0x411, 0x412, 0x413}, {0x421, 0x422, 0x423}}, } ret2, ret2Exp := new(uint64), uint64(0x9876) - if err := abi.UnpackIntoInterface(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil { + if err := abi.UnpackIntoInterface(&[]any{ret1, ret2}, "multi", buff.Bytes()); err != nil { t.Fatal(err) } if !reflect.DeepEqual(*ret1, ret1Exp) { @@ -593,7 +593,7 @@ func TestUnmarshal(t *testing.T) { // marshall mixed bytes (mixedBytes) p0, p0Exp := []byte{}, common.Hex2Bytes("01020000000000000000") p1, p1Exp := [32]byte{}, common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000ddeeff") - mixedBytes := []interface{}{&p0, &p1} + mixedBytes := []any{&p0, &p1} buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000ddeeff")) @@ -1016,7 +1016,7 @@ func TestPackAndUnpackIncompatibleNumber(t *testing.T) { inputValue *big.Int unpackErr error packErr error - expectValue interface{} + expectValue any }{ { decodeType: "uint8", diff --git a/accounts/keystore/key.go b/accounts/keystore/key.go index 9b2ac14712..4f24b5cf23 100644 --- a/accounts/keystore/key.go +++ b/accounts/keystore/key.go @@ -78,12 +78,12 @@ type encryptedKeyJSONV1 struct { } type CryptoJSON struct { - Cipher string `json:"cipher"` - CipherText string `json:"ciphertext"` - CipherParams cipherparamsJSON `json:"cipherparams"` - KDF string `json:"kdf"` - KDFParams map[string]interface{} `json:"kdfparams"` - MAC string `json:"mac"` + Cipher string `json:"cipher"` + CipherText string `json:"ciphertext"` + CipherParams cipherparamsJSON `json:"cipherparams"` + KDF string `json:"kdf"` + KDFParams map[string]any `json:"kdfparams"` + MAC string `json:"mac"` } type cipherparamsJSON struct { diff --git a/accounts/keystore/passphrase.go b/accounts/keystore/passphrase.go index fc7ea938e2..c2083df654 100644 --- a/accounts/keystore/passphrase.go +++ b/accounts/keystore/passphrase.go @@ -158,7 +158,7 @@ func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) } mac := crypto.Keccak256(derivedKey[16:32], cipherText) - scryptParamsJSON := make(map[string]interface{}, 5) + scryptParamsJSON := make(map[string]any, 5) scryptParamsJSON["n"] = scryptN scryptParamsJSON["r"] = scryptR scryptParamsJSON["p"] = scryptP @@ -199,7 +199,7 @@ func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) { // DecryptKey decrypts a key from a json blob, returning the private key itself. func DecryptKey(keyjson []byte, auth string) (*Key, error) { // Parse the json into a simple map to fetch the key version - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(keyjson, &m); err != nil { return nil, err } @@ -359,7 +359,7 @@ func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) { // TODO: can we do without this when unmarshalling dynamic JSON? // why do integers in KDF params end up as float64 and not int after // unmarshal? -func ensureInt(x interface{}) int { +func ensureInt(x any) int { res, ok := x.(int) if !ok { res = int(x.(float64)) diff --git a/accounts/usbwallet/ledger.go b/accounts/usbwallet/ledger.go index 80e63f1864..fab37c62b4 100644 --- a/accounts/usbwallet/ledger.go +++ b/accounts/usbwallet/ledger.go @@ -334,24 +334,24 @@ func (w *ledgerDriver) ledgerSign(derivationPath []uint32, tx *types.Transaction err error ) if chainID == nil { - if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil { + if txrlp, err = rlp.EncodeToBytes([]any{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data()}); err != nil { return common.Address{}, nil, err } } else { if tx.Type() == types.DynamicFeeTxType { - if txrlp, err = rlp.EncodeToBytes([]interface{}{chainID, tx.Nonce(), tx.GasTipCap(), tx.GasFeeCap(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil { + if txrlp, err = rlp.EncodeToBytes([]any{chainID, tx.Nonce(), tx.GasTipCap(), tx.GasFeeCap(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil { return common.Address{}, nil, err } // append type to transaction txrlp = append([]byte{tx.Type()}, txrlp...) } else if tx.Type() == types.AccessListTxType { - if txrlp, err = rlp.EncodeToBytes([]interface{}{chainID, tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil { + if txrlp, err = rlp.EncodeToBytes([]any{chainID, tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), tx.AccessList()}); err != nil { return common.Address{}, nil, err } // append type to transaction txrlp = append([]byte{tx.Type()}, txrlp...) } else if tx.Type() == types.LegacyTxType { - if txrlp, err = rlp.EncodeToBytes([]interface{}{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), chainID, big.NewInt(0), big.NewInt(0)}); err != nil { + if txrlp, err = rlp.EncodeToBytes([]any{tx.Nonce(), tx.GasPrice(), tx.Gas(), tx.To(), tx.Value(), tx.Data(), chainID, big.NewInt(0), big.NewInt(0)}); err != nil { return common.Address{}, nil, err } } diff --git a/beacon/engine/errors.go b/beacon/engine/errors.go index 62773a0ea9..ad60a0a05c 100644 --- a/beacon/engine/errors.go +++ b/beacon/engine/errors.go @@ -31,7 +31,7 @@ type EngineAPIError struct { func (e *EngineAPIError) ErrorCode() int { return e.code } func (e *EngineAPIError) Error() string { return e.msg } -func (e *EngineAPIError) ErrorData() interface{} { +func (e *EngineAPIError) ErrorData() any { if e.err == nil { return nil } diff --git a/beacon/light/test_helpers.go b/beacon/light/test_helpers.go index 50e554b3d7..de5ed8fe28 100644 --- a/beacon/light/test_helpers.go +++ b/beacon/light/test_helpers.go @@ -104,7 +104,7 @@ func makeTestHeaderWithMerkleProof(slot, index uint64, value merkle.Value) (type } // syncCommittee holds either a blsSyncCommittee or a fake dummySyncCommittee used for testing -type syncCommittee interface{} +type syncCommittee any // committeeSigVerifier verifies sync committee signatures (either proper BLS // signatures or fake signatures used for testing) diff --git a/build/ci.go b/build/ci.go index abb7c4997f..688b23942a 100644 --- a/build/ci.go +++ b/build/ci.go @@ -1227,7 +1227,7 @@ func doWindowsInstaller(cmdline []string) { // Render NSIS scripts: Installer NSIS contains two installer sections, // first section contains the geth binary, second section holds the dev tools. - templateData := map[string]interface{}{ + templateData := map[string]any{ "License": "COPYING", "Geth": gethTool, "DevTools": devTools, diff --git a/cmd/abidump/main.go b/cmd/abidump/main.go index ae1ac64139..4ffb036257 100644 --- a/cmd/abidump/main.go +++ b/cmd/abidump/main.go @@ -68,7 +68,7 @@ func main() { } } -func die(args ...interface{}) { +func die(args ...any) { fmt.Fprintln(os.Stderr, args...) os.Exit(1) } diff --git a/cmd/clef/main.go b/cmd/clef/main.go index dde4ae853f..94852f8422 100644 --- a/cmd/clef/main.go +++ b/cmd/clef/main.go @@ -779,7 +779,7 @@ func signer(c *cli.Context) error { go testExternalUI(apiImpl) } ui.OnSignerStartup(core.StartupInfo{ - Info: map[string]interface{}{ + Info: map[string]any{ "intapi_version": core.InternalAPIVersion, "extapi_version": core.ExternalAPIVersion, "extapi_http": extapiURL, @@ -1084,7 +1084,7 @@ func GenDoc(ctx *cli.Context) error { UserAgent: "Firefox 3.2", } output []string - add = func(name, desc string, v interface{}) { + add = func(name, desc string, v any) { if data, err := json.MarshalIndent(v, "", " "); err == nil { output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data)) } else { diff --git a/cmd/devp2p/enrcmd.go b/cmd/devp2p/enrcmd.go index c9b692612f..349ede8ff7 100644 --- a/cmd/devp2p/enrcmd.go +++ b/cmd/devp2p/enrcmd.go @@ -98,7 +98,7 @@ func dumpNodeURL(out io.Writer, n *enode.Node) { fmt.Fprintf(out, "URLv4: %s\n", n.URLv4()) } -func dumpRecordKV(kv []interface{}, indent int) string { +func dumpRecordKV(kv []any, indent int) string { // Determine the longest key name for alignment. var out string var longestKey = 0 diff --git a/cmd/devp2p/internal/v5test/framework.go b/cmd/devp2p/internal/v5test/framework.go index 92a5048150..61f2c64df1 100644 --- a/cmd/devp2p/internal/v5test/framework.go +++ b/cmd/devp2p/internal/v5test/framework.go @@ -44,10 +44,10 @@ func (p *readError) Unwrap() error { return p.err } func (p *readError) RequestID() []byte { return nil } func (p *readError) SetRequestID([]byte) {} -func (p *readError) AppendLogInfo(ctx []interface{}) []interface{} { return ctx } +func (p *readError) AppendLogInfo(ctx []any) []any { return ctx } // readErrorf creates a readError with the given text. -func readErrorf(format string, args ...interface{}) *readError { +func readErrorf(format string, args ...any) *readError { return &readError{fmt.Errorf(format, args...)} } @@ -68,7 +68,7 @@ type conn struct { } type logger interface { - Logf(string, ...interface{}) + Logf(string, ...any) } // newConn sets up a connection to the given node. @@ -231,7 +231,7 @@ func (tc *conn) read(c net.PacketConn) v5wire.Packet { } // logf prints to the test log. -func (tc *conn) logf(format string, args ...interface{}) { +func (tc *conn) logf(format string, args ...any) { if tc.log != nil { tc.log.Logf("(%s) %s", tc.localNode.ID().TerminalString(), fmt.Sprintf(format, args...)) } diff --git a/cmd/devp2p/main.go b/cmd/devp2p/main.go index 66974bba58..57a208978f 100644 --- a/cmd/devp2p/main.go +++ b/cmd/devp2p/main.go @@ -92,7 +92,7 @@ func getNodeArg(ctx *cli.Context) *enode.Node { return n } -func exit(err interface{}) { +func exit(err any) { if err == nil { os.Exit(0) } diff --git a/cmd/devp2p/nodesetcmd.go b/cmd/devp2p/nodesetcmd.go index d7725fadb1..d2cf59c138 100644 --- a/cmd/devp2p/nodesetcmd.go +++ b/cmd/devp2p/nodesetcmd.go @@ -72,7 +72,7 @@ func nodesetInfo(ctx *cli.Context) error { // showAttributeCounts prints the distribution of ENR attributes in a node set. func showAttributeCounts(ns nodeSet) { attrcount := make(map[string]int) - var attrlist []interface{} + var attrlist []any for _, n := range ns { r := n.N.Record() attrlist = r.AppendElements(attrlist[:0])[1:] diff --git a/cmd/ethkey/utils.go b/cmd/ethkey/utils.go index 2821145089..bf868c9cc8 100644 --- a/cmd/ethkey/utils.go +++ b/cmd/ethkey/utils.go @@ -47,7 +47,7 @@ func getPassphrase(ctx *cli.Context, confirmation bool) string { // mustPrintJSON prints the JSON encoding of the given object and // exits the program with an error message when the marshaling fails. -func mustPrintJSON(jsonObject interface{}) { +func mustPrintJSON(jsonObject any) { str, err := json.MarshalIndent(jsonObject, "", " ") if err != nil { utils.Fatalf("Failed to marshal JSON object: %v", err) diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go index af60333cbd..d88c922c02 100644 --- a/cmd/evm/internal/t8ntool/transition.go +++ b/cmd/evm/internal/t8ntool/transition.go @@ -318,7 +318,7 @@ func (g Alloc) OnAccount(addr *common.Address, dumpAccount state.DumpAccount) { } // saveFile marshals the object to the given file -func saveFile(baseDir, filename string, data interface{}) error { +func saveFile(baseDir, filename string, data any) error { b, err := json.MarshalIndent(data, "", " ") if err != nil { return NewError(ErrorJson, fmt.Errorf("failed marshalling output: %v", err)) @@ -334,9 +334,9 @@ func saveFile(baseDir, filename string, data interface{}) error { // dispatchOutput writes the output data to either stderr or stdout, or to the specified // files func dispatchOutput(ctx *cli.Context, baseDir string, result *ExecutionResult, alloc Alloc, body hexutil.Bytes, bt map[common.Hash]hexutil.Bytes) error { - stdOutObject := make(map[string]interface{}) - stdErrObject := make(map[string]interface{}) - dispatch := func(baseDir, fName, name string, obj interface{}) error { + stdOutObject := make(map[string]any) + stdErrObject := make(map[string]any) + dispatch := func(baseDir, fName, name string, obj any) error { switch fName { case "stdout": stdOutObject[name] = obj diff --git a/cmd/evm/internal/t8ntool/utils.go b/cmd/evm/internal/t8ntool/utils.go index 42f5471e7b..a472ad8d5b 100644 --- a/cmd/evm/internal/t8ntool/utils.go +++ b/cmd/evm/internal/t8ntool/utils.go @@ -25,7 +25,7 @@ import ( ) // readFile reads the json-data in the provided path and marshals into dest. -func readFile(path, desc string, dest interface{}) error { +func readFile(path, desc string, dest any) error { inFile, err := os.Open(path) if err != nil { return NewError(ErrorIO, fmt.Errorf("failed reading %s file: %v", desc, err)) diff --git a/cmd/evm/t8n_test.go b/cmd/evm/t8n_test.go index 3c6fd90b47..929b9e1627 100644 --- a/cmd/evm/t8n_test.go +++ b/cmd/evm/t8n_test.go @@ -736,7 +736,7 @@ func TestEvmRunRegEx(t *testing.T) { // cmpJson compares the JSON in two byte slices. func cmpJson(a, b []byte) (bool, error) { - var j, j2 interface{} + var j, j2 any if err := json.Unmarshal(a, &j); err != nil { return false, err } diff --git a/cmd/rlpdump/main.go b/cmd/rlpdump/main.go index 685e5bb71a..8cc848c273 100644 --- a/cmd/rlpdump/main.go +++ b/cmd/rlpdump/main.go @@ -174,7 +174,7 @@ func ws(n int) string { return strings.Repeat(" ", n) } -func die(args ...interface{}) { +func die(args ...any) { fmt.Fprintln(os.Stderr, args...) os.Exit(1) } @@ -187,7 +187,7 @@ func textToRlp(r io.Reader) ([]byte, error) { // - an element is either hex-encoded bytes OR a quoted string var ( scanner = bufio.NewScanner(r) - obj []interface{} + obj []any stack = list.New() ) for scanner.Scan() { @@ -198,12 +198,12 @@ func textToRlp(r io.Reader) ([]byte, error) { switch t { case "[": // list start stack.PushFront(obj) - obj = make([]interface{}, 0) + obj = make([]any, 0) case "]", "],": // list end - parent := stack.Remove(stack.Front()).([]interface{}) + parent := stack.Remove(stack.Front()).([]any) obj = append(parent, obj) case "[],": // empty list - obj = append(obj, make([]interface{}, 0)) + obj = append(obj, make([]any, 0)) default: // element data := []byte(t)[:len(t)-1] // cut off comma if data[0] == '"' { // ascii string diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 3e337a3d00..024185e0d7 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -63,7 +63,7 @@ var ErrImportInterrupted = errors.New("interrupted") // Fatalf formats a message to standard error and exits the program. // The message is also printed to standard output if standard error // is redirected to a different file. -func Fatalf(format string, args ...interface{}) { +func Fatalf(format string, args ...any) { w := io.MultiWriter(os.Stdout, os.Stderr) if runtime.GOOS == "windows" || runtime.GOOS == "openbsd" { // The SameFile check below doesn't work on Windows neither OpenBSD. diff --git a/common/compiler/helpers.go b/common/compiler/helpers.go index 063fc10811..452ec6162e 100644 --- a/common/compiler/helpers.go +++ b/common/compiler/helpers.go @@ -31,15 +31,15 @@ type Contract struct { // Depending on the source, language version, compiler version, and compiler // options will provide information about how the contract was compiled. type ContractInfo struct { - Source string `json:"source"` - Language string `json:"language"` - LanguageVersion string `json:"languageVersion"` - CompilerVersion string `json:"compilerVersion"` - CompilerOptions string `json:"compilerOptions"` - SrcMap interface{} `json:"srcMap"` - SrcMapRuntime string `json:"srcMapRuntime"` - AbiDefinition interface{} `json:"abiDefinition"` - UserDoc interface{} `json:"userDoc"` - DeveloperDoc interface{} `json:"developerDoc"` - Metadata string `json:"metadata"` + Source string `json:"source"` + Language string `json:"language"` + LanguageVersion string `json:"languageVersion"` + CompilerVersion string `json:"compilerVersion"` + CompilerOptions string `json:"compilerOptions"` + SrcMap any `json:"srcMap"` + SrcMapRuntime string `json:"srcMapRuntime"` + AbiDefinition any `json:"abiDefinition"` + UserDoc any `json:"userDoc"` + DeveloperDoc any `json:"developerDoc"` + Metadata string `json:"metadata"` } diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 9de94017c2..d58042dd0f 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -39,9 +39,9 @@ type solcOutputV8 struct { BinRuntime string `json:"bin-runtime"` SrcMapRuntime string `json:"srcmap-runtime"` Bin, SrcMap, Metadata string - Abi interface{} - Devdoc interface{} - Userdoc interface{} + Abi any + Devdoc any + Userdoc any Hashes map[string]string } Version string @@ -66,7 +66,7 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin contracts := make(map[string]*Contract) for name, info := range output.Contracts { // Parse the individual compilation results. - var abi, userdoc, devdoc interface{} + var abi, userdoc, devdoc any if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) } diff --git a/common/debug.go b/common/debug.go index 28c52b4a9c..36186b5e56 100644 --- a/common/debug.go +++ b/common/debug.go @@ -25,7 +25,7 @@ import ( ) // Report gives off a warning requesting the user to submit an issue to the github tracker. -func Report(extra ...interface{}) { +func Report(extra ...any) { fmt.Fprintln(os.Stderr, "You've encountered a sought after, hard to reproduce bug. Please report this to the developers <3 https://github.com/ethereum/go-ethereum/issues") fmt.Fprintln(os.Stderr, extra...) diff --git a/common/hexutil/hexutil_test.go b/common/hexutil/hexutil_test.go index f2b800d82c..a87daf82ab 100644 --- a/common/hexutil/hexutil_test.go +++ b/common/hexutil/hexutil_test.go @@ -23,13 +23,13 @@ import ( ) type marshalTest struct { - input interface{} + input any want string } type unmarshalTest struct { input string - want interface{} + want any wantErr error // if set, decoding must fail on any platform wantErr32bit error // if set, decoding must fail on 32bit platforms (used for Uint tests) } diff --git a/common/hexutil/json.go b/common/hexutil/json.go index 6b9f412078..e7964e6f87 100644 --- a/common/hexutil/json.go +++ b/common/hexutil/json.go @@ -79,7 +79,7 @@ func (b Bytes) String() string { func (b Bytes) ImplementsGraphQLType(name string) bool { return name == "Bytes" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (b *Bytes) UnmarshalGraphQL(input interface{}) error { +func (b *Bytes) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: @@ -213,7 +213,7 @@ func (b *Big) String() string { func (b Big) ImplementsGraphQLType(name string) bool { return name == "BigInt" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (b *Big) UnmarshalGraphQL(input interface{}) error { +func (b *Big) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: @@ -321,7 +321,7 @@ func (b Uint64) String() string { func (b Uint64) ImplementsGraphQLType(name string) bool { return name == "Long" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (b *Uint64) UnmarshalGraphQL(input interface{}) error { +func (b *Uint64) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: diff --git a/common/mclock/simclock.go b/common/mclock/simclock.go index f5ad3f8bc0..4bcc8c5498 100644 --- a/common/mclock/simclock.go +++ b/common/mclock/simclock.go @@ -193,13 +193,13 @@ func (h *simTimerHeap) Swap(i, j int) { (*h)[j].index = j } -func (h *simTimerHeap) Push(x interface{}) { +func (h *simTimerHeap) Push(x any) { t := x.(*simTimer) t.index = len(*h) *h = append(*h, t) } -func (h *simTimerHeap) Pop() interface{} { +func (h *simTimerHeap) Pop() any { end := len(*h) - 1 t := (*h)[end] t.index = -1 diff --git a/common/prque/lazyqueue_test.go b/common/prque/lazyqueue_test.go index ffb7e5e9e3..09f3fdbc0b 100644 --- a/common/prque/lazyqueue_test.go +++ b/common/prque/lazyqueue_test.go @@ -40,18 +40,18 @@ type lazyItem struct { index int } -func testPriority(a interface{}) int64 { +func testPriority(a any) int64 { return a.(*lazyItem).p } -func testMaxPriority(a interface{}, until mclock.AbsTime) int64 { +func testMaxPriority(a any, until mclock.AbsTime) int64 { i := a.(*lazyItem) dt := until - i.last i.maxp = i.p + int64(float64(dt)*testAvgRate) return i.maxp } -func testSetIndex(a interface{}, i int) { +func testSetIndex(a any, i int) { a.(*lazyItem).index = i } diff --git a/common/test_utils.go b/common/test_utils.go index 7a175412f4..8d609910ea 100644 --- a/common/test_utils.go +++ b/common/test_utils.go @@ -23,7 +23,7 @@ import ( ) // LoadJSON reads the given file and unmarshals its content. -func LoadJSON(file string, val interface{}) error { +func LoadJSON(file string, val any) error { content, err := os.ReadFile(file) if err != nil { return err diff --git a/common/types.go b/common/types.go index a96d6c7c83..2aac66e0cc 100644 --- a/common/types.go +++ b/common/types.go @@ -171,7 +171,7 @@ func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value { } // Scan implements Scanner for database/sql. -func (h *Hash) Scan(src interface{}) error { +func (h *Hash) Scan(src any) error { srcB, ok := src.([]byte) if !ok { return fmt.Errorf("can't scan %T into Hash", src) @@ -192,7 +192,7 @@ func (h Hash) Value() (driver.Value, error) { func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (h *Hash) UnmarshalGraphQL(input interface{}) error { +func (h *Hash) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: @@ -348,7 +348,7 @@ func (a *Address) UnmarshalJSON(input []byte) error { } // Scan implements Scanner for database/sql. -func (a *Address) Scan(src interface{}) error { +func (a *Address) Scan(src any) error { srcB, ok := src.([]byte) if !ok { return fmt.Errorf("can't scan %T into Address", src) @@ -369,7 +369,7 @@ func (a Address) Value() (driver.Value, error) { func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (a *Address) UnmarshalGraphQL(input interface{}) error { +func (a *Address) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: diff --git a/common/types_test.go b/common/types_test.go index 11247b117b..b0b99c9984 100644 --- a/common/types_test.go +++ b/common/types_test.go @@ -223,7 +223,7 @@ func TestMixedcaseAccount_Address(t *testing.T) { func TestHash_Scan(t *testing.T) { type args struct { - src interface{} + src any } tests := []struct { name string @@ -314,7 +314,7 @@ func TestHash_Value(t *testing.T) { func TestAddress_Scan(t *testing.T) { type args struct { - src interface{} + src any } tests := []struct { name string diff --git a/consensus/clique/clique.go b/consensus/clique/clique.go index a6f02c8c2b..254c189848 100644 --- a/consensus/clique/clique.go +++ b/consensus/clique/clique.go @@ -662,7 +662,7 @@ func CliqueRLP(header *types.Header) []byte { } func encodeSigHeader(w io.Writer, header *types.Header) { - enc := []interface{}{ + enc := []any{ header.ParentHash, header.UncleHash, header.Coinbase, diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index 376cbac8c0..8db7434ca8 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -529,7 +529,7 @@ func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainHeaderReader, hea func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) { hasher := sha3.NewLegacyKeccak256() - enc := []interface{}{ + enc := []any{ header.ParentHash, header.UncleHash, header.Coinbase, diff --git a/console/bridge.go b/console/bridge.go index c1d7746c02..7a035561a6 100644 --- a/console/bridge.go +++ b/console/bridge.go @@ -113,7 +113,7 @@ func (b *bridge) SleepBlocks(call jsre.Call) (goja.Value, error) { type jsonrpcCall struct { ID int64 Method string - Params []interface{} + Params []any } // Send implements the web3 provider "send" method. @@ -168,7 +168,7 @@ func (b *bridge) Send(call jsre.Call) (goja.Value, error) { } } else { code := -32603 - var data interface{} + var data any if err, ok := err.(rpc.Error); ok { code = err.ErrorCode() } @@ -194,8 +194,8 @@ func (b *bridge) Send(call jsre.Call) (goja.Value, error) { return result, nil } -func setError(resp *goja.Object, code int, msg string, data interface{}) { - err := make(map[string]interface{}) +func setError(resp *goja.Object, code int, msg string, data any) { + err := make(map[string]any) err["code"] = code err["message"] = msg if data != nil { diff --git a/core/blockchain.go b/core/blockchain.go index e71f97b7b9..2f3dabd4c8 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -1578,14 +1578,14 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [ } var ( head = blockChain[len(blockChain)-1] - context = []interface{}{ + context = []any{ "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)), "size", common.StorageSize(size), } ) if stats.ignored > 0 { - context = append(context, []interface{}{"ignored", stats.ignored}...) + context = append(context, []any{"ignored", stats.ignored}...) } log.Debug("Imported new block receipts", context...) return 0, nil @@ -2693,14 +2693,14 @@ func (bc *BlockChain) SetCanonical(head *types.Block) (common.Hash, error) { } bc.chainHeadFeed.Send(ChainHeadEvent{Header: head.Header()}) - context := []interface{}{ + context := []any{ "number", head.Number(), "hash", head.Hash(), "root", head.Root(), "elapsed", time.Since(start), } if timestamp := time.Unix(int64(head.Time()), 0); time.Since(timestamp) > time.Minute { - context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) + context = append(context, []any{"age", common.PrettyAge(timestamp)}...) } log.Info("Chain head was updated", context...) return head.Hash(), nil diff --git a/core/blockchain_insert.go b/core/blockchain_insert.go index 07a250a1bb..75e881f185 100644 --- a/core/blockchain_insert.go +++ b/core/blockchain_insert.go @@ -56,27 +56,27 @@ func (st *insertStats) report(chain []*types.Block, index int, snapDiffItems, sn end := chain[index] // Assemble the log context and send it to the logger - context := []interface{}{ + context := []any{ "number", end.Number(), "hash", end.Hash(), "blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000, "elapsed", common.PrettyDuration(elapsed), "mgasps", mgasps, } if timestamp := time.Unix(int64(end.Time()), 0); time.Since(timestamp) > time.Minute { - context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) + context = append(context, []any{"age", common.PrettyAge(timestamp)}...) } if snapDiffItems != 0 || snapBufItems != 0 { // snapshots enabled - context = append(context, []interface{}{"snapdiffs", snapDiffItems}...) + context = append(context, []any{"snapdiffs", snapDiffItems}...) if snapBufItems != 0 { // future snapshot refactor - context = append(context, []interface{}{"snapdirty", snapBufItems}...) + context = append(context, []any{"snapdirty", snapBufItems}...) } } if trieDiffNodes != 0 { // pathdb - context = append(context, []interface{}{"triediffs", trieDiffNodes}...) + context = append(context, []any{"triediffs", trieDiffNodes}...) } - context = append(context, []interface{}{"triedirty", triebufNodes}...) + context = append(context, []any{"triedirty", triebufNodes}...) if st.ignored > 0 { - context = append(context, []interface{}{"ignored", st.ignored}...) + context = append(context, []any{"ignored", st.ignored}...) } if setHead { log.Info("Imported new chain segment", context...) diff --git a/core/headerchain.go b/core/headerchain.go index a33222e9fd..47f56e2dfb 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -327,18 +327,18 @@ func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, start time.Time) return 0, err } // Report some public statistics so the user has a clue what's going on - context := []interface{}{ + context := []any{ "count", res.imported, "elapsed", common.PrettyDuration(time.Since(start)), } if last := res.lastHeader; last != nil { context = append(context, "number", last.Number, "hash", res.lastHash) if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute { - context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) + context = append(context, []any{"age", common.PrettyAge(timestamp)}...) } } if res.ignored > 0 { - context = append(context, []interface{}{"ignored", res.ignored}...) + context = append(context, []any{"ignored", res.ignored}...) } log.Debug("Imported new block headers", context...) return res.status, err diff --git a/core/rawdb/chain_freezer.go b/core/rawdb/chain_freezer.go index d33f7ce33d..14901a5073 100644 --- a/core/rawdb/chain_freezer.go +++ b/core/rawdb/chain_freezer.go @@ -287,11 +287,11 @@ func (f *chainFreezer) freeze(db ethdb.KeyValueStore) { } // Log something friendly for the user - context := []interface{}{ + context := []any{ "blocks", frozen - first, "elapsed", common.PrettyDuration(time.Since(start)), "number", frozen - 1, } if n := len(ancients); n > 0 { - context = append(context, []interface{}{"hash", ancients[n-1]}...) + context = append(context, []any{"hash", ancients[n-1]}...) } log.Debug("Deep froze chain segment", context...) diff --git a/core/rawdb/freezer_batch.go b/core/rawdb/freezer_batch.go index 080c0720a1..450f367e60 100644 --- a/core/rawdb/freezer_batch.go +++ b/core/rawdb/freezer_batch.go @@ -50,7 +50,7 @@ func newFreezerBatch(f *Freezer) *freezerBatch { } // Append adds an RLP-encoded item of the given kind. -func (batch *freezerBatch) Append(kind string, num uint64, item interface{}) error { +func (batch *freezerBatch) Append(kind string, num uint64, item any) error { if table := batch.tables[kind]; table != nil { return table.Append(num, item) } @@ -127,7 +127,7 @@ func (batch *freezerTableBatch) reset() { // Append rlp-encodes and adds data at the end of the freezer table. The item number is a // precautionary parameter to ensure data correctness, but the table will reject already // existing data. -func (batch *freezerTableBatch) Append(item uint64, data interface{}) error { +func (batch *freezerTableBatch) Append(item uint64, data any) error { if item != batch.curItem { return fmt.Errorf("%w: have %d want %d", errOutOrderInsertion, item, batch.curItem) } diff --git a/core/rawdb/freezer_memory.go b/core/rawdb/freezer_memory.go index a0d308f896..4f5fffd065 100644 --- a/core/rawdb/freezer_memory.go +++ b/core/rawdb/freezer_memory.go @@ -167,7 +167,7 @@ func (b *memoryBatch) reset(freezer *MemoryFreezer) { } // Append adds an RLP-encoded item. -func (b *memoryBatch) Append(kind string, number uint64, item interface{}) error { +func (b *memoryBatch) Append(kind string, number uint64, item any) error { if b.next[kind] != number { return errOutOrderInsertion } diff --git a/core/state/snapshot/context.go b/core/state/snapshot/context.go index 3d293d27f4..8fcd34ecb8 100644 --- a/core/state/snapshot/context.go +++ b/core/state/snapshot/context.go @@ -49,22 +49,22 @@ type generatorStats struct { // Log creates a contextual log with the given message and the context pulled // from the internally maintained statistics. func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) { - var ctx []interface{} + var ctx []any if root != (common.Hash{}) { - ctx = append(ctx, []interface{}{"root", root}...) + ctx = append(ctx, []any{"root", root}...) } // Figure out whether we're after or within an account switch len(marker) { case common.HashLength: - ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...) + ctx = append(ctx, []any{"at", common.BytesToHash(marker)}...) case 2 * common.HashLength: - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "in", common.BytesToHash(marker[:common.HashLength]), "at", common.BytesToHash(marker[common.HashLength:]), }...) } // Add the usual measurements - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "accounts", gs.accounts, "slots", gs.slots, "storage", gs.storage, @@ -77,7 +77,7 @@ func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) { left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8]) speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond), }...) } diff --git a/core/state/snapshot/conversion.go b/core/state/snapshot/conversion.go index 0d39687be4..06d9909113 100644 --- a/core/state/snapshot/conversion.go +++ b/core/state/snapshot/conversion.go @@ -162,7 +162,7 @@ func (stat *generateStats) report() { stat.lock.RLock() defer stat.lock.RUnlock() - ctx := []interface{}{ + ctx := []any{ "accounts", stat.accounts, "slots", stat.slots, "elapsed", common.PrettyDuration(time.Since(stat.start)), @@ -185,7 +185,7 @@ func (stat *generateStats) report() { } } } - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "eta", common.PrettyDuration(eta), }...) } @@ -198,12 +198,12 @@ func (stat *generateStats) reportDone() { stat.lock.RLock() defer stat.lock.RUnlock() - var ctx []interface{} - ctx = append(ctx, []interface{}{"accounts", stat.accounts}...) + var ctx []any + ctx = append(ctx, []any{"accounts", stat.accounts}...) if stat.slots != 0 { - ctx = append(ctx, []interface{}{"slots", stat.slots}...) + ctx = append(ctx, []any{"slots", stat.slots}...) } - ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...) + ctx = append(ctx, []any{"elapsed", common.PrettyDuration(time.Since(stat.start))}...) log.Info("Iterated snapshot", ctx...) } diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index 01fb55ea4c..70f94b7aa4 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -313,7 +313,7 @@ func (dl *diskLayer) generateRange(ctx *generatorContext, trieId *trie.ID, prefi last := result.last() // Construct contextual logger - logCtx := []interface{}{"kind", kind, "prefix", hexutil.Encode(prefix)} + logCtx := []any{"kind", kind, "prefix", hexutil.Encode(prefix)} if len(origin) > 0 { logCtx = append(logCtx, "origin", hexutil.Encode(origin)) } diff --git a/core/state/statedb_test.go b/core/state/statedb_test.go index 661d17bb7b..61c52c1fcc 100644 --- a/core/state/statedb_test.go +++ b/core/state/statedb_test.go @@ -590,7 +590,7 @@ func forEachStorage(s *StateDB, addr common.Address, cb func(key, value common.H func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error { for _, addr := range test.addrs { var err error - checkeq := func(op string, a, b interface{}) bool { + checkeq := func(op string, a, b any) bool { if err == nil && !reflect.DeepEqual(a, b) { err = fmt.Errorf("got %s(%s) == %v, want %v", op, addr.Hex(), a, b) return false diff --git a/core/txpool/legacypool/list.go b/core/txpool/legacypool/list.go index 0c9f13c62f..32d2537b9d 100644 --- a/core/txpool/legacypool/list.go +++ b/core/txpool/legacypool/list.go @@ -39,11 +39,11 @@ func (h nonceHeap) Len() int { return len(h) } func (h nonceHeap) Less(i, j int) bool { return h[i] < h[j] } func (h nonceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *nonceHeap) Push(x interface{}) { +func (h *nonceHeap) Push(x any) { *h = append(*h, x.(uint64)) } -func (h *nonceHeap) Pop() interface{} { +func (h *nonceHeap) Pop() any { old := *h n := len(old) x := old[n-1] @@ -515,12 +515,12 @@ func (h *priceHeap) cmp(a, b *types.Transaction) int { return a.GasTipCapCmp(b) } -func (h *priceHeap) Push(x interface{}) { +func (h *priceHeap) Push(x any) { tx := x.(*types.Transaction) h.list = append(h.list, tx) } -func (h *priceHeap) Pop() interface{} { +func (h *priceHeap) Pop() any { old := h.list n := len(old) x := old[n-1] diff --git a/core/types/block.go b/core/types/block.go index c52c05a4c7..a31ecb39cc 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -208,7 +208,7 @@ type Block struct { // These fields are used by package eth to track // inter-peer block relay. ReceivedAt time.Time - ReceivedFrom interface{} + ReceivedFrom any } // "external" block encoding. used for eth protocol, etc. diff --git a/core/types/block_test.go b/core/types/block_test.go index 5fa4756a50..e33593e658 100644 --- a/core/types/block_test.go +++ b/core/types/block_test.go @@ -41,7 +41,7 @@ func TestBlockEncoding(t *testing.T) { t.Fatal("decode error: ", err) } - check := func(f string, got, want interface{}) { + check := func(f string, got, want any) { if !reflect.DeepEqual(got, want) { t.Errorf("%s mismatch: got %v, want %v", f, got, want) } @@ -77,7 +77,7 @@ func TestEIP1559BlockEncoding(t *testing.T) { t.Fatal("decode error: ", err) } - check := func(f string, got, want interface{}) { + check := func(f string, got, want any) { if !reflect.DeepEqual(got, want) { t.Errorf("%s mismatch: got %v, want %v", f, got, want) } @@ -142,7 +142,7 @@ func TestEIP2718BlockEncoding(t *testing.T) { t.Fatal("decode error: ", err) } - check := func(f string, got, want interface{}) { + check := func(f string, got, want any) { if !reflect.DeepEqual(got, want) { t.Errorf("%s mismatch: got %v, want %v", f, got, want) } @@ -204,7 +204,7 @@ func TestEIP4844BlockEncoding(t *testing.T) { t.Fatal("decode error: ", err) } - check := func(f string, got, want interface{}) { + check := func(f string, got, want any) { if !reflect.DeepEqual(got, want) { t.Errorf("%s mismatch: got %v, want %v", f, got, want) } diff --git a/core/types/hashing.go b/core/types/hashing.go index 98fe64e15a..bbbe615cc1 100644 --- a/core/types/hashing.go +++ b/core/types/hashing.go @@ -29,12 +29,12 @@ import ( // hasherPool holds LegacyKeccak256 buffer for rlpHash. var hasherPool = sync.Pool{ - New: func() interface{} { return crypto.NewKeccakState() }, + New: func() any { return crypto.NewKeccakState() }, } // encodeBufferPool holds temporary encoder buffers for DeriveSha and TX encoding. var encodeBufferPool = sync.Pool{ - New: func() interface{} { return new(bytes.Buffer) }, + New: func() any { return new(bytes.Buffer) }, } // getPooledBuffer retrieves a buffer from the pool and creates a byte slice of the @@ -54,7 +54,7 @@ func getPooledBuffer(size uint64) ([]byte, *bytes.Buffer, error) { } // rlpHash encodes x and hashes the encoded bytes. -func rlpHash(x interface{}) (h common.Hash) { +func rlpHash(x any) (h common.Hash) { sha := hasherPool.Get().(crypto.KeccakState) defer hasherPool.Put(sha) sha.Reset() @@ -65,7 +65,7 @@ func rlpHash(x interface{}) (h common.Hash) { // prefixedRlpHash writes the prefix into the hasher before rlp-encoding x. // It's used for typed transactions. -func prefixedRlpHash(prefix byte, x interface{}) (h common.Hash) { +func prefixedRlpHash(prefix byte, x any) (h common.Hash) { sha := hasherPool.Get().(crypto.KeccakState) defer hasherPool.Put(sha) sha.Reset() diff --git a/core/types/rlp_fuzzer_test.go b/core/types/rlp_fuzzer_test.go index a3b9f72436..5f5c6c0577 100644 --- a/core/types/rlp_fuzzer_test.go +++ b/core/types/rlp_fuzzer_test.go @@ -26,7 +26,7 @@ import ( "github.com/holiman/uint256" ) -func decodeEncode(input []byte, val interface{}) error { +func decodeEncode(input []byte, val any) error { if err := rlp.DecodeBytes(input, val); err != nil { // not valid rlp, nothing to do return nil @@ -54,8 +54,8 @@ func fuzzRlp(t *testing.T, input []byte) { if elems, _, err := rlp.SplitList(input); err == nil { rlp.CountValues(elems) } - rlp.NewStream(bytes.NewReader(input), 0).Decode(new(interface{})) - if err := decodeEncode(input, new(interface{})); err != nil { + rlp.NewStream(bytes.NewReader(input), 0).Decode(new(any)) + if err := decodeEncode(input, new(any)); err != nil { t.Fatal(err) } { @@ -73,7 +73,7 @@ func fuzzRlp(t *testing.T, input []byte) { Bool bool Raw rlp.RawValue Slice []*Types - Iface []interface{} + Iface []any } var v Types if err := decodeEncode(input, &v); err != nil { @@ -89,7 +89,7 @@ func fuzzRlp(t *testing.T, input []byte) { Raw rlp.RawValue Slice []*AllTypes Array [3]*AllTypes - Iface []interface{} + Iface []any } var v AllTypes if err := decodeEncode(input, &v); err != nil { diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go index 2d854ae345..3b06adad8b 100644 --- a/core/types/transaction_test.go +++ b/core/types/transaction_test.go @@ -491,7 +491,7 @@ func TestTransactionSizes(t *testing.T) { } func TestYParityJSONUnmarshalling(t *testing.T) { - baseJson := map[string]interface{}{ + baseJson := map[string]any{ // type is filled in by the test "chainId": "0x7", "nonce": "0x0", @@ -503,7 +503,7 @@ func TestYParityJSONUnmarshalling(t *testing.T) { "maxFeePerBlobGas": "0x3b9aca00", "value": "0x0", "input": "0x", - "accessList": []interface{}{}, + "accessList": []any{}, "blobVersionedHashes": []string{ "0x010657f37554c781402a22917dee2f75def7ab966d7b770905398eba3c444014", }, diff --git a/core/types/types_test.go b/core/types/types_test.go index 96d0444994..655d03a3be 100644 --- a/core/types/types_test.go +++ b/core/types/types_test.go @@ -46,7 +46,7 @@ func benchRLP(b *testing.B, encode bool) { signer := NewLondonSigner(big.NewInt(1337)) for _, tc := range []struct { name string - obj interface{} + obj any }{ { "legacy-header", diff --git a/core/vm/program/program_test.go b/core/vm/program/program_test.go index ceb7d8be64..9be27e2243 100644 --- a/core/vm/program/program_test.go +++ b/core/vm/program/program_test.go @@ -28,7 +28,7 @@ import ( func TestPush(t *testing.T) { tests := []struct { - input interface{} + input any expected string }{ // native ints diff --git a/core/vm/stack.go b/core/vm/stack.go index 879dc9aa6d..c71a563616 100644 --- a/core/vm/stack.go +++ b/core/vm/stack.go @@ -23,7 +23,7 @@ import ( ) var stackPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &Stack{data: make([]uint256.Int, 0, 16)} }, } diff --git a/crypto/crypto.go b/crypto/crypto.go index db6b6ee071..511b37cad7 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -77,7 +77,7 @@ func HashData(kh KeccakState, data []byte) (h common.Hash) { // CreateAddress creates an ethereum address given the bytes and the nonce func CreateAddress(b common.Address, nonce uint64) common.Address { - data, _ := rlp.EncodeToBytes([]interface{}{b, nonce}) + data, _ := rlp.EncodeToBytes([]any{b, nonce}) return common.BytesToAddress(Keccak256(data)[12:]) } diff --git a/eth/api_debug.go b/eth/api_debug.go index db1b842e90..122d328910 100644 --- a/eth/api_debug.go +++ b/eth/api_debug.go @@ -98,9 +98,9 @@ func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.By // BadBlockArgs represents the entries in the list returned when bad blocks are queried. type BadBlockArgs struct { - Hash common.Hash `json:"hash"` - Block map[string]interface{} `json:"block"` - RLP string `json:"rlp"` + Hash common.Hash `json:"hash"` + Block map[string]any `json:"block"` + RLP string `json:"rlp"` } // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network @@ -113,7 +113,7 @@ func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) for _, block := range blocks { var ( blockRlp string - blockJSON map[string]interface{} + blockJSON map[string]any ) if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { blockRlp = err.Error() // Hacky, but hey, it works @@ -447,7 +447,7 @@ func (api *DebugAPI) GetTrieFlushInterval() (string, error) { // StateSize returns the current state size statistics from the state size tracker. // Returns an error if the state size tracker is not initialized or if stats are not ready. -func (api *DebugAPI) StateSize(blockHashOrNumber *rpc.BlockNumberOrHash) (interface{}, error) { +func (api *DebugAPI) StateSize(blockHashOrNumber *rpc.BlockNumberOrHash) (any, error) { sizer := api.eth.blockchain.StateSizer() if sizer == nil { return nil, errors.New("state size tracker is not enabled") @@ -477,7 +477,7 @@ func (api *DebugAPI) StateSize(blockHashOrNumber *rpc.BlockNumberOrHash) (interf } return nil, fmt.Errorf("state size of %s is not available", s) } - return map[string]interface{}{ + return map[string]any{ "stateRoot": stats.StateRoot, "blockNumber": hexutil.Uint64(stats.BlockNumber), "accounts": hexutil.Uint64(stats.Accounts), diff --git a/eth/backend.go b/eth/backend.go index cae2aabe30..58075954e7 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -370,7 +370,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { func makeExtraData(extra []byte) []byte { if len(extra) == 0 { // create default extradata - extra, _ = rlp.EncodeToBytes([]interface{}{ + extra, _ = rlp.EncodeToBytes([]any{ uint(gethversion.Major<<16 | gethversion.Minor<<8 | gethversion.Patch), "geth", runtime.Version(), diff --git a/eth/catalyst/api.go b/eth/catalyst/api.go index e6ecf4ff6a..437fb5c21d 100644 --- a/eth/catalyst/api.go +++ b/eth/catalyst/api.go @@ -250,12 +250,12 @@ func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payl finalized := api.remoteBlocks.get(update.FinalizedBlockHash) // Header advertised via a past newPayload request. Start syncing to it. - context := []interface{}{"number", header.Number, "hash", header.Hash()} + context := []any{"number", header.Number, "hash", header.Hash()} if update.FinalizedBlockHash != (common.Hash{}) { if finalized == nil { - context = append(context, []interface{}{"finalized", "unknown"}...) + context = append(context, []any{"finalized", "unknown"}...) } else { - context = append(context, []interface{}{"finalized", finalized.Number}...) + context = append(context, []any{"finalized", finalized.Number}...) } } log.Info("Forkchoice requested sync to new head", context...) diff --git a/eth/downloader/api.go b/eth/downloader/api.go index f97371de5f..3409883a7d 100644 --- a/eth/downloader/api.go +++ b/eth/downloader/api.go @@ -34,7 +34,7 @@ type DownloaderAPI struct { d *Downloader chain *core.BlockChain mux *event.TypeMux - installSyncSubscription chan chan interface{} + installSyncSubscription chan chan any uninstallSyncSubscription chan *uninstallSyncSubscriptionRequest } @@ -47,7 +47,7 @@ func NewDownloaderAPI(d *Downloader, chain *core.BlockChain, m *event.TypeMux) * d: d, chain: chain, mux: m, - installSyncSubscription: make(chan chan interface{}), + installSyncSubscription: make(chan chan any), uninstallSyncSubscription: make(chan *uninstallSyncSubscriptionRequest), } go api.eventLoop() @@ -67,7 +67,7 @@ func NewDownloaderAPI(d *Downloader, chain *core.BlockChain, m *event.TypeMux) * func (api *DownloaderAPI) eventLoop() { var ( sub = api.mux.Subscribe(StartEvent{}) - syncSubscriptions = make(map[chan interface{}]struct{}) + syncSubscriptions = make(map[chan any]struct{}) checkInterval = time.Second * 60 checkTimer = time.NewTimer(checkInterval) @@ -143,7 +143,7 @@ func (api *DownloaderAPI) Syncing(ctx context.Context) (*rpc.Subscription, error rpcSub := notifier.CreateSubscription() go func() { - statuses := make(chan interface{}) + statuses := make(chan any) sub := api.SubscribeSyncStatus(statuses) defer sub.Unsubscribe() @@ -168,15 +168,15 @@ type SyncingResult struct { // uninstallSyncSubscriptionRequest uninstalls a syncing subscription in the API event loop. type uninstallSyncSubscriptionRequest struct { - c chan interface{} - uninstalled chan interface{} + c chan any + uninstalled chan any } // SyncStatusSubscription represents a syncing subscription. type SyncStatusSubscription struct { - api *DownloaderAPI // register subscription in event loop of this api instance - c chan interface{} // channel where events are broadcasted to - unsubOnce sync.Once // make sure unsubscribe logic is executed once + api *DownloaderAPI // register subscription in event loop of this api instance + c chan any // channel where events are broadcasted to + unsubOnce sync.Once // make sure unsubscribe logic is executed once } // Unsubscribe uninstalls the subscription from the DownloadAPI event loop. @@ -184,7 +184,7 @@ type SyncStatusSubscription struct { // after this method returns. func (s *SyncStatusSubscription) Unsubscribe() { s.unsubOnce.Do(func() { - req := uninstallSyncSubscriptionRequest{s.c, make(chan interface{})} + req := uninstallSyncSubscriptionRequest{s.c, make(chan any)} s.api.uninstallSyncSubscription <- &req for { @@ -201,7 +201,7 @@ func (s *SyncStatusSubscription) Unsubscribe() { // SubscribeSyncStatus creates a subscription that will broadcast new synchronisation updates. // The given channel must receive interface values, the result can either be a SyncingResult or false. -func (api *DownloaderAPI) SubscribeSyncStatus(status chan interface{}) *SyncStatusSubscription { +func (api *DownloaderAPI) SubscribeSyncStatus(status chan any) *SyncStatusSubscription { api.installSyncSubscription <- status return &SyncStatusSubscription{api: api, c: status} } diff --git a/eth/downloader/queue.go b/eth/downloader/queue.go index 76a14345e5..6280a88151 100644 --- a/eth/downloader/queue.go +++ b/eth/downloader/queue.go @@ -355,15 +355,15 @@ func (q *queue) Results(block bool) []*fetchResult { return results } -func (q *queue) Stats() []interface{} { +func (q *queue) Stats() []any { q.lock.RLock() defer q.lock.RUnlock() return q.stats() } -func (q *queue) stats() []interface{} { - return []interface{}{ +func (q *queue) stats() []any { + return []any{ "receiptTasks", q.receiptTaskQueue.Size(), "blockTasks", q.blockTaskQueue.Size(), "itemSize", q.resultSize, @@ -536,7 +536,7 @@ func (q *queue) ExpireReceipts(peer string) int { // Note, this method expects the queue lock to be already held. The reason the // lock is not obtained in here is that the parameters already need to access // the queue, so they already need a lock anyway. -func (q *queue) expire(peer string, pendPool map[string]*fetchRequest, taskQueue interface{}) int { +func (q *queue) expire(peer string, pendPool map[string]*fetchRequest, taskQueue any) int { // Retrieve the request being expired and log an error if it's non-existent, // as there's no order of events that should lead to such expirations. req := pendPool[peer] diff --git a/eth/downloader/skeleton.go b/eth/downloader/skeleton.go index e693bfc066..5a4f27ad9a 100644 --- a/eth/downloader/skeleton.go +++ b/eth/downloader/skeleton.go @@ -1125,7 +1125,7 @@ func (s *skeleton) processResponse(res *headerResponse) (linked bool, merged boo // the syncer's internal state is corrupted. Do try to fix it, but // be very vocal about the fault. default: - var context []interface{} + var context []any for i := range s.progress.Subchains[1:] { context = append(context, fmt.Sprintf("stale_head_%d", i+1)) diff --git a/eth/ethconfig/gen_config.go b/eth/ethconfig/gen_config.go index 97c5db3ecd..27a322ab6d 100644 --- a/eth/ethconfig/gen_config.go +++ b/eth/ethconfig/gen_config.go @@ -15,7 +15,7 @@ import ( ) // MarshalTOML marshals as TOML. -func (c Config) MarshalTOML() (interface{}, error) { +func (c Config) MarshalTOML() (any, error) { type Config struct { Genesis *core.Genesis `toml:",omitempty"` NetworkId uint64 @@ -119,7 +119,7 @@ func (c Config) MarshalTOML() (interface{}, error) { } // UnmarshalTOML unmarshals from TOML. -func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { +func (c *Config) UnmarshalTOML(unmarshal func(any) error) error { type Config struct { Genesis *core.Genesis `toml:",omitempty"` NetworkId *uint64 diff --git a/eth/fetcher/tx_fetcher_test.go b/eth/fetcher/tx_fetcher_test.go index d6d5a8692e..b4eebb3b0e 100644 --- a/eth/fetcher/tx_fetcher_test.go +++ b/eth/fetcher/tx_fetcher_test.go @@ -80,7 +80,7 @@ type isUnderpriced int // runner. type txFetcherTest struct { init func() *TxFetcher - steps []interface{} + steps []any } // Tests that transaction announcements with associated metadata are added to a @@ -99,7 +99,7 @@ func TestTransactionFetcherWaiting(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Initial announcement to get something into the waitlist doTxNotify{peer: "A", hashes: []common.Hash{{0x01}, {0x02}}, types: []byte{types.LegacyTxType, types.LegacyTxType}, sizes: []uint32{111, 222}}, isWaiting(map[string][]announce{ @@ -301,7 +301,7 @@ func TestTransactionFetcherSkipWaiting(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{ peer: "A", @@ -391,7 +391,7 @@ func TestTransactionFetcherSingletonRequesting(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{{0x01}, {0x02}}, types: []byte{types.LegacyTxType, types.LegacyTxType}, sizes: []uint32{111, 222}}, isWaiting(map[string][]announce{ @@ -499,7 +499,7 @@ func TestTransactionFetcherFailedRescheduling(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{{0x01}, {0x02}}, types: []byte{types.LegacyTxType, types.LegacyTxType}, sizes: []uint32{111, 222}}, isWaiting(map[string][]announce{ @@ -582,7 +582,7 @@ func TestTransactionFetcherCleanup(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, isWaiting(map[string][]announce{ @@ -626,7 +626,7 @@ func TestTransactionFetcherCleanupEmpty(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, isWaiting(map[string][]announce{ @@ -669,7 +669,7 @@ func TestTransactionFetcherMissingRescheduling(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0], testTxsHashes[1], testTxsHashes[2]}, @@ -730,7 +730,7 @@ func TestTransactionFetcherMissingCleanup(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0], testTxsHashes[1]}, @@ -779,7 +779,7 @@ func TestTransactionFetcherBroadcasts(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Set up three transactions to be in different stats, waiting, queued and fetching doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, doWait{time: txArriveTimeout, step: true}, @@ -833,7 +833,7 @@ func TestTransactionFetcherWaitTimerResets(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ doTxNotify{peer: "A", hashes: []common.Hash{{0x01}}, types: []byte{types.LegacyTxType}, sizes: []uint32{111}}, isWaiting(map[string][]announce{ "A": { @@ -905,7 +905,7 @@ func TestTransactionFetcherTimeoutRescheduling(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Push an initial announcement through to the scheduled stage doTxNotify{ peer: "A", @@ -981,7 +981,7 @@ func TestTransactionFetcherTimeoutTimerResets(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ doTxNotify{peer: "A", hashes: []common.Hash{{0x01}}, types: []byte{types.LegacyTxType}, sizes: []uint32{111}}, doWait{time: txArriveTimeout, step: true}, doTxNotify{peer: "B", hashes: []common.Hash{{0x02}}, types: []byte{types.LegacyTxType}, sizes: []uint32{222}}, @@ -1059,7 +1059,7 @@ func TestTransactionFetcherRateLimiting(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Announce all the transactions, wait a bit and ensure only a small // percentage gets requested doTxNotify{peer: "A", hashes: hashes, types: ts, sizes: sizes}, @@ -1089,7 +1089,7 @@ func TestTransactionFetcherBandwidthLimiting(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Announce mid size transactions from A to verify that multiple // ones can be piled into a single request. doTxNotify{peer: "A", @@ -1206,7 +1206,7 @@ func TestTransactionFetcherDoSProtection(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Announce half of the transaction and wait for them to be scheduled doTxNotify{peer: "A", hashes: hashesA[:maxTxAnnounces/2], types: typesA[:maxTxAnnounces/2], sizes: sizesA[:maxTxAnnounces/2]}, doTxNotify{peer: "B", hashes: hashesB[:maxTxAnnounces/2-1], types: typesB[:maxTxAnnounces/2-1], sizes: sizesB[:maxTxAnnounces/2-1]}, @@ -1285,7 +1285,7 @@ func TestTransactionFetcherUnderpricedDedup(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Deliver a transaction through the fetcher, but reject as underpriced doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0], testTxsHashes[1]}, @@ -1340,7 +1340,7 @@ func TestTransactionFetcherUnderpricedDoSProtection(t *testing.T) { }) } // Generate a set of steps to announce and deliver the entire set of transactions - var steps []interface{} + var steps []any for i := 0; i < maxTxUnderpricedSetSize/maxTxRetrievals; i++ { steps = append(steps, doTxNotify{ peer: "A", @@ -1380,7 +1380,7 @@ func TestTransactionFetcherUnderpricedDoSProtection(t *testing.T) { nil, ) }, - steps: append(steps, []interface{}{ + steps: append(steps, []any{ // The preparation of the test has already been done in `steps`, add the last check doTxNotify{ peer: "A", @@ -1408,7 +1408,7 @@ func TestTransactionFetcherOutOfBoundDeliveries(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Deliver something out of the blue isWaiting(nil), isScheduled{nil, nil, nil}, @@ -1467,7 +1467,7 @@ func TestTransactionFetcherDrop(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Set up a few hashes into various stages doTxNotify{peer: "A", hashes: []common.Hash{{0x01}}, types: []byte{types.LegacyTxType}, sizes: []uint32{111}}, doWait{time: txArriveTimeout, step: true}, @@ -1541,7 +1541,7 @@ func TestTransactionFetcherDropRescheduling(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Set up a few hashes into various stages doTxNotify{peer: "A", hashes: []common.Hash{{0x01}}, types: []byte{types.LegacyTxType}, sizes: []uint32{111}}, doWait{time: txArriveTimeout, step: true}, @@ -1587,7 +1587,7 @@ func TestInvalidAnnounceMetadata(t *testing.T) { func(peer string) { drop <- peer }, ) }, - steps: []interface{}{ + steps: []any{ // Initial announcement to get something into the waitlist doTxNotify{ peer: "A", @@ -1670,7 +1670,7 @@ func TestTransactionFetcherFuzzCrash01(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Get a transaction into fetching mode and make it dangling with a broadcast doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, doWait{time: txArriveTimeout, step: true}, @@ -1698,7 +1698,7 @@ func TestTransactionFetcherFuzzCrash02(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Get a transaction into fetching mode and make it dangling with a broadcast doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, doWait{time: txArriveTimeout, step: true}, @@ -1728,7 +1728,7 @@ func TestTransactionFetcherFuzzCrash03(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Get a transaction into fetching mode and make it dangling with a broadcast doTxNotify{ peer: "A", @@ -1770,7 +1770,7 @@ func TestTransactionFetcherFuzzCrash04(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Get a transaction into fetching mode and make it dangling with a broadcast doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, doWait{time: txArriveTimeout, step: true}, @@ -1800,7 +1800,7 @@ func TestBlobTransactionAnnounce(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ // Initial announcement to get something into the waitlist doTxNotify{peer: "A", hashes: []common.Hash{{0x01}, {0x02}}, types: []byte{types.LegacyTxType, types.LegacyTxType}, sizes: []uint32{111, 222}}, isWaiting(map[string][]announce{ @@ -1870,7 +1870,7 @@ func TestTransactionFetcherDropAlternates(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ doTxNotify{peer: "A", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, doWait{time: txArriveTimeout, step: true}, doTxNotify{peer: "B", hashes: []common.Hash{testTxsHashes[0]}, types: []byte{testTxs[0].Type()}, sizes: []uint32{uint32(testTxs[0].Size())}}, @@ -1926,7 +1926,7 @@ func TestTransactionFetcherWrongMetadata(t *testing.T) { nil, ) }, - steps: []interface{}{ + steps: []any{ doTxNotify{peer: "A", hashes: []common.Hash{{0x01}, {0x02}}, types: []byte{0xff, types.LegacyTxType}, sizes: []uint32{111, 222}}, isWaiting(map[string][]announce{ "A": { diff --git a/eth/filters/api.go b/eth/filters/api.go index 4ed7e5be0a..b12f982122 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -365,7 +365,7 @@ func (api *FilterAPI) TransactionReceipts(ctx context.Context, filter *Transacti case receiptsWithTxs := <-matchedReceipts: if len(receiptsWithTxs) > 0 { // Convert to the same format as eth_getTransactionReceipt - marshaledReceipts := make([]map[string]interface{}, len(receiptsWithTxs)) + marshaledReceipts := make([]map[string]any, len(receiptsWithTxs)) for i, receiptWithTx := range receiptsWithTxs { marshaledReceipts[i] = ethapi.MarshalReceipt( receiptWithTx.Receipt, @@ -546,7 +546,7 @@ func (api *FilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Lo // // For pending transaction and block filters the result is []common.Hash. // (pending)Log filters return []Log. -func (api *FilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) { +func (api *FilterAPI) GetFilterChanges(id rpc.ID) (any, error) { api.filtersMu.Lock() defer api.filtersMu.Unlock() @@ -589,7 +589,7 @@ func (api *FilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) { } } - return []interface{}{}, errFilterNotFound + return []any{}, errFilterNotFound } // returnHashes is a helper that will return an empty hash array case the given hash array is nil, @@ -616,8 +616,8 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { BlockHash *common.Hash `json:"blockHash"` FromBlock *rpc.BlockNumber `json:"fromBlock"` ToBlock *rpc.BlockNumber `json:"toBlock"` - Addresses interface{} `json:"address"` - Topics []interface{} `json:"topics"` + Addresses any `json:"address"` + Topics []any `json:"topics"` } var raw input @@ -646,7 +646,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { if raw.Addresses != nil { // raw.Address can contain a single address or an array of addresses switch rawAddr := raw.Addresses.(type) { - case []interface{}: + case []any: for i, addr := range rawAddr { if strAddr, ok := addr.(string); ok { addr, err := decodeAddress(strAddr) @@ -689,7 +689,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error { } args.Topics[i] = []common.Hash{top} - case []interface{}: + case []any: // or case e.g. [null, "topic0", "topic1"] if len(topic) > maxSubTopics { return errExceedMaxTopics diff --git a/eth/handler_eth.go b/eth/handler_eth.go index 11742b14ad..47d41f9ce4 100644 --- a/eth/handler_eth.go +++ b/eth/handler_eth.go @@ -39,7 +39,7 @@ func (h *ethHandler) RunPeer(peer *eth.Peer, hand eth.Handler) error { } // PeerInfo retrieves all known `eth` information about a peer. -func (h *ethHandler) PeerInfo(id enode.ID) interface{} { +func (h *ethHandler) PeerInfo(id enode.ID) any { if p := h.peers.peer(id.String()); p != nil { return p.info() } diff --git a/eth/handler_eth_test.go b/eth/handler_eth_test.go index 1343cae03e..575ed0734f 100644 --- a/eth/handler_eth_test.go +++ b/eth/handler_eth_test.go @@ -47,7 +47,7 @@ func (h *testEthHandler) Chain() *core.BlockChain { panic("no backi func (h *testEthHandler) TxPool() eth.TxPool { panic("no backing tx pool") } func (h *testEthHandler) AcceptTxs() bool { return true } func (h *testEthHandler) RunPeer(*eth.Peer, eth.Handler) error { panic("not used in tests") } -func (h *testEthHandler) PeerInfo(enode.ID) interface{} { panic("not used in tests") } +func (h *testEthHandler) PeerInfo(enode.ID) any { panic("not used in tests") } func (h *testEthHandler) Handle(peer *eth.Peer, packet eth.Packet) error { switch packet := packet.(type) { diff --git a/eth/handler_snap.go b/eth/handler_snap.go index 767416ffd6..ce8477178e 100644 --- a/eth/handler_snap.go +++ b/eth/handler_snap.go @@ -34,7 +34,7 @@ func (h *snapHandler) RunPeer(peer *snap.Peer, hand snap.Handler) error { } // PeerInfo retrieves all known `snap` information about a peer. -func (h *snapHandler) PeerInfo(id enode.ID) interface{} { +func (h *snapHandler) PeerInfo(id enode.ID) any { if p := h.peers.peer(id.String()); p != nil { if p.snapExt != nil { return p.snapExt.info() diff --git a/eth/protocols/eth/dispatcher.go b/eth/protocols/eth/dispatcher.go index cba40596fc..e6ab52ecd1 100644 --- a/eth/protocols/eth/dispatcher.go +++ b/eth/protocols/eth/dispatcher.go @@ -47,9 +47,9 @@ type Request struct { sink chan *Response // Channel to deliver the response on cancel chan struct{} // Channel to cancel requests ahead of time - code uint64 // Message code of the request packet - want uint64 // Message code of the response packet - data interface{} // Data content of the request packet + code uint64 // Message code of the request packet + want uint64 // Message code of the response packet + data any // Data content of the request packet Peer string // Demultiplexer if cross-peer requests are batched together Sent time.Time // Timestamp when the request was sent @@ -101,8 +101,8 @@ type Response struct { code uint64 // Response packet type to cross validate with request Req *Request // Original request to cross-reference with - Res interface{} // Remote response for the request query - Meta interface{} // Metadata generated locally on the receiver thread + Res any // Remote response for the request query + Meta any // Metadata generated locally on the receiver thread Time time.Duration // Time it took for the request to be served Done chan error // Channel to signal message handling to the reader } @@ -138,7 +138,7 @@ func (p *Peer) dispatchRequest(req *Request) error { // dispatchResponse fulfils a pending request and delivers it to the requested // sink. -func (p *Peer) dispatchResponse(res *Response, metadata func() interface{}) error { +func (p *Peer) dispatchResponse(res *Response, metadata func() any) error { resOp := &response{ res: res, fail: make(chan error), diff --git a/eth/protocols/eth/handler.go b/eth/protocols/eth/handler.go index 2467e0c713..876495f820 100644 --- a/eth/protocols/eth/handler.go +++ b/eth/protocols/eth/handler.go @@ -75,7 +75,7 @@ type Backend interface { RunPeer(peer *Peer, handler Handler) error // PeerInfo retrieves all known `eth` information about a peer. - PeerInfo(id enode.ID) interface{} + PeerInfo(id enode.ID) any // Handle is a callback to be invoked when a data packet is received from // the remote peer. Only packets not consumed by the protocol handler will @@ -113,10 +113,10 @@ func MakeProtocols(backend Backend, network uint64, disc enode.Iterator) []p2p.P return Handle(backend, peer) }) }, - NodeInfo: func() interface{} { + NodeInfo: func() any { return nodeInfo(backend.Chain(), network) }, - PeerInfo: func(id enode.ID) interface{} { + PeerInfo: func(id enode.ID) any { return backend.PeerInfo(id) }, DialCandidates: disc, @@ -162,7 +162,7 @@ func Handle(backend Backend, peer *Peer) error { type msgHandler func(backend Backend, msg Decoder, peer *Peer) error type Decoder interface { - Decode(val interface{}) error + Decode(val any) error Time() time.Time } diff --git a/eth/protocols/eth/handler_test.go b/eth/protocols/eth/handler_test.go index 65c491f815..be434f1d78 100644 --- a/eth/protocols/eth/handler_test.go +++ b/eth/protocols/eth/handler_test.go @@ -159,7 +159,7 @@ func (b *testBackend) RunPeer(peer *Peer, handler Handler) error { // is omitted and we will just give control back to the handler. return handler(peer) } -func (b *testBackend) PeerInfo(enode.ID) interface{} { panic("not implemented") } +func (b *testBackend) PeerInfo(enode.ID) any { panic("not implemented") } func (b *testBackend) AcceptTxs() bool { return true @@ -554,7 +554,7 @@ type decoder struct { msg []byte } -func (d decoder) Decode(val interface{}) error { +func (d decoder) Decode(val any) error { buffer := bytes.NewBuffer(d.msg) s := rlp.NewStream(buffer, uint64(len(d.msg))) return s.Decode(val) diff --git a/eth/protocols/eth/handlers.go b/eth/protocols/eth/handlers.go index aad3353d88..fc920e97df 100644 --- a/eth/protocols/eth/handlers.go +++ b/eth/protocols/eth/handlers.go @@ -356,7 +356,7 @@ func handleBlockHeaders(backend Backend, msg Decoder, peer *Peer) error { if err := msg.Decode(res); err != nil { return err } - metadata := func() interface{} { + metadata := func() any { hashes := make([]common.Hash, len(res.BlockHeadersRequest)) for i, header := range res.BlockHeadersRequest { hashes[i] = header.Hash() @@ -376,7 +376,7 @@ func handleBlockBodies(backend Backend, msg Decoder, peer *Peer) error { if err := msg.Decode(res); err != nil { return err } - metadata := func() interface{} { + metadata := func() any { var ( txsHashes = make([]common.Hash, len(res.BlockBodiesResponse)) uncleHashes = make([]common.Hash, len(res.BlockBodiesResponse)) @@ -412,7 +412,7 @@ func handleReceipts[L ReceiptsList](backend Backend, msg Decoder, peer *Peer) er res.List[i].setBuffers(buffers) } - metadata := func() interface{} { + metadata := func() any { hasher := trie.NewStackTrie(nil) hashes := make([]common.Hash, len(res.List)) for i := range res.List { diff --git a/eth/protocols/eth/handshake_test.go b/eth/protocols/eth/handshake_test.go index 2fab3ea5a8..f568fc4873 100644 --- a/eth/protocols/eth/handshake_test.go +++ b/eth/protocols/eth/handshake_test.go @@ -44,11 +44,11 @@ func testHandshake(t *testing.T, protocol uint) { ) tests := []struct { code uint64 - data interface{} + data any want error }{ { - code: TransactionsMsg, data: []interface{}{}, + code: TransactionsMsg, data: []any{}, want: errNoStatusMsg, }, { diff --git a/eth/protocols/eth/protocol_test.go b/eth/protocols/eth/protocol_test.go index 8a2559a6c5..fcd2a01ee3 100644 --- a/eth/protocols/eth/protocol_test.go +++ b/eth/protocols/eth/protocol_test.go @@ -199,7 +199,7 @@ func TestMessages(t *testing.T) { } for i, tc := range []struct { - message interface{} + message any want []byte }{ { diff --git a/eth/protocols/snap/handler.go b/eth/protocols/snap/handler.go index 3249720f90..aa449c2bbf 100644 --- a/eth/protocols/snap/handler.go +++ b/eth/protocols/snap/handler.go @@ -76,7 +76,7 @@ type Backend interface { RunPeer(peer *Peer, handler Handler) error // PeerInfo retrieves all known `snap` information about a peer. - PeerInfo(id enode.ID) interface{} + PeerInfo(id enode.ID) any // Handle is a callback to be invoked when a data packet is received from // the remote peer. Only packets not consumed by the protocol handler will @@ -97,10 +97,10 @@ func MakeProtocols(backend Backend) []p2p.Protocol { return Handle(backend, peer) }) }, - NodeInfo: func() interface{} { + NodeInfo: func() any { return nodeInfo(backend.Chain()) }, - PeerInfo: func(id enode.ID) interface{} { + PeerInfo: func(id enode.ID) any { return backend.PeerInfo(id) }, Attributes: []enr.Entry{&enrEntry{}}, diff --git a/eth/protocols/snap/handler_fuzzing_test.go b/eth/protocols/snap/handler_fuzzing_test.go index 4930ae9ae6..34e0d53470 100644 --- a/eth/protocols/snap/handler_fuzzing_test.go +++ b/eth/protocols/snap/handler_fuzzing_test.go @@ -60,7 +60,7 @@ func FuzzTrieNodes(f *testing.F) { }) } -func doFuzz(input []byte, obj interface{}, code int) { +func doFuzz(input []byte, obj any, code int) { bc := getChain() defer bc.Stop() fuzz.NewFromGoFuzz(input).Fuzz(obj) @@ -136,10 +136,10 @@ type dummyBackend struct { chain *core.BlockChain } -func (d *dummyBackend) Chain() *core.BlockChain { return d.chain } -func (d *dummyBackend) RunPeer(*Peer, Handler) error { return nil } -func (d *dummyBackend) PeerInfo(enode.ID) interface{} { return "Foo" } -func (d *dummyBackend) Handle(*Peer, Packet) error { return nil } +func (d *dummyBackend) Chain() *core.BlockChain { return d.chain } +func (d *dummyBackend) RunPeer(*Peer, Handler) error { return nil } +func (d *dummyBackend) PeerInfo(enode.ID) any { return "Foo" } +func (d *dummyBackend) Handle(*Peer, Packet) error { return nil } type dummyRW struct { code uint64 diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 5f2f16627a..c76b6856ee 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -181,7 +181,7 @@ type StdTraceConfig struct { // txTraceResult is the result of a single transaction trace. type txTraceResult struct { TxHash common.Hash `json:"txHash"` // transaction hash - Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer + Result any `json:"result,omitempty"` // Trace results produced by the tracer Error string `json:"error,omitempty"` // Trace failure produced by the tracer } @@ -863,7 +863,7 @@ func containsTx(block *types.Block, hash common.Hash) bool { // TraceTransaction returns the structured logs created during the execution of EVM // and returns them as a JSON object. -func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) { +func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (any, error) { found, _, blockHash, blockNumber, index := api.backend.GetCanonicalTransaction(hash) if !found { // Warn in case tx indexer is not done. @@ -911,7 +911,7 @@ func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config * // after executing the specified block. However, if a transaction index is provided, // the trace will be conducted on the state after executing the specified transaction // within the specified block. -func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) { +func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (any, error) { // Try to retrieve the specified block var ( err error @@ -1006,7 +1006,7 @@ func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, bloc // traceTx configures a new tracer according to the provided configuration, and // executes the given message in the provided environment. The return value will // be tracer dependent. -func (api *API) traceTx(ctx context.Context, tx *types.Transaction, message *core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig, precompiles vm.PrecompiledContracts) (interface{}, error) { +func (api *API) traceTx(ctx context.Context, tx *types.Transaction, message *core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig, precompiles vm.PrecompiledContracts) (any, error) { var ( tracer *Tracer err error diff --git a/eth/tracers/internal/tracetest/flat_calltrace_test.go b/eth/tracers/internal/tracetest/flat_calltrace_test.go index 1882ef315e..8610a2db07 100644 --- a/eth/tracers/internal/tracetest/flat_calltrace_test.go +++ b/eth/tracers/internal/tracetest/flat_calltrace_test.go @@ -176,7 +176,7 @@ func testFlatCallTracer(tracerName string, dirPath string, t *testing.T) { // jsonEqualFlat is similar to reflect.DeepEqual, but does a 'bounce' via json prior to // comparison -func jsonEqualFlat(x, y interface{}) bool { +func jsonEqualFlat(x, y any) bool { xTrace := new([]flatCallTrace) yTrace := new([]flatCallTrace) if xj, err := json.Marshal(x); err == nil { diff --git a/eth/tracers/internal/tracetest/prestate_test.go b/eth/tracers/internal/tracetest/prestate_test.go index 456d962c69..6eaba422d0 100644 --- a/eth/tracers/internal/tracetest/prestate_test.go +++ b/eth/tracers/internal/tracetest/prestate_test.go @@ -46,7 +46,7 @@ type account struct { // prestateTracerTest defines a single test to check the stateDiff tracer against. type prestateTracerTest struct { tracerTestEnv - Result interface{} `json:"result"` + Result any `json:"result"` } func TestPrestateTracerLegacy(t *testing.T) { diff --git a/eth/tracers/internal/tracetest/supply_test.go b/eth/tracers/internal/tracetest/supply_test.go index 2b5a8212aa..7516283a08 100644 --- a/eth/tracers/internal/tracetest/supply_test.go +++ b/eth/tracers/internal/tracetest/supply_test.go @@ -643,7 +643,7 @@ func testSupplyTracer(t *testing.T, genesis *core.Genesis, gen func(b *core.Bloc return output, chain, nil } -func compareAsJSON(t *testing.T, expected interface{}, actual interface{}) { +func compareAsJSON(t *testing.T, expected any, actual any) { t.Helper() want, err := json.Marshal(expected) if err != nil { diff --git a/ethclient/ethclient.go b/ethclient/ethclient.go index 6f2fb5ebc8..b1a14c76b5 100644 --- a/ethclient/ethclient.go +++ b/ethclient/ethclient.go @@ -138,7 +138,7 @@ type rpcBlock struct { Withdrawals []*types.Withdrawal `json:"withdrawals,omitempty"` } -func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) { +func (ec *Client) getBlock(ctx context.Context, method string, args ...any) (*types.Block, error) { var raw json.RawMessage err := ec.c.CallContext(ctx, &raw, method, args...) if err != nil { @@ -186,7 +186,7 @@ func (ec *Client) getBlock(ctx context.Context, method string, args ...interface for i := range reqs { reqs[i] = rpc.BatchElem{ Method: "eth_getUncleByBlockHashAndIndex", - Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))}, + Args: []any{body.Hash, hexutil.EncodeUint64(uint64(i))}, Result: &uncles[i], } } @@ -774,8 +774,8 @@ func toBlockNumArg(number *big.Int) string { return fmt.Sprintf("", number) } -func toCallArg(msg ethereum.CallMsg) interface{} { - arg := map[string]interface{}{ +func toCallArg(msg ethereum.CallMsg) any { + arg := map[string]any{ "from": msg.From, "to": msg.To, } @@ -886,9 +886,9 @@ func (s SimulateBlock) MarshalJSON() ([]byte, error) { type Alias struct { BlockOverrides *ethereum.BlockOverrides `json:"blockOverrides,omitempty"` StateOverrides map[common.Address]ethereum.OverrideAccount `json:"stateOverrides,omitempty"` - Calls []interface{} `json:"calls"` + Calls []any `json:"calls"` } - calls := make([]interface{}, len(s.Calls)) + calls := make([]any, len(s.Calls)) for i, call := range s.Calls { calls[i] = toCallArg(call) } diff --git a/ethclient/gethclient/gethclient.go b/ethclient/gethclient/gethclient.go index c2013bca2c..4432e2b8da 100644 --- a/ethclient/gethclient/gethclient.go +++ b/ethclient/gethclient/gethclient.go @@ -244,8 +244,8 @@ func toBlockNumArg(number *big.Int) string { return fmt.Sprintf("", number) } -func toCallArg(msg ethereum.CallMsg) interface{} { - arg := map[string]interface{}{ +func toCallArg(msg ethereum.CallMsg) any { + arg := map[string]any{ "from": msg.From, "to": msg.To, } diff --git a/ethclient/types_test.go b/ethclient/types_test.go index dcb9a579b7..2d25f72c71 100644 --- a/ethclient/types_test.go +++ b/ethclient/types_test.go @@ -38,7 +38,7 @@ func TestToFilterArg(t *testing.T) { for _, testCase := range []struct { name string input ethereum.FilterQuery - output interface{} + output any err error }{ { @@ -61,7 +61,7 @@ func TestToFilterArg(t *testing.T) { ToBlock: big.NewInt(2), Topics: [][]common.Hash{}, }, - map[string]interface{}{ + map[string]any{ "address": addresses, "fromBlock": "0x1", "toBlock": "0x2", @@ -75,7 +75,7 @@ func TestToFilterArg(t *testing.T) { Addresses: addresses, Topics: [][]common.Hash{}, }, - map[string]interface{}{ + map[string]any{ "address": addresses, "fromBlock": "0x0", "toBlock": "latest", @@ -91,7 +91,7 @@ func TestToFilterArg(t *testing.T) { ToBlock: big.NewInt(-1), Topics: [][]common.Hash{}, }, - map[string]interface{}{ + map[string]any{ "address": addresses, "fromBlock": "pending", "toBlock": "pending", @@ -106,7 +106,7 @@ func TestToFilterArg(t *testing.T) { BlockHash: &blockHash, Topics: [][]common.Hash{}, }, - map[string]interface{}{ + map[string]any{ "address": addresses, "blockHash": blockHash, "topics": [][]common.Hash{}, diff --git a/ethdb/database.go b/ethdb/database.go index 534fcad4fc..499ce248ba 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -172,7 +172,7 @@ type AncientWriter interface { // AncientWriteOp is given to the function argument of ModifyAncients. type AncientWriteOp interface { // Append adds an RLP-encoded item. - Append(kind string, number uint64, item interface{}) error + Append(kind string, number uint64, item any) error // AppendRaw adds an item without RLP-encoding it. AppendRaw(kind string, number uint64, item []byte) error diff --git a/ethdb/leveldb/leveldb.go b/ethdb/leveldb/leveldb.go index b6c93907b1..c9b05bd227 100644 --- a/ethdb/leveldb/leveldb.go +++ b/ethdb/leveldb/leveldb.go @@ -113,7 +113,7 @@ func NewCustom(file string, namespace string, customize func(options *opt.Option options := configureOptions(customize) logger := log.New("database", file) usedCache := options.GetBlockCacheCapacity() + options.GetWriteBuffer()*2 - logCtx := []interface{}{"cache", common.StorageSize(usedCache), "handles", options.GetOpenFilesCacheCapacity()} + logCtx := []any{"cache", common.StorageSize(usedCache), "handles", options.GetOpenFilesCacheCapacity()} if options.ReadOnly { logCtx = append(logCtx, "readonly", "true") } diff --git a/ethdb/pebble/pebble.go b/ethdb/pebble/pebble.go index 800559ab4b..004276444d 100644 --- a/ethdb/pebble/pebble.go +++ b/ethdb/pebble/pebble.go @@ -165,13 +165,13 @@ func (d *Database) onWriteStallEnd() { // TODO(karalabe): Remove when Pebble sets this as the default. type panicLogger struct{} -func (l panicLogger) Infof(format string, args ...interface{}) { +func (l panicLogger) Infof(format string, args ...any) { } -func (l panicLogger) Errorf(format string, args ...interface{}) { +func (l panicLogger) Errorf(format string, args ...any) { } -func (l panicLogger) Fatalf(format string, args ...interface{}) { +func (l panicLogger) Fatalf(format string, args ...any) { panic(fmt.Errorf("fatal: "+format, args...)) } diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index c17e225165..7982e4dd8a 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -126,7 +126,7 @@ func newConnectionWrapper(conn *websocket.Conn) *connWrapper { } // WriteJSON wraps corresponding method on the websocket but is safe for concurrent calling -func (w *connWrapper) WriteJSON(v interface{}) error { +func (w *connWrapper) WriteJSON(v any) error { w.wlock.Lock() defer w.wlock.Unlock() @@ -134,7 +134,7 @@ func (w *connWrapper) WriteJSON(v interface{}) error { } // ReadJSON wraps corresponding method on the websocket but is safe for concurrent calling -func (w *connWrapper) ReadJSON(v interface{}) error { +func (w *connWrapper) ReadJSON(v any) error { w.rlock.Lock() defer w.rlock.Unlock() @@ -395,7 +395,7 @@ func (s *Service) readLoop(conn *connWrapper) { continue } // Not a system ping, try to decode an actual state message - var msg map[string][]interface{} + var msg map[string][]any if err := json.Unmarshal(blob, &msg); err != nil { log.Warn("Failed to decode stats server message", "err", err) return @@ -425,7 +425,7 @@ func (s *Service) readLoop(conn *connWrapper) { // If the message is a history request, forward to the event processor if len(msg["emit"]) == 2 && command == "history" { // Make sure the request is valid and doesn't crash us - request, ok := msg["emit"][1].(map[string]interface{}) + request, ok := msg["emit"][1].(map[string]any) if !ok { log.Warn("Invalid stats history request", "msg", msg["emit"][1]) select { @@ -434,7 +434,7 @@ func (s *Service) readLoop(conn *connWrapper) { } continue } - list, ok := request["list"].([]interface{}) + list, ok := request["list"].([]any) if !ok { log.Warn("Invalid stats history block list", "list", request["list"]) return @@ -513,7 +513,7 @@ func (s *Service) login(conn *connWrapper) error { }, Secret: s.pass, } - login := map[string][]interface{}{ + login := map[string][]any{ "emit": {"hello", auth}, } if err := conn.WriteJSON(login); err != nil { @@ -552,7 +552,7 @@ func (s *Service) reportLatency(conn *connWrapper) error { // Send the current time to the ethstats server start := time.Now() - ping := map[string][]interface{}{ + ping := map[string][]any{ "emit": {"node-ping", map[string]string{ "id": s.node, "clientTime": start.String(), @@ -577,7 +577,7 @@ func (s *Service) reportLatency(conn *connWrapper) error { // Send back the measured latency log.Trace("Sending measured latency to ethstats", "latency", latency) - stats := map[string][]interface{}{ + stats := map[string][]any{ "emit": {"latency", map[string]string{ "id": s.node, "latency": latency, @@ -636,11 +636,11 @@ func (s *Service) reportNewPayload(conn *connWrapper, ev core.NewPayloadEvent) e log.Trace("Sending new payload to ethstats", "number", details.Number, "hash", details.Hash) - stats := map[string]interface{}{ + stats := map[string]any{ "id": s.node, "block": details, } - report := map[string][]interface{}{ + report := map[string][]any{ "emit": {"block_new_payload", stats}, } return conn.WriteJSON(report) @@ -658,11 +658,11 @@ func (s *Service) reportBlock(conn *connWrapper, header *types.Header) error { // Assemble the block report and send it to the server log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash) - stats := map[string]interface{}{ + stats := map[string]any{ "id": s.node, "block": details, } - report := map[string][]interface{}{ + report := map[string][]any{ "emit": {"block", stats}, } return conn.WriteJSON(report) @@ -758,11 +758,11 @@ func (s *Service) reportHistory(conn *connWrapper, list []uint64) error { } else { log.Trace("No history to send to stats server") } - stats := map[string]interface{}{ + stats := map[string]any{ "id": s.node, "history": history, } - report := map[string][]interface{}{ + report := map[string][]any{ "emit": {"history", stats}, } return conn.WriteJSON(report) @@ -781,13 +781,13 @@ func (s *Service) reportPending(conn *connWrapper) error { // Assemble the transaction stats and send it to the server log.Trace("Sending pending transactions to ethstats", "count", pending) - stats := map[string]interface{}{ + stats := map[string]any{ "id": s.node, "stats": &pendStats{ Pending: pending, }, } - report := map[string][]interface{}{ + report := map[string][]any{ "emit": {"pending", stats}, } return conn.WriteJSON(report) @@ -827,7 +827,7 @@ func (s *Service) reportStats(conn *connWrapper) error { // Assemble the node stats and send it to the server log.Trace("Sending node details to ethstats") - stats := map[string]interface{}{ + stats := map[string]any{ "id": s.node, "stats": &nodeStats{ Active: true, @@ -837,7 +837,7 @@ func (s *Service) reportStats(conn *connWrapper) error { Uptime: 100, }, } - report := map[string][]interface{}{ + report := map[string][]any{ "emit": {"stats", stats}, } return conn.WriteJSON(report) diff --git a/event/event.go b/event/event.go index 25a2c2e457..6d6495deea 100644 --- a/event/event.go +++ b/event/event.go @@ -28,7 +28,7 @@ import ( // TypeMuxEvent is a time-tagged notification pushed to subscribers. type TypeMuxEvent struct { Time time.Time - Data interface{} + Data any } // A TypeMux dispatches events to registered receivers. Receivers can be @@ -50,7 +50,7 @@ var ErrMuxClosed = errors.New("event: mux closed") // Subscribe creates a subscription for events of the given types. The // subscription's channel is closed when it is unsubscribed // or the mux is closed. -func (mux *TypeMux) Subscribe(types ...interface{}) *TypeMuxSubscription { +func (mux *TypeMux) Subscribe(types ...any) *TypeMuxSubscription { sub := newsub(mux) mux.mutex.Lock() defer mux.mutex.Unlock() @@ -80,7 +80,7 @@ func (mux *TypeMux) Subscribe(types ...interface{}) *TypeMuxSubscription { // Post sends an event to all receivers registered for the given type. // It returns ErrMuxClosed if the mux has been stopped. -func (mux *TypeMux) Post(ev interface{}) error { +func (mux *TypeMux) Post(ev any) error { event := &TypeMuxEvent{ Time: time.Now(), Data: ev, diff --git a/event/event_test.go b/event/event_test.go index 84b37eca3b..1dde96a4a8 100644 --- a/event/event_test.go +++ b/event/event_test.go @@ -201,7 +201,7 @@ func BenchmarkPostConcurrent(b *testing.B) { // for comparison func BenchmarkChanSend(b *testing.B) { - c := make(chan interface{}) + c := make(chan any) defer close(c) closed := make(chan struct{}) go func() { diff --git a/event/feed.go b/event/feed.go index d94bd820f0..7fac9abf5a 100644 --- a/event/feed.go +++ b/event/feed.go @@ -33,10 +33,10 @@ var errBadChannel = errors.New("event: Subscribe argument does not have sendable // // The zero value is ready to use. type Feed struct { - once sync.Once // ensures that init only runs once - sendLock chan struct{} // sendLock has a one-element buffer and is empty when held.It protects sendCases. - removeSub chan interface{} // interrupts Send - sendCases caseList // the active set of select cases used by Send + once sync.Once // ensures that init only runs once + sendLock chan struct{} // sendLock has a one-element buffer and is empty when held.It protects sendCases. + removeSub chan any // interrupts Send + sendCases caseList // the active set of select cases used by Send // The inbox holds newly subscribed channels until they are added to sendCases. mu sync.Mutex @@ -59,7 +59,7 @@ func (e feedTypeError) Error() string { func (f *Feed) init(etype reflect.Type) { f.etype = etype - f.removeSub = make(chan interface{}) + f.removeSub = make(chan any) f.sendLock = make(chan struct{}, 1) f.sendLock <- struct{}{} f.sendCases = caseList{{Chan: reflect.ValueOf(f.removeSub), Dir: reflect.SelectRecv}} @@ -70,7 +70,7 @@ func (f *Feed) init(etype reflect.Type) { // // The channel should have ample buffer space to avoid blocking other subscribers. // Slow subscribers are not dropped. -func (f *Feed) Subscribe(channel interface{}) Subscription { +func (f *Feed) Subscribe(channel any) Subscription { chanval := reflect.ValueOf(channel) chantyp := chanval.Type() if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.SendDir == 0 { @@ -117,7 +117,7 @@ func (f *Feed) remove(sub *feedSub) { // Send delivers to all subscribed channels simultaneously. // It returns the number of subscribers that the value was sent to. -func (f *Feed) Send(value interface{}) (nsent int) { +func (f *Feed) Send(value any) (nsent int) { rvalue := reflect.ValueOf(value) f.once.Do(func() { f.init(rvalue.Type()) }) @@ -200,7 +200,7 @@ func (sub *feedSub) Err() <-chan error { type caseList []reflect.SelectCase // find returns the index of a case containing the given channel. -func (cs caseList) find(channel interface{}) int { +func (cs caseList) find(channel any) int { for i, cas := range cs { if cas.Chan.Interface() == channel { return i diff --git a/graphql/graphql.go b/graphql/graphql.go index 244d6926a2..21a1f96ad3 100644 --- a/graphql/graphql.go +++ b/graphql/graphql.go @@ -50,7 +50,7 @@ type Long int64 func (b Long) ImplementsGraphQLType(name string) bool { return name == "Long" } // UnmarshalGraphQL unmarshals the provided GraphQL query data. -func (b *Long) UnmarshalGraphQL(input interface{}) error { +func (b *Long) UnmarshalGraphQL(input any) error { var err error switch input := input.(type) { case string: diff --git a/graphql/graphql_test.go b/graphql/graphql_test.go index ca864d5fb2..a2784d8b27 100644 --- a/graphql/graphql_test.go +++ b/graphql/graphql_test.go @@ -356,7 +356,7 @@ func TestGraphQLConcurrentResolvers(t *testing.T) { want: `{"block":{"account":{"balance":"0x0","transactionCount":"0x0","code":"0x"}}}`, }, } { - res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) + res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]any{}) if res.Errors != nil { t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) } @@ -416,7 +416,7 @@ func TestWithdrawals(t *testing.T) { want: `{"block":{"withdrawalsRoot":"0x8418fc1a48818928f6692f148e9b10e99a88edc093b095cb8ca97950284b553d","withdrawals":[{"validator":"0x5","amount":"0xa"}]}}`, }, } { - res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]interface{}{}) + res := handler.Schema.Exec(context.Background(), tt.body, "", map[string]any{}) if res.Errors != nil { t.Fatalf("failed to execute query for testcase #%d: %v", i, res.Errors) } diff --git a/graphql/service.go b/graphql/service.go index 9381a51da6..370959b7bc 100644 --- a/graphql/service.go +++ b/graphql/service.go @@ -41,9 +41,9 @@ type handler struct { func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { var params struct { - Query string `json:"query"` - OperationName string `json:"operationName"` - Variables map[string]interface{} `json:"variables"` + Query string `json:"query"` + OperationName string `json:"operationName"` + Variables map[string]any `json:"variables"` } if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) diff --git a/interfaces.go b/interfaces.go index 21d42c6d34..9caed1d3bb 100644 --- a/interfaces.go +++ b/interfaces.go @@ -324,7 +324,7 @@ func (a OverrideAccount) MarshalJSON() ([]byte, error) { Nonce hexutil.Uint64 `json:"nonce,omitempty"` Code string `json:"code,omitempty"` Balance *hexutil.Big `json:"balance,omitempty"` - State interface{} `json:"state,omitempty"` + State any `json:"state,omitempty"` StateDiff map[common.Hash]common.Hash `json:"stateDiff,omitempty"` } diff --git a/internal/build/util.go b/internal/build/util.go index 6e6632c750..bddb89fb03 100644 --- a/internal/build/util.go +++ b/internal/build/util.go @@ -127,18 +127,18 @@ func readGitFile(file string) string { } // Render renders the given template file into outputFile. -func Render(templateFile, outputFile string, outputPerm os.FileMode, x interface{}) { +func Render(templateFile, outputFile string, outputPerm os.FileMode, x any) { tpl := template.Must(template.ParseFiles(templateFile)) render(tpl, outputFile, outputPerm, x) } // RenderString renders the given template string into outputFile. -func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x interface{}) { +func RenderString(templateContent, outputFile string, outputPerm os.FileMode, x any) { tpl := template.Must(template.New("").Parse(templateContent)) render(tpl, outputFile, outputPerm, x) } -func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x interface{}) { +func render(tpl *template.Template, outputFile string, outputPerm os.FileMode, x any) { if err := os.MkdirAll(filepath.Dir(outputFile), 0755); err != nil { log.Fatal(err) } diff --git a/internal/cmdtest/test_cmd.go b/internal/cmdtest/test_cmd.go index f6f0425598..316c0b590d 100644 --- a/internal/cmdtest/test_cmd.go +++ b/internal/cmdtest/test_cmd.go @@ -35,7 +35,7 @@ import ( "github.com/ethereum/go-ethereum/internal/reexec" ) -func NewTestCmd(t *testing.T, data interface{}) *TestCmd { +func NewTestCmd(t *testing.T, data any) *TestCmd { return &TestCmd{T: t, Data: data} } @@ -44,7 +44,7 @@ type TestCmd struct { *testing.T Func template.FuncMap - Data interface{} + Data any Cleanup func() cmd *exec.Cmd @@ -89,9 +89,9 @@ func (tt *TestCmd) InputLine(s string) string { return "" } -func (tt *TestCmd) SetTemplateFunc(name string, fn interface{}) { +func (tt *TestCmd) SetTemplateFunc(name string, fn any) { if tt.Func == nil { - tt.Func = make(map[string]interface{}) + tt.Func = make(map[string]any) } tt.Func[name] = fn } diff --git a/internal/debug/flags.go b/internal/debug/flags.go index 30b0ddb3be..fdf1157439 100644 --- a/internal/debug/flags.go +++ b/internal/debug/flags.go @@ -191,7 +191,7 @@ func Setup(ctx *cli.Context) error { return fmt.Errorf("failed to initiatilize file logger: %v", err) } } - context := []interface{}{"rotate", rotation} + context := []any{"rotate", rotation} if len(logFmtFlag) > 0 { context = append(context, "format", logFmtFlag) } else { diff --git a/internal/debug/loudpanic.go b/internal/debug/loudpanic.go index a7296e7b3f..1f9af9b26f 100644 --- a/internal/debug/loudpanic.go +++ b/internal/debug/loudpanic.go @@ -19,7 +19,7 @@ package debug import "runtime/debug" // LoudPanic panics in a way that gets all goroutine stacks printed on stderr. -func LoudPanic(x interface{}) { +func LoudPanic(x any) { debug.SetTraceback("all") panic(x) } diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index eb437201d5..df0bd70a24 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -146,7 +146,7 @@ func (api *EthereumAPI) BlobBaseFee(ctx context.Context) *hexutil.Big { // - highestBlock: block number of the highest block header this node has received from peers // - pulledStates: number of state entries processed until now // - knownStates: number of known state entries that still need to be pulled -func (api *EthereumAPI) Syncing(ctx context.Context) (interface{}, error) { +func (api *EthereumAPI) Syncing(ctx context.Context) (any, error) { progress := api.b.SyncProgress(ctx) // Return not syncing if the synchronisation already completed @@ -154,7 +154,7 @@ func (api *EthereumAPI) Syncing(ctx context.Context) (interface{}, error) { return false, nil } // Otherwise gather the block sync stats - return map[string]interface{}{ + return map[string]any{ "startingBlock": hexutil.Uint64(progress.StartingBlock), "currentBlock": hexutil.Uint64(progress.CurrentBlock), "highestBlock": hexutil.Uint64(progress.HighestBlock), @@ -466,7 +466,7 @@ func decodeStorageKey(s string) (h common.Hash, inputLength int, err error) { // - When number is -2 the chain latest header is returned. // - When number is -3 the chain finalized header is returned. // - When number is -4 the chain safe header is returned. -func (api *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) { +func (api *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]any, error) { header, err := api.b.HeaderByNumber(ctx, number) if header != nil && err == nil { response := RPCMarshalHeader(header) @@ -482,7 +482,7 @@ func (api *BlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.Bloc } // GetHeaderByHash returns the requested header by hash. -func (api *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} { +func (api *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]any { header, _ := api.b.HeaderByHash(ctx, hash) if header != nil { return RPCMarshalHeader(header) @@ -497,7 +497,7 @@ func (api *BlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) // - When number is -4 the chain safe block is returned. // - When fullTx is true all transactions in the block are returned, otherwise // only the transaction hash is returned. -func (api *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { +func (api *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]any, error) { block, err := api.b.BlockByNumber(ctx, number) if block != nil && err == nil { response := RPCMarshalBlock(block, true, fullTx, api.b.ChainConfig()) @@ -514,7 +514,7 @@ func (api *BlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.Block // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full // detail, otherwise only the transaction hash is returned. -func (api *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) { +func (api *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]any, error) { block, err := api.b.BlockByHash(ctx, hash) if block != nil { return RPCMarshalBlock(block, true, fullTx, api.b.ChainConfig()), nil @@ -523,7 +523,7 @@ func (api *BlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, } // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. -func (api *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { +func (api *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]any, error) { block, err := api.b.BlockByNumber(ctx, blockNr) if block != nil { uncles := block.Uncles() @@ -538,7 +538,7 @@ func (api *BlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blo } // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. -func (api *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { +func (api *BlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]any, error) { block, err := api.b.BlockByHash(ctx, blockHash) if block != nil { uncles := block.Uncles() @@ -599,7 +599,7 @@ func (api *BlockChainAPI) GetStorageAt(ctx context.Context, address common.Addre } // GetBlockReceipts returns the block receipts for the given block hash or number or tag. -func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]interface{}, error) { +func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash) ([]map[string]any, error) { var ( err error block *types.Block @@ -627,7 +627,7 @@ func (api *BlockChainAPI) GetBlockReceipts(ctx context.Context, blockNrOrHash rp // Derive the sender. signer := types.MakeSigner(api.b.ChainConfig(), block.Number(), block.Time()) - result := make([]map[string]interface{}, len(receipts)) + result := make([]map[string]any, len(receipts)) for i, receipt := range receipts { result[i] = MarshalReceipt(receipt, block.Hash(), block.NumberU64(), signer, txs[i], i) } @@ -904,8 +904,8 @@ func (api *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, } // RPCMarshalHeader converts the given header to the RPC output . -func RPCMarshalHeader(head *types.Header) map[string]interface{} { - result := map[string]interface{}{ +func RPCMarshalHeader(head *types.Header) map[string]any { + result := map[string]any{ "number": (*hexutil.Big)(head.Number), "hash": head.Hash(), "parentHash": head.ParentHash, @@ -947,21 +947,21 @@ func RPCMarshalHeader(head *types.Header) map[string]interface{} { // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain // transaction hashes. -func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) map[string]interface{} { +func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) map[string]any { fields := RPCMarshalHeader(block.Header()) fields["size"] = hexutil.Uint64(block.Size()) if inclTx { - formatTx := func(idx int, tx *types.Transaction) interface{} { + formatTx := func(idx int, tx *types.Transaction) any { return tx.Hash() } if fullTx { - formatTx = func(idx int, tx *types.Transaction) interface{} { + formatTx = func(idx int, tx *types.Transaction) any { return newRPCTransactionFromBlockIndex(block, uint64(idx), config) } } txs := block.Transactions() - transactions := make([]interface{}, len(txs)) + transactions := make([]any, len(txs)) for i, tx := range txs { transactions[i] = formatTx(i, tx) } @@ -1475,7 +1475,7 @@ func (api *TransactionAPI) GetRawTransactionByHash(ctx context.Context, hash com } // GetTransactionReceipt returns the transaction receipt for the given transaction hash. -func (api *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { +func (api *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]any, error) { found, tx, blockHash, blockNumber, index := api.b.GetCanonicalTransaction(hash) if !found { // Make sure indexer is done. @@ -1494,10 +1494,10 @@ func (api *TransactionAPI) GetTransactionReceipt(ctx context.Context, hash commo } // MarshalReceipt marshals a transaction receipt into a JSON object. -func MarshalReceipt(receipt *types.Receipt, blockHash common.Hash, blockNumber uint64, signer types.Signer, tx *types.Transaction, txIndex int) map[string]interface{} { +func MarshalReceipt(receipt *types.Receipt, blockHash common.Hash, blockNumber uint64, signer types.Signer, tx *types.Transaction, txIndex int) map[string]any { from, _ := types.Sender(signer, tx) - fields := map[string]interface{}{ + fields := map[string]any{ "blockHash": blockHash, "blockNumber": hexutil.Uint64(blockNumber), "transactionHash": tx.Hash(), @@ -1670,7 +1670,7 @@ func (api *TransactionAPI) SendRawTransaction(ctx context.Context, input hexutil // SendRawTransactionSync will add the signed transaction to the transaction pool // and wait until the transaction has been included in a block and return the receipt, or the timeout. -func (api *TransactionAPI) SendRawTransactionSync(ctx context.Context, input hexutil.Bytes, timeoutMs *hexutil.Uint64) (map[string]interface{}, error) { +func (api *TransactionAPI) SendRawTransactionSync(ctx context.Context, input hexutil.Bytes, timeoutMs *hexutil.Uint64) (map[string]any, error) { tx := new(types.Transaction) if err := tx.UnmarshalBinary(input); err != nil { return nil, err diff --git a/internal/ethapi/api_test.go b/internal/ethapi/api_test.go index aaa002b5ec..57c2f01963 100644 --- a/internal/ethapi/api_test.go +++ b/internal/ethapi/api_test.go @@ -3427,7 +3427,7 @@ func TestRPCGetBlockOrHeader(t *testing.T) { for i, tt := range testSuite { var ( - result map[string]interface{} + result map[string]any err error rpc string ) @@ -3613,7 +3613,7 @@ func TestRPCGetTransactionReceipt(t *testing.T) { for i, tt := range testSuite { var ( - result interface{} + result any err error ) result, err = api.GetTransactionReceipt(context.Background(), tt.txHash) @@ -3716,7 +3716,7 @@ func TestRPCGetBlockReceipts(t *testing.T) { for i, tt := range testSuite { var ( - result interface{} + result any err error ) result, err = api.GetBlockReceipts(context.Background(), tt.test) @@ -3728,7 +3728,7 @@ func TestRPCGetBlockReceipts(t *testing.T) { } } -func testRPCResponseWithFile(t *testing.T, testid int, result interface{}, rpc string, file string) { +func testRPCResponseWithFile(t *testing.T, testid int, result any, rpc string, file string) { data, err := json.MarshalIndent(result, "", " ") if err != nil { t.Errorf("test %d: json marshal error", testid) @@ -4038,7 +4038,7 @@ func TestSendRawTransactionSync_Timeout(t *testing.T) { // assert error shape & data (hash) var de interface { ErrorCode() int - ErrorData() interface{} + ErrorData() any } if !errors.As(err, &de) { t.Fatalf("expected data error with code/data, got %T %v", err, err) diff --git a/internal/ethapi/errors.go b/internal/ethapi/errors.go index 30711a0167..c389d49104 100644 --- a/internal/ethapi/errors.go +++ b/internal/ethapi/errors.go @@ -46,7 +46,7 @@ func (e *revertError) ErrorCode() int { } // ErrorData returns the hex encoded revert reason. -func (e *revertError) ErrorData() interface{} { +func (e *revertError) ErrorData() any { return e.reason } @@ -83,7 +83,7 @@ func (e *TxIndexingError) ErrorCode() int { } // ErrorData returns the hex encoded revert reason. -func (e *TxIndexingError) ErrorData() interface{} { return "transaction indexing is in progress" } +func (e *TxIndexingError) ErrorData() any { return "transaction indexing is in progress" } type callError struct { Message string `json:"message"` @@ -176,6 +176,6 @@ type blockGasLimitReachedError struct{ message string } func (e *blockGasLimitReachedError) Error() string { return e.message } func (e *blockGasLimitReachedError) ErrorCode() int { return errCodeBlockGasLimitReached } -func (e *txSyncTimeoutError) Error() string { return e.msg } -func (e *txSyncTimeoutError) ErrorCode() int { return errCodeTxSyncTimeout } -func (e *txSyncTimeoutError) ErrorData() interface{} { return e.hash.Hex() } +func (e *txSyncTimeoutError) Error() string { return e.msg } +func (e *txSyncTimeoutError) ErrorCode() int { return errCodeTxSyncTimeout } +func (e *txSyncTimeoutError) ErrorData() any { return e.hash.Hex() } diff --git a/internal/jsre/jsre.go b/internal/jsre/jsre.go index 4512115f16..d9d881e675 100644 --- a/internal/jsre/jsre.go +++ b/internal/jsre/jsre.go @@ -186,15 +186,15 @@ loop: select { case timer := <-ready: // execute callback, remove/reschedule the timer - var arguments []interface{} + var arguments []any if len(timer.call.Arguments) > 2 { tmp := timer.call.Arguments[2:] - arguments = make([]interface{}, 2+len(tmp)) + arguments = make([]any, 2+len(tmp)) for i, value := range tmp { arguments[i+2] = value } } else { - arguments = make([]interface{}, 1) + arguments = make([]any, 1) } arguments[0] = timer.call.Arguments[0] call, isFunc := goja.AssertFunction(timer.call.Arguments[0]) @@ -287,7 +287,7 @@ func (re *JSRE) Run(code string) (v goja.Value, err error) { } // Set assigns value v to a variable in the JS environment. -func (re *JSRE) Set(ns string, v interface{}) (err error) { +func (re *JSRE) Set(ns string, v any) (err error) { re.Do(func(vm *goja.Runtime) { vm.Set(ns, v) }) return err } @@ -317,7 +317,7 @@ func (re *JSRE) Evaluate(code string, w io.Writer) { } // Interrupt stops the current JS evaluation. -func (re *JSRE) Interrupt(v interface{}) { +func (re *JSRE) Interrupt(v any) { done := make(chan bool) noop := func(*goja.Runtime) {} diff --git a/internal/jsre/pretty.go b/internal/jsre/pretty.go index bd772b4927..4dd8582b5b 100644 --- a/internal/jsre/pretty.go +++ b/internal/jsre/pretty.go @@ -253,7 +253,7 @@ func iterOwnKeys(vm *goja.Runtime, obj *goja.Object, f func(string)) { } gv := rv.Export() switch gv := gv.(type) { - case []interface{}: + case []any: for _, v := range gv { f(v.(string)) } diff --git a/internal/testlog/testlog.go b/internal/testlog/testlog.go index 8a3ea85438..40bdb5c4bc 100644 --- a/internal/testlog/testlog.go +++ b/internal/testlog/testlog.go @@ -104,13 +104,13 @@ func (l *logger) Handler() slog.Handler { return l.l.Handler() } -func (l *logger) Write(level slog.Level, msg string, ctx ...interface{}) {} +func (l *logger) Write(level slog.Level, msg string, ctx ...any) {} func (l *logger) Enabled(ctx context.Context, level slog.Level) bool { return l.l.Enabled(ctx, level) } -func (l *logger) Trace(msg string, ctx ...interface{}) { +func (l *logger) Trace(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -118,7 +118,7 @@ func (l *logger) Trace(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Log(level slog.Level, msg string, ctx ...interface{}) { +func (l *logger) Log(level slog.Level, msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -126,7 +126,7 @@ func (l *logger) Log(level slog.Level, msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Debug(msg string, ctx ...interface{}) { +func (l *logger) Debug(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -134,7 +134,7 @@ func (l *logger) Debug(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Info(msg string, ctx ...interface{}) { +func (l *logger) Info(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -142,7 +142,7 @@ func (l *logger) Info(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Warn(msg string, ctx ...interface{}) { +func (l *logger) Warn(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -150,7 +150,7 @@ func (l *logger) Warn(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Error(msg string, ctx ...interface{}) { +func (l *logger) Error(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -158,7 +158,7 @@ func (l *logger) Error(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) Crit(msg string, ctx ...interface{}) { +func (l *logger) Crit(msg string, ctx ...any) { l.t.Helper() l.mu.Lock() defer l.mu.Unlock() @@ -166,12 +166,12 @@ func (l *logger) Crit(msg string, ctx ...interface{}) { l.flush() } -func (l *logger) With(ctx ...interface{}) log.Logger { +func (l *logger) With(ctx ...any) log.Logger { newLogger := l.l.With(ctx...) return &logger{l.t, newLogger, l.mu, newLogger.Handler().(*bufHandler)} } -func (l *logger) New(ctx ...interface{}) log.Logger { +func (l *logger) New(ctx ...any) log.Logger { return l.With(ctx...) } diff --git a/internal/utesting/utesting.go b/internal/utesting/utesting.go index 8260de1d76..784011cfe9 100644 --- a/internal/utesting/utesting.go +++ b/internal/utesting/utesting.go @@ -297,7 +297,7 @@ func (t *T) Failed() bool { // Log formats its arguments using default formatting, analogous to Println, and records // the text in the error log. -func (t *T) Log(vs ...interface{}) { +func (t *T) Log(vs ...any) { t.mu.Lock() defer t.mu.Unlock() fmt.Fprintln(t.output, vs...) @@ -305,7 +305,7 @@ func (t *T) Log(vs ...interface{}) { // Logf formats its arguments according to the format, analogous to Printf, and records // the text in the error log. A final newline is added if not provided. -func (t *T) Logf(format string, vs ...interface{}) { +func (t *T) Logf(format string, vs ...any) { t.mu.Lock() defer t.mu.Unlock() if len(format) == 0 || format[len(format)-1] != '\n' { @@ -315,25 +315,25 @@ func (t *T) Logf(format string, vs ...interface{}) { } // Error is equivalent to Log followed by Fail. -func (t *T) Error(vs ...interface{}) { +func (t *T) Error(vs ...any) { t.Log(vs...) t.Fail() } // Errorf is equivalent to Logf followed by Fail. -func (t *T) Errorf(format string, vs ...interface{}) { +func (t *T) Errorf(format string, vs ...any) { t.Logf(format, vs...) t.Fail() } // Fatal is equivalent to Log followed by FailNow. -func (t *T) Fatal(vs ...interface{}) { +func (t *T) Fatal(vs ...any) { t.Log(vs...) t.FailNow() } // Fatalf is equivalent to Logf followed by FailNow. -func (t *T) Fatalf(format string, vs ...interface{}) { +func (t *T) Fatalf(format string, vs ...any) { t.Logf(format, vs...) t.FailNow() } diff --git a/log/logger.go b/log/logger.go index 016856c834..d63ffa8b9b 100644 --- a/log/logger.go +++ b/log/logger.go @@ -105,31 +105,31 @@ func LevelString(l slog.Level) string { // A Logger writes key/value pairs to a Handler type Logger interface { // With returns a new Logger that has this logger's attributes plus the given attributes - With(ctx ...interface{}) Logger + With(ctx ...any) Logger // New returns a new Logger that has this logger's attributes plus the given attributes. Identical to 'With'. - New(ctx ...interface{}) Logger + New(ctx ...any) Logger // Log logs a message at the specified level with context key/value pairs - Log(level slog.Level, msg string, ctx ...interface{}) + Log(level slog.Level, msg string, ctx ...any) // Trace log a message at the trace level with context key/value pairs - Trace(msg string, ctx ...interface{}) + Trace(msg string, ctx ...any) // Debug logs a message at the debug level with context key/value pairs - Debug(msg string, ctx ...interface{}) + Debug(msg string, ctx ...any) // Info logs a message at the info level with context key/value pairs - Info(msg string, ctx ...interface{}) + Info(msg string, ctx ...any) // Warn logs a message at the warn level with context key/value pairs - Warn(msg string, ctx ...interface{}) + Warn(msg string, ctx ...any) // Error logs a message at the error level with context key/value pairs - Error(msg string, ctx ...interface{}) + Error(msg string, ctx ...any) // Crit logs a message at the crit level with context key/value pairs, and exits - Crit(msg string, ctx ...interface{}) + Crit(msg string, ctx ...any) // Write logs a message at the specified level Write(level slog.Level, msg string, attrs ...any) @@ -177,11 +177,11 @@ func (l *logger) Log(level slog.Level, msg string, attrs ...any) { l.Write(level, msg, attrs...) } -func (l *logger) With(ctx ...interface{}) Logger { +func (l *logger) With(ctx ...any) Logger { return &logger{l.inner.With(ctx...)} } -func (l *logger) New(ctx ...interface{}) Logger { +func (l *logger) New(ctx ...any) Logger { return l.With(ctx...) } @@ -190,15 +190,15 @@ func (l *logger) Enabled(ctx context.Context, level slog.Level) bool { return l.inner.Enabled(ctx, level) } -func (l *logger) Trace(msg string, ctx ...interface{}) { +func (l *logger) Trace(msg string, ctx ...any) { l.Write(LevelTrace, msg, ctx...) } -func (l *logger) Debug(msg string, ctx ...interface{}) { +func (l *logger) Debug(msg string, ctx ...any) { l.Write(slog.LevelDebug, msg, ctx...) } -func (l *logger) Info(msg string, ctx ...interface{}) { +func (l *logger) Info(msg string, ctx ...any) { l.Write(slog.LevelInfo, msg, ctx...) } @@ -206,11 +206,11 @@ func (l *logger) Warn(msg string, ctx ...any) { l.Write(slog.LevelWarn, msg, ctx...) } -func (l *logger) Error(msg string, ctx ...interface{}) { +func (l *logger) Error(msg string, ctx ...any) { l.Write(slog.LevelError, msg, ctx...) } -func (l *logger) Crit(msg string, ctx ...interface{}) { +func (l *logger) Crit(msg string, ctx ...any) { l.Write(LevelCrit, msg, ctx...) os.Exit(1) } diff --git a/log/root.go b/log/root.go index c09a36b114..b79b5a1df8 100644 --- a/log/root.go +++ b/log/root.go @@ -47,7 +47,7 @@ func Root() Logger { // log.Trace("msg") // log.Trace("msg", "key1", val1) // log.Trace("msg", "key1", val1, "key2", val2) -func Trace(msg string, ctx ...interface{}) { +func Trace(msg string, ctx ...any) { Root().Write(LevelTrace, msg, ctx...) } @@ -60,7 +60,7 @@ func Trace(msg string, ctx ...interface{}) { // log.Debug("msg") // log.Debug("msg", "key1", val1) // log.Debug("msg", "key1", val1, "key2", val2) -func Debug(msg string, ctx ...interface{}) { +func Debug(msg string, ctx ...any) { Root().Write(slog.LevelDebug, msg, ctx...) } @@ -73,7 +73,7 @@ func Debug(msg string, ctx ...interface{}) { // log.Info("msg") // log.Info("msg", "key1", val1) // log.Info("msg", "key1", val1, "key2", val2) -func Info(msg string, ctx ...interface{}) { +func Info(msg string, ctx ...any) { Root().Write(slog.LevelInfo, msg, ctx...) } @@ -86,7 +86,7 @@ func Info(msg string, ctx ...interface{}) { // log.Warn("msg") // log.Warn("msg", "key1", val1) // log.Warn("msg", "key1", val1, "key2", val2) -func Warn(msg string, ctx ...interface{}) { +func Warn(msg string, ctx ...any) { Root().Write(slog.LevelWarn, msg, ctx...) } @@ -99,7 +99,7 @@ func Warn(msg string, ctx ...interface{}) { // log.Error("msg") // log.Error("msg", "key1", val1) // log.Error("msg", "key1", val1, "key2", val2) -func Error(msg string, ctx ...interface{}) { +func Error(msg string, ctx ...any) { Root().Write(slog.LevelError, msg, ctx...) } @@ -112,13 +112,13 @@ func Error(msg string, ctx ...interface{}) { // log.Crit("msg") // log.Crit("msg", "key1", val1) // log.Crit("msg", "key1", val1, "key2", val2) -func Crit(msg string, ctx ...interface{}) { +func Crit(msg string, ctx ...any) { Root().Write(LevelCrit, msg, ctx...) os.Exit(1) } // New returns a new logger with the given context. // New is a convenient alias for Root().New -func New(ctx ...interface{}) Logger { +func New(ctx ...any) Logger { return Root().With(ctx...) } diff --git a/metrics/exp/exp.go b/metrics/exp/exp.go index 85cabca6b1..41ef84b855 100644 --- a/metrics/exp/exp.go +++ b/metrics/exp/exp.go @@ -187,7 +187,7 @@ func (exp *exp) publishResettingTimer(name string, metric *metrics.ResettingTime } func (exp *exp) syncToExpvar() { - exp.registry.Each(func(name string, i interface{}) { + exp.registry.Each(func(name string, i any) { switch i := i.(type) { case *metrics.Counter: exp.publishCounter(name, i.Snapshot()) diff --git a/metrics/influxdb/influxdb.go b/metrics/influxdb/influxdb.go index 11f6c3ad22..df4414be3d 100644 --- a/metrics/influxdb/influxdb.go +++ b/metrics/influxdb/influxdb.go @@ -6,36 +6,36 @@ import ( "github.com/ethereum/go-ethereum/metrics" ) -func readMeter(namespace, name string, i interface{}) (string, map[string]interface{}) { +func readMeter(namespace, name string, i any) (string, map[string]any) { switch metric := i.(type) { case *metrics.Counter: measurement := fmt.Sprintf("%s%s.count", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "value": metric.Snapshot().Count(), } return measurement, fields case *metrics.CounterFloat64: measurement := fmt.Sprintf("%s%s.count", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "value": metric.Snapshot().Count(), } return measurement, fields case *metrics.Gauge: measurement := fmt.Sprintf("%s%s.gauge", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "value": metric.Snapshot().Value(), } return measurement, fields case *metrics.GaugeFloat64: measurement := fmt.Sprintf("%s%s.gauge", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "value": metric.Snapshot().Value(), } return measurement, fields case *metrics.GaugeInfo: ms := metric.Snapshot() measurement := fmt.Sprintf("%s%s.gauge", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "value": ms.Value().String(), } return measurement, fields @@ -46,7 +46,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf } ps := ms.Percentiles([]float64{0.25, 0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) measurement := fmt.Sprintf("%s%s.histogram", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "count": ms.Count(), "max": ms.Max(), "mean": ms.Mean(), @@ -65,7 +65,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf case *metrics.Meter: ms := metric.Snapshot() measurement := fmt.Sprintf("%s%s.meter", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "count": ms.Count(), "m1": ms.Rate1(), "m5": ms.Rate5(), @@ -78,7 +78,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf ps := ms.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) measurement := fmt.Sprintf("%s%s.timer", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "count": ms.Count(), "max": ms.Max(), "mean": ms.Mean(), @@ -104,7 +104,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf } ps := ms.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) measurement := fmt.Sprintf("%s%s.timer", namespace, name) - fields := map[string]interface{}{ + fields := map[string]any{ "count": ms.Count(), "max": ms.Max(), "mean": ms.Mean(), diff --git a/metrics/influxdb/influxdbv1.go b/metrics/influxdb/influxdbv1.go index ac58280803..2c3a8c693f 100644 --- a/metrics/influxdb/influxdbv1.go +++ b/metrics/influxdb/influxdbv1.go @@ -133,7 +133,7 @@ func (r *reporter) send(tstamp int64) error { if err != nil { return err } - r.reg.Each(func(name string, i interface{}) { + r.reg.Each(func(name string, i any) { var now time.Time if tstamp <= 0 { now = time.Now() diff --git a/metrics/influxdb/influxdbv2.go b/metrics/influxdb/influxdbv2.go index 114d57ae07..b7383e79a6 100644 --- a/metrics/influxdb/influxdbv2.go +++ b/metrics/influxdb/influxdbv2.go @@ -77,7 +77,7 @@ func (r *v2Reporter) run() { // send sends the measurements. If provided tstamp is >0, it is used. Otherwise, // a 'fresh' timestamp is used. func (r *v2Reporter) send(tstamp int64) { - r.reg.Each(func(name string, i interface{}) { + r.reg.Each(func(name string, i any) { var now time.Time if tstamp <= 0 { now = time.Now() diff --git a/metrics/log.go b/metrics/log.go index 08f3effb81..545b832f63 100644 --- a/metrics/log.go +++ b/metrics/log.go @@ -5,7 +5,7 @@ import ( ) type Logger interface { - Printf(format string, v ...interface{}) + Printf(format string, v ...any) } func Log(r Registry, freq time.Duration, l Logger) { @@ -19,7 +19,7 @@ func LogScaled(r Registry, freq time.Duration, scale time.Duration, l Logger) { duSuffix := scale.String()[1:] for range time.Tick(freq) { - r.Each(func(name string, i interface{}) { + r.Each(func(name string, i any) { switch metric := i.(type) { case *Counter: l.Printf("counter %s\n", name) diff --git a/metrics/opentsdb.go b/metrics/opentsdb.go index 57af3d025e..c385efdc8d 100644 --- a/metrics/opentsdb.go +++ b/metrics/opentsdb.go @@ -62,7 +62,7 @@ func getShortHostname() string { func (c *OpenTSDBConfig) writeRegistry(w io.Writer, now int64, shortHostname string) { du := float64(c.DurationUnit) - c.Registry.Each(func(name string, i interface{}) { + c.Registry.Each(func(name string, i any) { switch metric := i.(type) { case *Counter: fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, metric.Snapshot().Count(), shortHostname) diff --git a/metrics/prometheus/collector.go b/metrics/prometheus/collector.go index 31b8c51b65..3684fef271 100644 --- a/metrics/prometheus/collector.go +++ b/metrics/prometheus/collector.go @@ -148,19 +148,19 @@ func (c *collector) writeGaugeInfo(name string, value metrics.GaugeInfoValue) { c.buff.WriteString(fmt.Sprintf("{%v} 1\n\n", strings.Join(kvs, ", "))) } -func (c *collector) writeGaugeCounter(name string, value interface{}) { +func (c *collector) writeGaugeCounter(name string, value any) { name = mutateKey(name) c.buff.WriteString(fmt.Sprintf(typeGaugeTpl, name)) c.buff.WriteString(fmt.Sprintf(keyValueTpl, name, value)) } -func (c *collector) writeSummaryCounter(name string, value interface{}) { +func (c *collector) writeSummaryCounter(name string, value any) { name = mutateKey(name + "_count") c.buff.WriteString(fmt.Sprintf(typeCounterTpl, name)) c.buff.WriteString(fmt.Sprintf(keyValueTpl, name, value)) } -func (c *collector) writeSummaryPercentile(name, p string, value interface{}) { +func (c *collector) writeSummaryPercentile(name, p string, value any) { name = mutateKey(name) c.buff.WriteString(fmt.Sprintf(keyQuantileTagValueTpl, name, p, value)) } diff --git a/metrics/prometheus/collector_test.go b/metrics/prometheus/collector_test.go index a8585d1226..860b01f944 100644 --- a/metrics/prometheus/collector_test.go +++ b/metrics/prometheus/collector_test.go @@ -36,7 +36,7 @@ func TestCollector(t *testing.T) { c = newCollector() want string ) - internal.ExampleMetrics().Each(func(name string, i interface{}) { + internal.ExampleMetrics().Each(func(name string, i any) { c.Add(name, i) }) if wantB, err := os.ReadFile("./testdata/prometheus.want"); err != nil { diff --git a/metrics/prometheus/prometheus.go b/metrics/prometheus/prometheus.go index dbdeae6c7f..75a0863865 100644 --- a/metrics/prometheus/prometheus.go +++ b/metrics/prometheus/prometheus.go @@ -31,7 +31,7 @@ func Handler(reg metrics.Registry) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Gather and pre-sort the metrics to avoid random listings var names []string - reg.Each(func(name string, i interface{}) { + reg.Each(func(name string, i any) { names = append(names, name) }) sort.Strings(names) diff --git a/metrics/registry.go b/metrics/registry.go index 6070f3d0e9..cee6111d8e 100644 --- a/metrics/registry.go +++ b/metrics/registry.go @@ -21,20 +21,20 @@ var ErrDuplicateMetric = errors.New("duplicate metric") type Registry interface { // Each call the given function for each registered metric. - Each(func(string, interface{})) + Each(func(string, any)) // Get the metric by the given name or nil if none is registered. - Get(string) interface{} + Get(string) any // GetAll metrics in the Registry. - GetAll() map[string]map[string]interface{} + GetAll() map[string]map[string]any // GetOrRegister returns an existing metric or registers the one returned // by the given constructor. - GetOrRegister(string, func() interface{}) interface{} + GetOrRegister(string, func() any) any // Register the given metric under the given name. - Register(string, interface{}) error + Register(string, any) error // RunHealthchecks run all registered healthchecks. RunHealthchecks() @@ -48,7 +48,7 @@ type orderedRegistry struct { } // Each call the given function for each registered metric. -func (r *orderedRegistry) Each(f func(string, interface{})) { +func (r *orderedRegistry) Each(f func(string, any)) { var names []string reg := r.registered() for name := range reg { @@ -77,14 +77,14 @@ type StandardRegistry struct { } // Each call the given function for each registered metric. -func (r *StandardRegistry) Each(f func(string, interface{})) { +func (r *StandardRegistry) Each(f func(string, any)) { for name, i := range r.registered() { f(name, i) } } // Get the metric by the given name or nil if none is registered. -func (r *StandardRegistry) Get(name string) interface{} { +func (r *StandardRegistry) Get(name string) any { item, _ := r.metrics.Load(name) return item } @@ -93,7 +93,7 @@ func (r *StandardRegistry) Get(name string) interface{} { // alternative to calling Get and Register on failure. // The interface can be the metric to register if not found in registry, // or a function returning the metric for lazy instantiation. -func (r *StandardRegistry) GetOrRegister(name string, ctor func() interface{}) interface{} { +func (r *StandardRegistry) GetOrRegister(name string, ctor func() any) any { // fast path cached, ok := r.metrics.Load(name) if ok { @@ -105,7 +105,7 @@ func (r *StandardRegistry) GetOrRegister(name string, ctor func() interface{}) i // Register the given metric under the given name. Returns a ErrDuplicateMetric // if a metric by the given name is already registered. -func (r *StandardRegistry) Register(name string, i interface{}) error { +func (r *StandardRegistry) Register(name string, i any) error { // fast path _, ok := r.metrics.Load(name) if ok { @@ -130,10 +130,10 @@ func (r *StandardRegistry) RunHealthchecks() { } // GetAll metrics in the Registry -func (r *StandardRegistry) GetAll() map[string]map[string]interface{} { - data := make(map[string]map[string]interface{}) - r.Each(func(name string, i interface{}) { - values := make(map[string]interface{}) +func (r *StandardRegistry) GetAll() map[string]map[string]any { + data := make(map[string]map[string]any) + r.Each(func(name string, i any) { + values := make(map[string]any) switch metric := i.(type) { case *Counter: values["count"] = metric.Snapshot().Count() @@ -198,7 +198,7 @@ func (r *StandardRegistry) Unregister(name string) { r.metrics.LoadAndDelete(name) } -func (r *StandardRegistry) loadOrRegister(name string, i interface{}) (interface{}, bool, bool) { +func (r *StandardRegistry) loadOrRegister(name string, i any) (any, bool, bool) { switch i.(type) { case *Counter, *CounterFloat64, *Gauge, *GaugeFloat64, *GaugeInfo, *Healthcheck, Histogram, *Meter, *Timer, *ResettingTimer: default: @@ -208,8 +208,8 @@ func (r *StandardRegistry) loadOrRegister(name string, i interface{}) (interface return item, loaded, true } -func (r *StandardRegistry) registered() map[string]interface{} { - metrics := make(map[string]interface{}) +func (r *StandardRegistry) registered() map[string]any { + metrics := make(map[string]any) r.metrics.Range(func(key, value any) bool { metrics[key.(string)] = value return true @@ -250,9 +250,9 @@ func NewPrefixedChildRegistry(parent Registry, prefix string) Registry { } // Each call the given function for each registered metric. -func (r *PrefixedRegistry) Each(fn func(string, interface{})) { - wrappedFn := func(prefix string) func(string, interface{}) { - return func(name string, iface interface{}) { +func (r *PrefixedRegistry) Each(fn func(string, any)) { + wrappedFn := func(prefix string) func(string, any) { + return func(name string, iface any) { if strings.HasPrefix(name, prefix) { fn(name, iface) } else { @@ -276,7 +276,7 @@ func findPrefix(registry Registry, prefix string) (Registry, string) { } // Get the metric by the given name or nil if none is registered. -func (r *PrefixedRegistry) Get(name string) interface{} { +func (r *PrefixedRegistry) Get(name string) any { realName := r.prefix + name return r.underlying.Get(realName) } @@ -284,13 +284,13 @@ func (r *PrefixedRegistry) Get(name string) interface{} { // GetOrRegister gets an existing metric or registers the given one. // The interface can be the metric to register if not found in registry, // or a function returning the metric for lazy instantiation. -func (r *PrefixedRegistry) GetOrRegister(name string, ctor func() interface{}) interface{} { +func (r *PrefixedRegistry) GetOrRegister(name string, ctor func() any) any { realName := r.prefix + name return r.underlying.GetOrRegister(realName, ctor) } // Register the given metric under the given name. The name will be prefixed. -func (r *PrefixedRegistry) Register(name string, metric interface{}) error { +func (r *PrefixedRegistry) Register(name string, metric any) error { realName := r.prefix + name return r.underlying.Register(realName, metric) } @@ -301,7 +301,7 @@ func (r *PrefixedRegistry) RunHealthchecks() { } // GetAll metrics in the Registry -func (r *PrefixedRegistry) GetAll() map[string]map[string]interface{} { +func (r *PrefixedRegistry) GetAll() map[string]map[string]any { return r.underlying.GetAll() } @@ -316,18 +316,18 @@ var ( ) // Each call the given function for each registered metric. -func Each(f func(string, interface{})) { +func Each(f func(string, any)) { DefaultRegistry.Each(f) } // Get the metric by the given name or nil if none is registered. -func Get(name string) interface{} { +func Get(name string) any { return DefaultRegistry.Get(name) } // GetOrRegister gets an existing metric or creates and registers a new one. Threadsafe // alternative to calling Get and Register on failure. -func GetOrRegister(name string, i func() interface{}) interface{} { +func GetOrRegister(name string, i func() any) any { return DefaultRegistry.GetOrRegister(name, i) } @@ -340,13 +340,13 @@ func getOrRegister[T any](name string, ctor func() T, r Registry) T { // Register the given metric under the given name. Returns a ErrDuplicateMetric // if a metric by the given name is already registered. -func Register(name string, i interface{}) error { +func Register(name string, i any) error { return DefaultRegistry.Register(name, i) } // MustRegister register the given metric under the given name. Panics if a metric by the // given name is already registered. -func MustRegister(name string, i interface{}) { +func MustRegister(name string, i any) { if err := Register(name, i); err != nil { panic(err) } diff --git a/metrics/registry_test.go b/metrics/registry_test.go index 6af0796da9..ccdc7dfcab 100644 --- a/metrics/registry_test.go +++ b/metrics/registry_test.go @@ -10,7 +10,7 @@ func BenchmarkRegistry(b *testing.B) { r.Register("foo", NewCounter()) b.ResetTimer() for i := 0; i < b.N; i++ { - r.Each(func(string, interface{}) {}) + r.Each(func(string, any) {}) } } @@ -42,7 +42,7 @@ func TestRegistry(t *testing.T) { r := NewRegistry() r.Register("foo", NewCounter()) i := 0 - r.Each(func(name string, iface interface{}) { + r.Each(func(name string, iface any) { i++ if name != "foo" { t.Fatal(name) @@ -56,7 +56,7 @@ func TestRegistry(t *testing.T) { } r.Unregister("foo") i = 0 - r.Each(func(string, interface{}) { i++ }) + r.Each(func(string, any) { i++ }) if i != 0 { t.Fatal(i) } @@ -71,7 +71,7 @@ func TestRegistryDuplicate(t *testing.T) { t.Fatal(err) } i := 0 - r.Each(func(name string, iface interface{}) { + r.Each(func(name string, iface any) { i++ if _, ok := iface.(*Counter); !ok { t.Fatal(iface) @@ -105,7 +105,7 @@ func TestRegistryGetOrRegister(t *testing.T) { } i := 0 - r.Each(func(name string, iface interface{}) { + r.Each(func(name string, iface any) { i++ if name != "foo" { t.Fatal(name) @@ -130,7 +130,7 @@ func TestRegistryGetOrRegisterWithLazyInstantiation(t *testing.T) { } i := 0 - r.Each(func(name string, iface interface{}) { + r.Each(func(name string, iface any) { i++ if name != "foo" { t.Fatal(name) @@ -168,7 +168,7 @@ func TestPrefixedChildRegistryGetOrRegister(t *testing.T) { _ = GetOrRegisterCounter("foo", pr) i := 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ if name != "prefix.foo" { t.Fatal(name) @@ -185,7 +185,7 @@ func TestPrefixedRegistryGetOrRegister(t *testing.T) { _ = GetOrRegisterCounter("foo", r) i := 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ if name != "prefix.foo" { t.Fatal(name) @@ -206,7 +206,7 @@ func TestPrefixedRegistryRegister(t *testing.T) { } i := 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ if name != "prefix.foo" { t.Fatal(name) @@ -223,7 +223,7 @@ func TestPrefixedRegistryUnregister(t *testing.T) { _ = r.Register("foo", NewCounter()) i := 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ if name != "prefix.foo" { t.Fatal(name) @@ -236,7 +236,7 @@ func TestPrefixedRegistryUnregister(t *testing.T) { r.Unregister("foo") i = 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ }) @@ -277,7 +277,7 @@ func TestChildPrefixedRegistryRegister(t *testing.T) { } i := 0 - r.Each(func(name string, m interface{}) { + r.Each(func(name string, m any) { i++ if name != "prefix.foo" { t.Fatal(name) @@ -303,7 +303,7 @@ func TestChildPrefixedRegistryOfChildRegister(t *testing.T) { Register("bars", c) i := 0 - r2.Each(func(name string, m interface{}) { + r2.Each(func(name string, m any) { i++ if name != "prefix.prefix2.baz" { t.Fatal(name) diff --git a/metrics/syslog.go b/metrics/syslog.go index b265328f87..a97950f5aa 100644 --- a/metrics/syslog.go +++ b/metrics/syslog.go @@ -13,7 +13,7 @@ import ( // the given syslogger. func Syslog(r Registry, d time.Duration, w *syslog.Writer) { for range time.Tick(d) { - r.Each(func(name string, i interface{}) { + r.Each(func(name string, i any) { switch metric := i.(type) { case *Counter: w.Info(fmt.Sprintf("counter %s: count: %d", name, metric.Snapshot().Count())) diff --git a/metrics/writer.go b/metrics/writer.go index 2a41f8e1fe..8679e820d1 100644 --- a/metrics/writer.go +++ b/metrics/writer.go @@ -20,7 +20,7 @@ func Write(r Registry, d time.Duration, w io.Writer) { // io.Writer. func WriteOnce(r Registry, w io.Writer) { var namedMetrics []namedMetric - r.Each(func(name string, i interface{}) { + r.Each(func(name string, i any) { namedMetrics = append(namedMetrics, namedMetric{name, i}) }) slices.SortFunc(namedMetrics, namedMetric.cmp) @@ -91,7 +91,7 @@ func WriteOnce(r Registry, w io.Writer) { type namedMetric struct { name string - m interface{} + m any } func (m namedMetric) cmp(other namedMetric) int { diff --git a/miner/ordering.go b/miner/ordering.go index bcf7af46e8..1c910c0254 100644 --- a/miner/ordering.go +++ b/miner/ordering.go @@ -70,11 +70,11 @@ func (s txByPriceAndTime) Less(i, j int) bool { } func (s txByPriceAndTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s *txByPriceAndTime) Push(x interface{}) { +func (s *txByPriceAndTime) Push(x any) { *s = append(*s, x.(*txWithMinerFee)) } -func (s *txByPriceAndTime) Pop() interface{} { +func (s *txByPriceAndTime) Pop() any { old := *s n := len(old) x := old[n-1] diff --git a/node/jwt_handler.go b/node/jwt_handler.go index 637ae19686..2ed6e9b67e 100644 --- a/node/jwt_handler.go +++ b/node/jwt_handler.go @@ -27,14 +27,14 @@ import ( const jwtExpiryTimeout = 60 * time.Second type jwtHandler struct { - keyFunc func(token *jwt.Token) (interface{}, error) + keyFunc func(token *jwt.Token) (any, error) next http.Handler } // newJWTHandler creates a http.Handler with jwt authentication support. func newJWTHandler(secret []byte, next http.Handler) http.Handler { return &jwtHandler{ - keyFunc: func(token *jwt.Token) (interface{}, error) { + keyFunc: func(token *jwt.Token) (any, error) { return secret, nil }, next: next, diff --git a/node/rpcstack.go b/node/rpcstack.go index a1cc832f9f..5609ac4eea 100644 --- a/node/rpcstack.go +++ b/node/rpcstack.go @@ -473,7 +473,7 @@ func (h *virtualHostHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } var gzPool = sync.Pool{ - New: func() interface{} { + New: func() any { w := gzip.NewWriter(io.Discard) return w }, diff --git a/node/rpcstack_test.go b/node/rpcstack_test.go index 54e58cccb2..beb60dfad5 100644 --- a/node/rpcstack_test.go +++ b/node/rpcstack_test.go @@ -324,7 +324,7 @@ func baseRpcRequest(t *testing.T, url, bodyStr string, extraHeaders ...string) * return resp } -type testClaim map[string]interface{} +type testClaim map[string]any func (testClaim) Valid() error { return nil @@ -332,7 +332,7 @@ func (testClaim) Valid() error { func TestJWT(t *testing.T) { var secret = []byte("secret") - issueToken := func(secret []byte, method jwt.SigningMethod, input map[string]interface{}) string { + issueToken := func(secret []byte, method jwt.SigningMethod, input map[string]any) string { if method == nil { method = jwt.SigningMethodHS256 } diff --git a/p2p/config_toml.go b/p2p/config_toml.go index 8a255e62fb..a19d174d24 100644 --- a/p2p/config_toml.go +++ b/p2p/config_toml.go @@ -14,7 +14,7 @@ import ( var _ = (*configMarshaling)(nil) // MarshalTOML marshals as TOML. -func (c Config) MarshalTOML() (interface{}, error) { +func (c Config) MarshalTOML() (any, error) { type Config struct { PrivateKey *ecdsa.PrivateKey `toml:"-"` MaxPeers int @@ -66,7 +66,7 @@ func (c Config) MarshalTOML() (interface{}, error) { } // UnmarshalTOML unmarshals from TOML. -func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { +func (c *Config) UnmarshalTOML(unmarshal func(any) error) error { type Config struct { PrivateKey *ecdsa.PrivateKey `toml:"-"` MaxPeers *int diff --git a/p2p/discover/table_test.go b/p2p/discover/table_test.go index 8cc4ae33b2..3a5c0494bb 100644 --- a/p2p/discover/table_test.go +++ b/p2p/discover/table_test.go @@ -475,7 +475,7 @@ func nodeIDEqual[N nodeType](n1, n2 N) bool { // gen wraps quick.Value so it's easier to use. // it generates a random value of the given value's type. -func gen(typ interface{}, rand *rand.Rand) interface{} { +func gen(typ any, rand *rand.Rand) any { v, ok := quick.Value(reflect.TypeOf(typ), rand) if !ok { panic(fmt.Sprintf("couldn't generate random value of type %T", typ)) diff --git a/p2p/discover/v4_udp_test.go b/p2p/discover/v4_udp_test.go index 287f0c34fa..b43be45c41 100644 --- a/p2p/discover/v4_udp_test.go +++ b/p2p/discover/v4_udp_test.go @@ -110,7 +110,7 @@ func (test *udpTest) packetInFrom(wantError error, key *ecdsa.PrivateKey, addr n // waits for a packet to be sent by the transport. // validate should have type func(X, netip.AddrPort, []byte), where X is a packet type. -func (test *udpTest) waitPacketOut(validate interface{}) (closed bool) { +func (test *udpTest) waitPacketOut(validate any) (closed bool) { test.t.Helper() dgram, err := test.pipe.receive() diff --git a/p2p/discover/v4wire/v4wire_test.go b/p2p/discover/v4wire/v4wire_test.go index 38820f3b48..c4f6cb927d 100644 --- a/p2p/discover/v4wire/v4wire_test.go +++ b/p2p/discover/v4wire/v4wire_test.go @@ -30,7 +30,7 @@ import ( // EIP-8 test vectors. var testPackets = []struct { input string - wantPacket interface{} + wantPacket any }{ { input: "71dbda3a79554728d4f94411e42ee1f8b0d561c10e1e5f5893367948c6a7d70bb87b235fa28a77070271b6c164a2dce8c7e13a5739b53b5e96f2e5acb0e458a02902f5965d55ecbeb2ebb6cabb8b2b232896a36b737666c55265ad0a68412f250001ea04cb847f000001820cfa8215a8d790000000000000000000000000000000018208ae820d058443b9a355", diff --git a/p2p/discover/v5_udp.go b/p2p/discover/v5_udp.go index c13032e1af..513aa4ad97 100644 --- a/p2p/discover/v5_udp.go +++ b/p2p/discover/v5_udp.go @@ -84,7 +84,7 @@ type UDPv5 struct { respTimeout time.Duration // misc buffers used during message handling - logcontext []interface{} + logcontext []any // talkreq handler registry talk *talkSystem diff --git a/p2p/discover/v5_udp_test.go b/p2p/discover/v5_udp_test.go index 6abe20d7a4..432ebac709 100644 --- a/p2p/discover/v5_udp_test.go +++ b/p2p/discover/v5_udp_test.go @@ -984,7 +984,7 @@ func (test *udpV5Test) getNode(key *ecdsa.PrivateKey, addr netip.AddrPort) *enod // waitPacketOut waits for the next output packet and handles it using the given 'validate' // function. The function must be of type func (X, netip.AddrPort, v5wire.Nonce) where X is // assignable to packetV5. -func (test *udpV5Test) waitPacketOut(validate interface{}) (closed bool) { +func (test *udpV5Test) waitPacketOut(validate any) (closed bool) { test.t.Helper() fn := reflect.ValueOf(validate) diff --git a/p2p/discover/v5wire/msg.go b/p2p/discover/v5wire/msg.go index 089fd4ebdc..5a105fef73 100644 --- a/p2p/discover/v5wire/msg.go +++ b/p2p/discover/v5wire/msg.go @@ -36,7 +36,7 @@ type Packet interface { // AppendLogInfo returns its argument 'ctx' with additional fields // appended for logging purposes. - AppendLogInfo(ctx []interface{}) []interface{} + AppendLogInfo(ctx []any) []any } // Message types. @@ -156,7 +156,7 @@ func (*Whoareyou) Kind() byte { return WhoareyouPacket } func (*Whoareyou) RequestID() []byte { return nil } func (*Whoareyou) SetRequestID([]byte) {} -func (*Whoareyou) AppendLogInfo(ctx []interface{}) []interface{} { +func (*Whoareyou) AppendLogInfo(ctx []any) []any { return ctx } @@ -165,7 +165,7 @@ func (*Unknown) Kind() byte { return UnknownPacket } func (*Unknown) RequestID() []byte { return nil } func (*Unknown) SetRequestID([]byte) {} -func (*Unknown) AppendLogInfo(ctx []interface{}) []interface{} { +func (*Unknown) AppendLogInfo(ctx []any) []any { return ctx } @@ -174,7 +174,7 @@ func (*Ping) Kind() byte { return PingMsg } func (p *Ping) RequestID() []byte { return p.ReqID } func (p *Ping) SetRequestID(id []byte) { p.ReqID = id } -func (p *Ping) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *Ping) AppendLogInfo(ctx []any) []any { return append(ctx, "req", hexutil.Bytes(p.ReqID), "enrseq", p.ENRSeq) } @@ -183,7 +183,7 @@ func (*Pong) Kind() byte { return PongMsg } func (p *Pong) RequestID() []byte { return p.ReqID } func (p *Pong) SetRequestID(id []byte) { p.ReqID = id } -func (p *Pong) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *Pong) AppendLogInfo(ctx []any) []any { return append(ctx, "req", hexutil.Bytes(p.ReqID), "enrseq", p.ENRSeq) } @@ -192,7 +192,7 @@ func (p *Findnode) Kind() byte { return FindnodeMsg } func (p *Findnode) RequestID() []byte { return p.ReqID } func (p *Findnode) SetRequestID(id []byte) { p.ReqID = id } -func (p *Findnode) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *Findnode) AppendLogInfo(ctx []any) []any { ctx = append(ctx, "req", hexutil.Bytes(p.ReqID)) if p.OpID != 0 { ctx = append(ctx, "opid", p.OpID) @@ -205,7 +205,7 @@ func (*Nodes) Kind() byte { return NodesMsg } func (p *Nodes) RequestID() []byte { return p.ReqID } func (p *Nodes) SetRequestID(id []byte) { p.ReqID = id } -func (p *Nodes) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *Nodes) AppendLogInfo(ctx []any) []any { return append(ctx, "req", hexutil.Bytes(p.ReqID), "tot", p.RespCount, @@ -218,7 +218,7 @@ func (*TalkRequest) Kind() byte { return TalkRequestMsg } func (p *TalkRequest) RequestID() []byte { return p.ReqID } func (p *TalkRequest) SetRequestID(id []byte) { p.ReqID = id } -func (p *TalkRequest) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *TalkRequest) AppendLogInfo(ctx []any) []any { return append(ctx, "proto", p.Protocol, "req", hexutil.Bytes(p.ReqID), "len", len(p.Message)) } @@ -227,6 +227,6 @@ func (*TalkResponse) Kind() byte { return TalkResponseMsg } func (p *TalkResponse) RequestID() []byte { return p.ReqID } func (p *TalkResponse) SetRequestID(id []byte) { p.ReqID = id } -func (p *TalkResponse) AppendLogInfo(ctx []interface{}) []interface{} { +func (p *TalkResponse) AppendLogInfo(ctx []any) []any { return append(ctx, "req", hexutil.Bytes(p.ReqID), "len", len(p.Message)) } diff --git a/p2p/dnsdisc/client.go b/p2p/dnsdisc/client.go index ac369ce07d..c87413b0c0 100644 --- a/p2p/dnsdisc/client.go +++ b/p2p/dnsdisc/client.go @@ -134,7 +134,7 @@ func (c *Client) NewIterator(urls ...string) (enode.Iterator, error) { // resolveRoot retrieves a root entry via DNS. func (c *Client) resolveRoot(ctx context.Context, loc *linkEntry) (rootEntry, error) { - e, err, _ := c.singleflight.Do(loc.str, func() (interface{}, error) { + e, err, _ := c.singleflight.Do(loc.str, func() (any, error) { txts, err := c.cfg.Resolver.LookupTXT(ctx, loc.domain) c.cfg.Logger.Trace("Updating DNS discovery root", "tree", loc.domain, "err", err) if err != nil { @@ -175,7 +175,7 @@ func (c *Client) resolveEntry(ctx context.Context, domain, hash string) (entry, return e, nil } - ei, err, _ := c.singleflight.Do(cacheKey, func() (interface{}, error) { + ei, err, _ := c.singleflight.Do(cacheKey, func() (any, error) { e, err := c.doResolveEntry(ctx, domain, hash) if err != nil { return nil, err diff --git a/p2p/enode/node_test.go b/p2p/enode/node_test.go index 51bc4ebe15..06f6f50007 100644 --- a/p2p/enode/node_test.go +++ b/p2p/enode/node_test.go @@ -56,7 +56,7 @@ func TestPythonInterop(t *testing.T) { if n.ID() != wantID { t.Errorf("wrong id: got %x, want %x", n.ID(), wantID) } - want := map[enr.Entry]interface{}{new(enr.IPv4): &wantIP, new(enr.UDP): &wantUDP} + want := map[enr.Entry]any{new(enr.IPv4): &wantIP, new(enr.UDP): &wantUDP} for k, v := range want { desc := fmt.Sprintf("loading key %q", k.ENRKey()) if assert.NoError(t, n.Load(k), desc) { diff --git a/p2p/enr/enr.go b/p2p/enr/enr.go index 2b093b2f1a..afa192e607 100644 --- a/p2p/enr/enr.go +++ b/p2p/enr/enr.go @@ -313,7 +313,7 @@ func (r *Record) SetSig(s IdentityScheme, sig []byte) error { } // AppendElements appends the sequence number and entries to the given slice. -func (r *Record) AppendElements(list []interface{}) []interface{} { +func (r *Record) AppendElements(list []any) []any { list = append(list, r.seq) for _, p := range r.pairs { list = append(list, p.k, p.v) @@ -322,7 +322,7 @@ func (r *Record) AppendElements(list []interface{}) []interface{} { } func (r *Record) encode(sig []byte) (raw []byte, err error) { - list := make([]interface{}, 1, 2*len(r.pairs)+2) + list := make([]any, 1, 2*len(r.pairs)+2) list[0] = sig list = r.AppendElements(list) if raw, err = rlp.EncodeToBytes(list); err != nil { diff --git a/p2p/enr/entries.go b/p2p/enr/entries.go index 58e660c154..86b8255a5b 100644 --- a/p2p/enr/entries.go +++ b/p2p/enr/entries.go @@ -37,7 +37,7 @@ type Entry interface { type generic struct { key string - value interface{} + value any } func (g generic) ENRKey() string { return g.key } @@ -53,7 +53,7 @@ func (g *generic) DecodeRLP(s *rlp.Stream) error { // WithEntry wraps any value with a key name. It can be used to set and load arbitrary values // in a record. The value v must be supported by rlp. To use WithEntry with Load, the value // must be a pointer. -func WithEntry(k string, v interface{}) Entry { +func WithEntry(k string, v any) Entry { return &generic{key: k, value: v} } diff --git a/p2p/message.go b/p2p/message.go index 3ab56ee350..3ab0e517d7 100644 --- a/p2p/message.go +++ b/p2p/message.go @@ -51,7 +51,7 @@ type Msg struct { // the given value, which must be a pointer. // // For the decoding rules, please see package rlp. -func (msg Msg) Decode(val interface{}) error { +func (msg Msg) Decode(val any) error { s := rlp.NewStream(msg.Payload, uint64(msg.Size)) if err := s.Decode(val); err != nil { return newPeerError(errInvalidMsg, "(code %x) (size %d) %v", msg.Code, msg.Size, err) @@ -96,7 +96,7 @@ type MsgReadWriter interface { // Send writes an RLP-encoded message with the given code. // data should encode as an RLP list. -func Send(w MsgWriter, msgcode uint64, data interface{}) error { +func Send(w MsgWriter, msgcode uint64, data any) error { size, r, err := rlp.EncodeToReader(data) if err != nil { return err @@ -112,7 +112,7 @@ func Send(w MsgWriter, msgcode uint64, data interface{}) error { // the message payload will be an RLP list containing the items: // // [e1, e2, e3] -func SendItems(w MsgWriter, msgcode uint64, elems ...interface{}) error { +func SendItems(w MsgWriter, msgcode uint64, elems ...any) error { return Send(w, msgcode, elems) } @@ -224,7 +224,7 @@ func (p *MsgPipeRW) Close() error { // ExpectMsg reads a message from r and verifies that its // code and encoded RLP content match the provided values. // If content is nil, the payload is discarded and not verified. -func ExpectMsg(r MsgReader, code uint64, content interface{}) error { +func ExpectMsg(r MsgReader, code uint64, content any) error { msg, err := r.ReadMsg() if err != nil { return err diff --git a/p2p/netutil/net.go b/p2p/netutil/net.go index 696c331859..d32e6bc0c3 100644 --- a/p2p/netutil/net.go +++ b/p2p/netutil/net.go @@ -85,7 +85,7 @@ func ParseNetlist(s string) (*Netlist, error) { } // MarshalTOML implements toml.MarshalerRec. -func (l Netlist) MarshalTOML() interface{} { +func (l Netlist) MarshalTOML() any { list := make([]string, 0, len(l)) for _, net := range l { list = append(list, net.String()) @@ -94,7 +94,7 @@ func (l Netlist) MarshalTOML() interface{} { } // UnmarshalTOML implements toml.UnmarshalerRec. -func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error { +func (l *Netlist) UnmarshalTOML(fn func(any) error) error { var masks []string if err := fn(&masks); err != nil { return err diff --git a/p2p/peer.go b/p2p/peer.go index 5521889f30..acbe9ab4b4 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -554,7 +554,7 @@ type PeerInfo struct { Trusted bool `json:"trusted"` Static bool `json:"static"` } `json:"network"` - Protocols map[string]interface{} `json:"protocols"` // Sub-protocol specific metadata fields + Protocols map[string]any `json:"protocols"` // Sub-protocol specific metadata fields } // Info gathers and returns a collection of metadata known about a peer. @@ -570,7 +570,7 @@ func (p *Peer) Info() *PeerInfo { ID: p.ID().String(), Name: p.Fullname(), Caps: caps, - Protocols: make(map[string]interface{}, len(p.running)), + Protocols: make(map[string]any, len(p.running)), } if p.Node().Seq() > 0 { info.ENR = p.Node().String() @@ -583,7 +583,7 @@ func (p *Peer) Info() *PeerInfo { // Gather all the running protocol infos for _, proto := range p.running { - protoInfo := interface{}("unknown") + protoInfo := any("unknown") if query := proto.Protocol.PeerInfo; query != nil { if metadata := query(p.ID()); metadata != nil { protoInfo = metadata diff --git a/p2p/peer_error.go b/p2p/peer_error.go index dcdadf7fe3..41a8add6d6 100644 --- a/p2p/peer_error.go +++ b/p2p/peer_error.go @@ -36,7 +36,7 @@ type peerError struct { message string } -func newPeerError(code int, format string, v ...interface{}) *peerError { +func newPeerError(code int, format string, v ...any) *peerError { desc, ok := errorToString[code] if !ok { panic("invalid error code") diff --git a/p2p/protocol.go b/p2p/protocol.go index de3127e233..0eac7fc10c 100644 --- a/p2p/protocol.go +++ b/p2p/protocol.go @@ -49,12 +49,12 @@ type Protocol struct { // NodeInfo is an optional helper method to retrieve protocol specific metadata // about the host node. - NodeInfo func() interface{} + NodeInfo func() any // PeerInfo is an optional helper method to retrieve protocol specific metadata // about a certain peer in the network. If an info retrieval function is set, // but returns nil, it is assumed that the protocol handshake is still running. - PeerInfo func(id enode.ID) interface{} + PeerInfo func(id enode.ID) any // DialCandidates, if non-nil, is a way to tell Server about protocol-specific nodes // that should be dialed. The server continuously reads nodes from the iterator and diff --git a/p2p/rlpx/rlpx.go b/p2p/rlpx/rlpx.go index 0dc4ecbe2d..47b74e9904 100644 --- a/p2p/rlpx/rlpx.go +++ b/p2p/rlpx/rlpx.go @@ -594,7 +594,7 @@ func (h *handshakeState) makeAuthResp() (msg *authRespV4, err error) { } // readMsg reads an encrypted handshake message, decoding it into msg. -func (h *handshakeState) readMsg(msg interface{}, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) { +func (h *handshakeState) readMsg(msg any, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) { h.rbuf.reset() h.rbuf.grow(512) @@ -627,7 +627,7 @@ func (h *handshakeState) readMsg(msg interface{}, prv *ecdsa.PrivateKey, r io.Re } // sealEIP8 encrypts a handshake message. -func (h *handshakeState) sealEIP8(msg interface{}) ([]byte, error) { +func (h *handshakeState) sealEIP8(msg any) ([]byte, error) { h.wbuf.reset() // Write the message plaintext. diff --git a/p2p/server.go b/p2p/server.go index 10c855f1c4..56b62bbea2 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -1021,8 +1021,8 @@ type NodeInfo struct { Discovery int `json:"discovery"` // UDP listening port for discovery protocol Listener int `json:"listener"` // TCP listening port for RLPx } `json:"ports"` - ListenAddr string `json:"listenAddr"` - Protocols map[string]interface{} `json:"protocols"` + ListenAddr string `json:"listenAddr"` + Protocols map[string]any `json:"protocols"` } // NodeInfo gathers and returns a collection of metadata known about the host. @@ -1035,7 +1035,7 @@ func (srv *Server) NodeInfo() *NodeInfo { ID: node.ID().String(), IP: node.IPAddr().String(), ListenAddr: srv.ListenAddr, - Protocols: make(map[string]interface{}), + Protocols: make(map[string]any), } info.Ports.Discovery = node.UDP() info.Ports.Listener = node.TCP() @@ -1044,7 +1044,7 @@ func (srv *Server) NodeInfo() *NodeInfo { // Gather all the running protocol infos (only once per protocol type) for _, proto := range srv.Protocols { if _, ok := info.Protocols[proto.Name]; !ok { - nodeInfo := interface{}("unknown") + nodeInfo := any("unknown") if query := proto.NodeInfo; query != nil { nodeInfo = proto.NodeInfo() } diff --git a/p2p/transport_test.go b/p2p/transport_test.go index 777be1bd0d..9ba43845d0 100644 --- a/p2p/transport_test.go +++ b/p2p/transport_test.go @@ -107,7 +107,7 @@ func TestProtocolHandshake(t *testing.T) { func TestProtocolHandshakeErrors(t *testing.T) { tests := []struct { code uint64 - msg interface{} + msg any err error }{ { diff --git a/p2p/util.go b/p2p/util.go index 2c8f322a66..7e00dfefa0 100644 --- a/p2p/util.go +++ b/p2p/util.go @@ -62,11 +62,11 @@ func (h *expHeap) expire(now mclock.AbsTime, onExp func(string)) { } // heap.Interface boilerplate -func (h expHeap) Len() int { return len(h) } -func (h expHeap) Less(i, j int) bool { return h[i].exp < h[j].exp } -func (h expHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *expHeap) Push(x interface{}) { *h = append(*h, x.(expItem)) } -func (h *expHeap) Pop() interface{} { +func (h expHeap) Len() int { return len(h) } +func (h expHeap) Less(i, j int) bool { return h[i].exp < h[j].exp } +func (h expHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *expHeap) Push(x any) { *h = append(*h, x.(expItem)) } +func (h *expHeap) Pop() any { old := *h n := len(old) x := old[n-1] diff --git a/rlp/decode.go b/rlp/decode.go index 19074072fb..379709f7eb 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -56,7 +56,7 @@ var ( errUint256Large = errors.New("rlp: value too large for uint256") streamPool = sync.Pool{ - New: func() interface{} { return new(Stream) }, + New: func() any { return new(Stream) }, } ) @@ -79,7 +79,7 @@ type Decoder interface { // panics cause by huge value sizes. If you need an input limit, use // // NewStream(r, limit).Decode(val) -func Decode(r io.Reader, val interface{}) error { +func Decode(r io.Reader, val any) error { stream := streamPool.Get().(*Stream) defer streamPool.Put(stream) @@ -89,7 +89,7 @@ func Decode(r io.Reader, val interface{}) error { // DecodeBytes parses RLP data from b into val. Please see package-level documentation for // the decoding rules. The input must contain exactly one value and no trailing data. -func DecodeBytes(b []byte, val interface{}) error { +func DecodeBytes(b []byte, val any) error { r := (*sliceReader)(&b) stream := streamPool.Get().(*Stream) @@ -930,7 +930,7 @@ func (s *Stream) ReadUint256(dst *uint256.Int) error { // Decode decodes a value and stores the result in the value pointed // to by val. Please see the documentation for the Decode function // to learn about the decoding rules. -func (s *Stream) Decode(val interface{}) error { +func (s *Stream) Decode(val any) error { if val == nil { return errDecodeIntoNil } diff --git a/rlp/decode_test.go b/rlp/decode_test.go index 4b3a322873..2b65fbbc93 100644 --- a/rlp/decode_test.go +++ b/rlp/decode_test.go @@ -356,8 +356,8 @@ func TestDecodeErrors(t *testing.T) { type decodeTest struct { input string - ptr interface{} - value interface{} + ptr any + value any error string } @@ -686,7 +686,7 @@ var decodeTests = []decodeTest{ { input: "C103", ptr: new(nilListUint), - value: func() interface{} { + value: func() any { v := uint(3) return nilListUint{X: &v} }(), @@ -856,12 +856,12 @@ var decodeTests = []decodeTest{ {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}}, // interface{} - {input: "00", ptr: new(interface{}), value: []byte{0}}, - {input: "01", ptr: new(interface{}), value: []byte{1}}, - {input: "80", ptr: new(interface{}), value: []byte{}}, - {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}}, - {input: "C0", ptr: new(interface{}), value: []interface{}{}}, - {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}}, + {input: "00", ptr: new(any), value: []byte{0}}, + {input: "01", ptr: new(any), value: []byte{1}}, + {input: "80", ptr: new(any), value: []byte{}}, + {input: "850505050505", ptr: new(any), value: []byte{5, 5, 5, 5, 5}}, + {input: "C0", ptr: new(any), value: []any{}}, + {input: "C50183040404", ptr: new(any), value: []any{[]byte{1}, []byte{4, 4, 4}}}, { input: "C3010203", ptr: new([]io.Reader), @@ -871,14 +871,14 @@ var decodeTests = []decodeTest{ // fuzzer crashes { input: "c330f9c030f93030ce3030303030303030bd303030303030", - ptr: new(interface{}), + ptr: new(any), error: "rlp: element is larger than containing list", }, } func uintp(i uint) *uint { return &i } -func runTests(t *testing.T, decode func([]byte, interface{}) error) { +func runTests(t *testing.T, decode func([]byte, any) error) { for i, test := range decodeTests { input, err := hex.DecodeString(test.input) if err != nil { @@ -905,7 +905,7 @@ func runTests(t *testing.T, decode func([]byte, interface{}) error) { } func TestDecodeWithByteReader(t *testing.T) { - runTests(t, func(input []byte, into interface{}) error { + runTests(t, func(input []byte, into any) error { return Decode(bytes.NewReader(input), into) }) } @@ -950,14 +950,14 @@ func (r *plainReader) Read(buf []byte) (n int, err error) { } func TestDecodeWithNonByteReader(t *testing.T) { - runTests(t, func(input []byte, into interface{}) error { + runTests(t, func(input []byte, into any) error { return Decode(newPlainReader(input), into) }) } func TestDecodeStreamReset(t *testing.T) { s := NewStream(nil, 0) - runTests(t, func(input []byte, into interface{}) error { + runTests(t, func(input []byte, into any) error { s.Reset(bytes.NewReader(input), 0) return s.Decode(into) }) @@ -1083,7 +1083,7 @@ func TestInvalidOptionalField(t *testing.T) { ) tests := []struct { - v interface{} + v any err string }{ {v: new(invalid1), err: `rlp: invalid struct tag "" for rlp.invalid1.B (must be optional because preceding field "A" is optional)`}, diff --git a/rlp/encbuffer.go b/rlp/encbuffer.go index 61d8bd059c..5d5790d80f 100644 --- a/rlp/encbuffer.go +++ b/rlp/encbuffer.go @@ -36,7 +36,7 @@ type encBuffer struct { // The global encBuffer pool. var encBufferPool = sync.Pool{ - New: func() interface{} { return new(encBuffer) }, + New: func() any { return new(encBuffer) }, } func getEncBuffer() *encBuffer { @@ -197,7 +197,7 @@ func (buf *encBuffer) listEnd(index int) { } } -func (buf *encBuffer) encode(val interface{}) error { +func (buf *encBuffer) encode(val any) error { rval := reflect.ValueOf(val) writer, err := cachedWriter(rval.Type()) if err != nil { diff --git a/rlp/encode.go b/rlp/encode.go index ed99275739..783b77b30e 100644 --- a/rlp/encode.go +++ b/rlp/encode.go @@ -59,7 +59,7 @@ type Encoder interface { // buffered. // // Please see package-level documentation of encoding rules. -func Encode(w io.Writer, val interface{}) error { +func Encode(w io.Writer, val any) error { // Optimization: reuse *encBuffer when called by EncodeRLP. if buf := encBufferFromWriter(w); buf != nil { return buf.encode(val) @@ -75,7 +75,7 @@ func Encode(w io.Writer, val interface{}) error { // EncodeToBytes returns the RLP encoding of val. // Please see package-level documentation for the encoding rules. -func EncodeToBytes(val interface{}) ([]byte, error) { +func EncodeToBytes(val any) ([]byte, error) { buf := getEncBuffer() defer encBufferPool.Put(buf) @@ -90,7 +90,7 @@ func EncodeToBytes(val interface{}) ([]byte, error) { // data. // // Please see the documentation of Encode for the encoding rules. -func EncodeToReader(val interface{}) (size int, r io.Reader, err error) { +func EncodeToReader(val any) (size int, r io.Reader, err error) { buf := getEncBuffer() if err := buf.encode(val); err != nil { encBufferPool.Put(buf) diff --git a/rlp/encode_test.go b/rlp/encode_test.go index e63ea319b4..bd5cd2ebe1 100644 --- a/rlp/encode_test.go +++ b/rlp/encode_test.go @@ -84,7 +84,7 @@ var ( ) type encTest struct { - val interface{} + val any output, error string } @@ -232,7 +232,7 @@ var encTests = []encTest{ {val: []uint{1, 2, 3}, output: "C3010203"}, { // [ [], [[]], [ [], [[]] ] ] - val: []interface{}{[]interface{}{}, [][]interface{}{{}}, []interface{}{[]interface{}{}, [][]interface{}{{}}}}, + val: []any{[]any{}, [][]any{{}}, []any{[]any{}, [][]any{{}}}}, output: "C7C0C1C0C3C0C1C0", }, { @@ -240,7 +240,7 @@ var encTests = []encTest{ output: "F83C836161618362626283636363836464648365656583666666836767678368686883696969836A6A6A836B6B6B836C6C6C836D6D6D836E6E6E836F6F6F", }, { - val: []interface{}{uint(1), uint(0xFFFFFF), []interface{}{[]uint{4, 5, 5}}, "abc"}, + val: []any{uint(1), uint(0xFFFFFF), []any{[]uint{4, 5, 5}}, "abc"}, output: "CE0183FFFFFFC4C304050583616263", }, { @@ -334,9 +334,9 @@ var encTests = []encTest{ {val: (*uint256.Int)(nil), output: "80"}, {val: (*[]string)(nil), output: "C0"}, {val: (*[10]string)(nil), output: "C0"}, - {val: (*[]interface{})(nil), output: "C0"}, + {val: (*[]any)(nil), output: "C0"}, {val: (*[]struct{ uint })(nil), output: "C0"}, - {val: (*interface{})(nil), output: "C0"}, + {val: (*any)(nil), output: "C0"}, // nil struct fields { @@ -401,7 +401,7 @@ var encTests = []encTest{ {val: []byteEncoder{0, 1, 2, 3, 4}, output: "C5C0C0C0C0C0"}, } -func runEncTests(t *testing.T, f func(val interface{}) ([]byte, error)) { +func runEncTests(t *testing.T, f func(val any) ([]byte, error)) { for i, test := range encTests { output, err := f(test.val) if err != nil && test.error == "" { @@ -422,7 +422,7 @@ func runEncTests(t *testing.T, f func(val interface{}) ([]byte, error)) { } func TestEncode(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { + runEncTests(t, func(val any) ([]byte, error) { b := new(bytes.Buffer) err := Encode(b, val) return b.Bytes(), err @@ -435,7 +435,7 @@ func TestEncodeToBytes(t *testing.T) { func TestEncodeAppendToBytes(t *testing.T) { buffer := make([]byte, 20) - runEncTests(t, func(val interface{}) ([]byte, error) { + runEncTests(t, func(val any) ([]byte, error) { w := NewEncoderBuffer(nil) defer w.Flush() @@ -449,7 +449,7 @@ func TestEncodeAppendToBytes(t *testing.T) { } func TestEncodeToReader(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { + runEncTests(t, func(val any) ([]byte, error) { _, r, err := EncodeToReader(val) if err != nil { return nil, err @@ -459,7 +459,7 @@ func TestEncodeToReader(t *testing.T) { } func TestEncodeToReaderPiecewise(t *testing.T) { - runEncTests(t, func(val interface{}) ([]byte, error) { + runEncTests(t, func(val any) ([]byte, error) { size, r, err := EncodeToReader(val) if err != nil { return nil, err @@ -507,7 +507,7 @@ func TestEncodeToReaderReturnToPool(t *testing.T) { wg.Wait() } -var sink interface{} +var sink any func BenchmarkIntsize(b *testing.B) { for i := 0; i < b.N; i++ { @@ -563,7 +563,7 @@ func BenchmarkEncodeConcurrentInterface(b *testing.B) { B *big.Int C [20]byte } - value := []interface{}{ + value := []any{ uint(999), &struct1{A: "hello", B: big.NewInt(0xFFFFFFFF)}, [10]byte{1, 2, 3, 4, 5, 6}, diff --git a/rlp/rlpgen/main.go b/rlp/rlpgen/main.go index b3a74b9df1..0db483ec9a 100644 --- a/rlp/rlpgen/main.go +++ b/rlp/rlpgen/main.go @@ -56,7 +56,7 @@ func main() { } } -func fatal(args ...interface{}) { +func fatal(args ...any) { fmt.Fprintln(os.Stderr, args...) os.Exit(1) } diff --git a/rpc/client.go b/rpc/client.go index 9dc36a6105..29986eed40 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -64,11 +64,11 @@ const ( // BatchElem is an element in a batch request. type BatchElem struct { Method string - Args []interface{} + Args []any // The result is unmarshaled into this field. Result must be set to a // non-nil pointer value of the desired type, otherwise the response will be // discarded. - Result interface{} + Result any // Error is set if the server returns an error for this request, or if // unmarshalling into Result fails. It is not set for I/O errors. Error error @@ -275,7 +275,7 @@ func initClient(conn ServerCodec, services *serviceRegistry, cfg *clientConfig) // methods on the given receiver match the criteria to be either a RPC method or a // subscription an error is returned. Otherwise a new service is created and added to the // service collection this client provides to the server. -func (c *Client) RegisterName(name string, receiver interface{}) error { +func (c *Client) RegisterName(name string, receiver any) error { return c.services.registerName(name, receiver) } @@ -324,7 +324,7 @@ func (c *Client) SetHeader(key, value string) { // // The result must be a pointer so that package json can unmarshal into it. You // can also pass nil, in which case the result is ignored. -func (c *Client) Call(result interface{}, method string, args ...interface{}) error { +func (c *Client) Call(result any, method string, args ...any) error { ctx := context.Background() return c.CallContext(ctx, result, method, args...) } @@ -334,7 +334,7 @@ func (c *Client) Call(result interface{}, method string, args ...interface{}) er // // The result must be a pointer so that package json can unmarshal into it. You // can also pass nil, in which case the result is ignored. -func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { +func (c *Client) CallContext(ctx context.Context, result any, method string, args ...any) error { if result != nil && reflect.TypeOf(result).Kind() != reflect.Ptr { return fmt.Errorf("call result parameter must be pointer or nil interface: %v", result) } @@ -467,7 +467,7 @@ func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error { } // Notify sends a notification, i.e. a method call that doesn't expect a response. -func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) error { +func (c *Client) Notify(ctx context.Context, method string, args ...any) error { op := new(requestOp) msg, err := c.newMessage(method, args...) if err != nil { @@ -482,7 +482,7 @@ func (c *Client) Notify(ctx context.Context, method string, args ...interface{}) } // EthSubscribe registers a subscription under the "eth" namespace. -func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error) { +func (c *Client) EthSubscribe(ctx context.Context, channel any, args ...any) (*ClientSubscription, error) { return c.Subscribe(ctx, "eth", channel, args...) } @@ -498,7 +498,7 @@ func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ... // before considering the subscriber dead. The subscription Err channel will receive // ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure // that the channel usually has at least one reader to prevent this issue. -func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error) { +func (c *Client) Subscribe(ctx context.Context, namespace string, channel any, args ...any) (*ClientSubscription, error) { // Check type of channel first. chanVal := reflect.ValueOf(channel) if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 { @@ -539,7 +539,7 @@ func (c *Client) SupportsSubscriptions() bool { return !c.isHTTP } -func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMessage, error) { +func (c *Client) newMessage(method string, paramsIn ...any) (*jsonrpcMessage, error) { msg := &jsonrpcMessage{Version: vsn, ID: c.nextID(), Method: method} if paramsIn != nil { // prevent sending "params":null var err error @@ -552,7 +552,7 @@ func (c *Client) newMessage(method string, paramsIn ...interface{}) (*jsonrpcMes // send registers op with the dispatch loop, then sends msg on the connection. // if sending fails, op is deregistered. -func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error { +func (c *Client) send(ctx context.Context, op *requestOp, msg any) error { select { case c.reqInit <- op: err := c.write(ctx, msg, false) @@ -567,7 +567,7 @@ func (c *Client) send(ctx context.Context, op *requestOp, msg interface{}) error } } -func (c *Client) write(ctx context.Context, msg interface{}, retry bool) error { +func (c *Client) write(ctx context.Context, msg any, retry bool) error { if c.writeConn == nil { // The previous write failed. Try to establish a new connection. if err := c.reconnect(ctx); err != nil { diff --git a/rpc/client_test.go b/rpc/client_test.go index 03a3410537..2977b0fa70 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -104,7 +104,7 @@ func TestClientErrorData(t *testing.T) { client := DialInProc(server) defer client.Close() - var resp interface{} + var resp any err := client.Call(&resp, "test_returnError") if err == nil { t.Fatal("expected error") @@ -139,17 +139,17 @@ func TestClientBatchRequest(t *testing.T) { batch := []BatchElem{ { Method: "test_echo", - Args: []interface{}{"hello", 10, &echoArgs{"world"}}, + Args: []any{"hello", 10, &echoArgs{"world"}}, Result: new(echoResult), }, { Method: "test_echo", - Args: []interface{}{"hello2", 11, &echoArgs{"world"}}, + Args: []any{"hello2", 11, &echoArgs{"world"}}, Result: new(echoResult), }, { Method: "no_such_method", - Args: []interface{}{1, 2, 3}, + Args: []any{1, 2, 3}, Result: new(int), }, } @@ -159,17 +159,17 @@ func TestClientBatchRequest(t *testing.T) { wantResult := []BatchElem{ { Method: "test_echo", - Args: []interface{}{"hello", 10, &echoArgs{"world"}}, + Args: []any{"hello", 10, &echoArgs{"world"}}, Result: &echoResult{"hello", 10, &echoArgs{"world"}}, }, { Method: "test_echo", - Args: []interface{}{"hello2", 11, &echoArgs{"world"}}, + Args: []any{"hello2", 11, &echoArgs{"world"}}, Result: &echoResult{"hello2", 11, &echoArgs{"world"}}, }, { Method: "no_such_method", - Args: []interface{}{1, 2, 3}, + Args: []any{1, 2, 3}, Result: new(int), Error: &jsonError{Code: -32601, Message: "the method no_such_method does not exist/is not available"}, }, @@ -419,7 +419,7 @@ func TestClientSubscribeInvalidArg(t *testing.T) { client := DialInProc(server) defer client.Close() - check := func(shouldPanic bool, arg interface{}) { + check := func(shouldPanic bool, arg any) { defer func() { err := recover() if shouldPanic && err == nil { diff --git a/rpc/errors.go b/rpc/errors.go index 438aff218c..2eaded53db 100644 --- a/rpc/errors.go +++ b/rpc/errors.go @@ -41,8 +41,8 @@ type Error interface { // A DataError contains some data in addition to the error message. type DataError interface { - Error() string // returns the message - ErrorData() interface{} // returns the error data + Error() string // returns the message + ErrorData() any // returns the error data } // Error types defined below are the built-in JSON-RPC errors. diff --git a/rpc/http.go b/rpc/http.go index a74f36a1b0..a687392501 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -44,7 +44,7 @@ type httpConn struct { client *http.Client url string closeOnce sync.Once - closeCh chan interface{} + closeCh chan any mu sync.Mutex // protects headers headers http.Header auth HTTPAuth @@ -54,7 +54,7 @@ type httpConn struct { // and some methods don't work. The panic() stubs here exist to ensure // this special treatment is correct. -func (hc *httpConn) writeJSON(context.Context, interface{}, bool) error { +func (hc *httpConn) writeJSON(context.Context, any, bool) error { panic("writeJSON called on httpConn") } @@ -75,7 +75,7 @@ func (hc *httpConn) close() { hc.closeOnce.Do(func() { close(hc.closeCh) }) } -func (hc *httpConn) closed() <-chan interface{} { +func (hc *httpConn) closed() <-chan any { return hc.closeCh } @@ -160,7 +160,7 @@ func newClientTransportHTTP(endpoint string, cfg *clientConfig) reconnectFunc { headers: headers, url: endpoint, auth: cfg.httpAuth, - closeCh: make(chan interface{}), + closeCh: make(chan any), } return func(ctx context.Context) (ServerCodec, error) { @@ -176,7 +176,7 @@ func cleanlyCloseBody(body io.ReadCloser) error { return body.Close() } -func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg interface{}) error { +func (c *Client) sendHTTP(ctx context.Context, op *requestOp, msg any) error { hc := c.writeConn.(*httpConn) respBody, err := hc.doRequest(ctx, msg) if err != nil { @@ -209,7 +209,7 @@ func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonr return nil } -func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadCloser, error) { +func (hc *httpConn) doRequest(ctx context.Context, msg any) (io.ReadCloser, error) { body, err := json.Marshal(msg) if err != nil { return nil, err diff --git a/rpc/json.go b/rpc/json.go index fcd801fc95..4cc76e9a04 100644 --- a/rpc/json.go +++ b/rpc/json.go @@ -113,7 +113,7 @@ func (msg *jsonrpcMessage) errorResponse(err error) *jsonrpcMessage { return resp } -func (msg *jsonrpcMessage) response(result interface{}) *jsonrpcMessage { +func (msg *jsonrpcMessage) response(result any) *jsonrpcMessage { enc, err := json.Marshal(result) if err != nil { return msg.errorResponse(&internalServerError{errcodeMarshalError, err.Error()}) @@ -138,9 +138,9 @@ func errorMessage(err error) *jsonrpcMessage { } type jsonError struct { - Code int `json:"code"` - Message string `json:"message"` - Data interface{} `json:"data,omitempty"` + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data,omitempty"` } func (err *jsonError) Error() string { @@ -154,7 +154,7 @@ func (err *jsonError) ErrorCode() int { return err.Code } -func (err *jsonError) ErrorData() interface{} { +func (err *jsonError) ErrorData() any { return err.Data } @@ -180,24 +180,24 @@ type ConnRemoteAddr interface { // support for parsing arguments and serializing (result) objects. type jsonCodec struct { remote string - closer sync.Once // close closed channel once - closeCh chan interface{} // closed on Close - decode decodeFunc // decoder to allow multiple transports - encMu sync.Mutex // guards the encoder - encode encodeFunc // encoder to allow multiple transports + closer sync.Once // close closed channel once + closeCh chan any // closed on Close + decode decodeFunc // decoder to allow multiple transports + encMu sync.Mutex // guards the encoder + encode encodeFunc // encoder to allow multiple transports conn deadlineCloser } -type encodeFunc = func(v interface{}, isErrorResponse bool) error +type encodeFunc = func(v any, isErrorResponse bool) error -type decodeFunc = func(v interface{}) error +type decodeFunc = func(v any) error // NewFuncCodec creates a codec which uses the given functions to read and write. If conn // implements ConnRemoteAddr, log messages will use it to include the remote address of // the connection. func NewFuncCodec(conn deadlineCloser, encode encodeFunc, decode decodeFunc) ServerCodec { codec := &jsonCodec{ - closeCh: make(chan interface{}), + closeCh: make(chan any), encode: encode, decode: decode, conn: conn, @@ -215,7 +215,7 @@ func NewCodec(conn Conn) ServerCodec { dec := json.NewDecoder(conn) dec.UseNumber() - encode := func(v interface{}, isErrorResponse bool) error { + encode := func(v any, isErrorResponse bool) error { return enc.Encode(v) } return NewFuncCodec(conn, encode, dec.Decode) @@ -248,7 +248,7 @@ func (c *jsonCodec) readBatch() (messages []*jsonrpcMessage, batch bool, err err return messages, batch, nil } -func (c *jsonCodec) writeJSON(ctx context.Context, v interface{}, isErrorResponse bool) error { +func (c *jsonCodec) writeJSON(ctx context.Context, v any, isErrorResponse bool) error { c.encMu.Lock() defer c.encMu.Unlock() @@ -268,7 +268,7 @@ func (c *jsonCodec) close() { } // closed returns a channel which will be closed when Close is called -func (c *jsonCodec) closed() <-chan interface{} { +func (c *jsonCodec) closed() <-chan any { return c.closeCh } diff --git a/rpc/server.go b/rpc/server.go index 599e31fb41..a0568fc4f8 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -102,7 +102,7 @@ func (s *Server) SetWebsocketReadLimit(limit int64) { // methods on the given receiver match the criteria to be either an RPC method or a // subscription an error is returned. Otherwise a new service is created and added to the // service collection this server provides to clients. -func (s *Server) RegisterName(name string, receiver interface{}) error { +func (s *Server) RegisterName(name string, receiver any) error { return s.services.registerName(name, receiver) } diff --git a/rpc/service.go b/rpc/service.go index 0f62d7eb7c..1607c64d0a 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -57,7 +57,7 @@ type callback struct { isSubscribe bool // true if this is a subscription callback } -func (r *serviceRegistry) registerName(name string, rcvr interface{}) error { +func (r *serviceRegistry) registerName(name string, rcvr any) error { rcvrVal := reflect.ValueOf(rcvr) if name == "" { return fmt.Errorf("no service name for type %s", rcvrVal.Type().String()) @@ -180,7 +180,7 @@ func (c *callback) makeArgTypes() { } // call invokes the callback. -func (c *callback) call(ctx context.Context, method string, args []reflect.Value) (res interface{}, errRes error) { +func (c *callback) call(ctx context.Context, method string, args []reflect.Value) (res any, errRes error) { // Create the argument slice. fullargs := make([]reflect.Value, 0, 2+len(args)) if c.rcvr.IsValid() { diff --git a/rpc/subscription.go b/rpc/subscription.go index 9e400c8b60..9f532115f9 100644 --- a/rpc/subscription.go +++ b/rpc/subscription.go @@ -363,14 +363,14 @@ func (sub *ClientSubscription) forward() (unsubscribeServer bool, err error) { } } -func (sub *ClientSubscription) unmarshal(result json.RawMessage) (interface{}, error) { +func (sub *ClientSubscription) unmarshal(result json.RawMessage) (any, error) { val := reflect.New(sub.etype) err := json.Unmarshal(result, val.Interface()) return val.Elem().Interface(), err } func (sub *ClientSubscription) requestUnsubscribe() error { - var result interface{} + var result any ctx, cancel := context.WithTimeout(context.Background(), unsubscribeTimeout) defer cancel() err := sub.client.CallContext(ctx, &result, sub.namespace+unsubscribeMethodSuffix, sub.subid) diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index cd44d219de..53103c312e 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -87,11 +87,11 @@ func TestSubscriptions(t *testing.T) { // create subscriptions one by one for i, namespace := range namespaces { - request := map[string]interface{}{ + request := map[string]any{ "id": i, "method": fmt.Sprintf("%s_subscribe", namespace), "jsonrpc": "2.0", - "params": []interface{}{"someSubscription", notificationCount, i}, + "params": []any{"someSubscription", notificationCount, i}, } if err := out.Encode(&request); err != nil { t.Fatalf("Could not create subscription: %v", err) @@ -237,12 +237,12 @@ type mockConn struct { } // writeJSON writes a message to the connection. -func (c *mockConn) writeJSON(ctx context.Context, msg interface{}, isError bool) error { +func (c *mockConn) writeJSON(ctx context.Context, msg any, isError bool) error { return c.enc.Encode(msg) } // closed returns a channel which is closed when the connection is closed. -func (c *mockConn) closed() <-chan interface{} { return nil } +func (c *mockConn) closed() <-chan any { return nil } // remoteAddr returns the peer address of the connection. func (c *mockConn) remoteAddr() string { return "" } diff --git a/rpc/testservice_test.go b/rpc/testservice_test.go index 69199e21b7..2d6ed08af4 100644 --- a/rpc/testservice_test.go +++ b/rpc/testservice_test.go @@ -66,9 +66,9 @@ type echoResult struct { type testError struct{} -func (testError) Error() string { return "testError" } -func (testError) ErrorCode() int { return 444 } -func (testError) ErrorData() interface{} { return "testError data" } +func (testError) Error() string { return "testError" } +func (testError) ErrorCode() int { return 444 } +func (testError) ErrorData() any { return "testError data" } type MarshalErrObj struct{} @@ -136,24 +136,24 @@ func (s *testService) Panic() string { panic("service panic") } -func (s *testService) CallMeBack(ctx context.Context, method string, args []interface{}) (interface{}, error) { +func (s *testService) CallMeBack(ctx context.Context, method string, args []any) (any, error) { c, ok := ClientFromContext(ctx) if !ok { return nil, errors.New("no client") } - var result interface{} + var result any err := c.Call(&result, method, args...) return result, err } -func (s *testService) CallMeBackLater(ctx context.Context, method string, args []interface{}) error { +func (s *testService) CallMeBackLater(ctx context.Context, method string, args []any) error { c, ok := ClientFromContext(ctx) if !ok { return errors.New("no client") } go func() { <-ctx.Done() - var result interface{} + var result any c.Call(&result, method, args...) }() return nil diff --git a/rpc/types.go b/rpc/types.go index 85f15344e8..092ce4b074 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -30,11 +30,11 @@ import ( // API describes the set of methods offered over the RPC interface type API struct { - Namespace string // namespace under which the rpc methods of Service are exposed - Version string // deprecated - this field is no longer used, but retained for compatibility - Service interface{} // receiver instance which holds the methods - Public bool // deprecated - this field is no longer used, but retained for compatibility - Authenticated bool // whether the api should only be available behind authentication. + Namespace string // namespace under which the rpc methods of Service are exposed + Version string // deprecated - this field is no longer used, but retained for compatibility + Service any // receiver instance which holds the methods + Public bool // deprecated - this field is no longer used, but retained for compatibility + Authenticated bool // whether the api should only be available behind authentication. } // ServerCodec implements reading, parsing and writing RPC messages for the server side of @@ -52,10 +52,10 @@ type ServerCodec interface { // Implementations must be safe for concurrent use. type jsonWriter interface { // writeJSON writes a message to the connection. - writeJSON(ctx context.Context, msg interface{}, isError bool) error + writeJSON(ctx context.Context, msg any, isError bool) error // Closed returns a channel which is closed when the connection is closed. - closed() <-chan interface{} + closed() <-chan any // RemoteAddr returns the peer address of the connection. remoteAddr() string } diff --git a/rpc/websocket.go b/rpc/websocket.go index 543ff617ba..0bc0503abc 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -293,7 +293,7 @@ type websocketCodec struct { func newWebsocketCodec(conn *websocket.Conn, host string, req http.Header, readLimit int64) ServerCodec { conn.SetReadLimit(readLimit) - encode := func(v interface{}, isErrorResponse bool) error { + encode := func(v any, isErrorResponse bool) error { return conn.WriteJSON(v) } wc := &websocketCodec{ @@ -332,7 +332,7 @@ func (wc *websocketCodec) peerInfo() PeerInfo { return wc.info } -func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}, isError bool) error { +func (wc *websocketCodec) writeJSON(ctx context.Context, v any, isError bool) error { err := wc.jsonCodec.writeJSON(ctx, v, isError) if err == nil { // Notify pingLoop to delay the next idle ping. diff --git a/rpc/websocket_test.go b/rpc/websocket_test.go index 3b7d5a9da0..6eb430fe97 100644 --- a/rpc/websocket_test.go +++ b/rpc/websocket_test.go @@ -406,35 +406,35 @@ func TestWebsocketMethodNameLengthLimit(t *testing.T) { tests := []struct { name string method string - params []interface{} + params []any expectedError string isSubscription bool }{ { name: "valid method name", method: "test_echo", - params: []interface{}{"test", 1}, + params: []any{"test", 1}, expectedError: "", isSubscription: false, }, { name: "method name too long", method: "test_" + string(make([]byte, maxMethodNameLength+1)), - params: []interface{}{"test", 1}, + params: []any{"test", 1}, expectedError: "method name too long", isSubscription: false, }, { name: "valid subscription", method: "nftest_subscribe", - params: []interface{}{"someSubscription", 1, 2}, + params: []any{"someSubscription", 1, 2}, expectedError: "", isSubscription: true, }, { name: "subscription name too long", method: string(make([]byte, maxMethodNameLength+1)) + "_subscribe", - params: []interface{}{"newHeads"}, + params: []any{"newHeads"}, expectedError: "subscription name too long", isSubscription: true, }, @@ -442,7 +442,7 @@ func TestWebsocketMethodNameLengthLimit(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - var result interface{} + var result any err := client.Call(&result, tt.method, tt.params...) if tt.expectedError == "" { if err != nil { diff --git a/signer/core/api.go b/signer/core/api.go index 12acf925f0..eb602e233f 100644 --- a/signer/core/api.go +++ b/signer/core/api.go @@ -58,7 +58,7 @@ type ExternalAPI interface { // SignTransaction request to sign the specified transaction SignTransaction(ctx context.Context, args apitypes.SendTxArgs, methodSelector *string) (*ethapi.SignTransactionResult, error) // SignData - request to sign the given data (plus prefix) - SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error) + SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data any) (hexutil.Bytes, error) // SignTypedData - request to sign the given structured data (plus prefix) SignTypedData(ctx context.Context, addr common.MixedcaseAddress, data apitypes.TypedData) (hexutil.Bytes, error) // EcRecover - recover public key from given message and signature @@ -262,7 +262,7 @@ type ( Text string `json:"text"` } StartupInfo struct { - Info map[string]interface{} `json:"info"` + Info map[string]any `json:"info"` } UserInputRequest struct { Title string `json:"title"` diff --git a/signer/core/apitypes/signed_data_internal_test.go b/signer/core/apitypes/signed_data_internal_test.go index bee9f1c351..b064671ba7 100644 --- a/signer/core/apitypes/signed_data_internal_test.go +++ b/signer/core/apitypes/signed_data_internal_test.go @@ -96,7 +96,7 @@ func TestBytesPadding(t *testing.T) { func TestParseAddress(t *testing.T) { t.Parallel() tests := []struct { - Input interface{} + Input any Output []byte // nil => error }{ { @@ -146,7 +146,7 @@ func TestParseAddress(t *testing.T) { func TestParseBytes(t *testing.T) { t.Parallel() for i, tt := range []struct { - v interface{} + v any exp []byte }{ {"0x", []byte{}}, @@ -182,7 +182,7 @@ func TestParseInteger(t *testing.T) { t.Parallel() for i, tt := range []struct { t string - v interface{} + v any exp *big.Int }{ {"uint32", "-123", nil}, @@ -212,7 +212,7 @@ func TestParseInteger(t *testing.T) { func TestConvertStringDataToSlice(t *testing.T) { t.Parallel() slice := []string{"a", "b", "c"} - var it interface{} = slice + var it any = slice _, err := convertDataToSlice(it) if err != nil { t.Fatal(err) @@ -226,7 +226,7 @@ func TestConvertUint256DataToSlice(t *testing.T) { math.NewHexOrDecimal256(2), math.NewHexOrDecimal256(3), } - var it interface{} = slice + var it any = slice _, err := convertDataToSlice(it) if err != nil { t.Fatal(err) @@ -240,7 +240,7 @@ func TestConvertAddressDataToSlice(t *testing.T) { common.HexToAddress("0x0000000000000000000000000000000000000002"), common.HexToAddress("0x0000000000000000000000000000000000000003"), } - var it interface{} = slice + var it any = slice _, err := convertDataToSlice(it) if err != nil { t.Fatal(err) diff --git a/signer/core/apitypes/types.go b/signer/core/apitypes/types.go index 9034e7e9ca..d9774616a2 100644 --- a/signer/core/apitypes/types.go +++ b/signer/core/apitypes/types.go @@ -348,7 +348,7 @@ type TypePriority struct { Value uint } -type TypedDataMessage = map[string]interface{} +type TypedDataMessage = map[string]any // TypedDataDomain represents the domain part of an EIP-712 message. type TypedDataDomain struct { @@ -447,7 +447,7 @@ func (typedData *TypedData) TypeHash(primaryType string) hexutil.Bytes { // `enc(value₁) ‖ enc(value₂) ‖ … ‖ enc(valueₙ)` // // each encoded member is 32-byte long -func (typedData *TypedData) EncodeData(primaryType string, data map[string]interface{}, depth int) (hexutil.Bytes, error) { +func (typedData *TypedData) EncodeData(primaryType string, data map[string]any, depth int) (hexutil.Bytes, error) { if err := typedData.validate(); err != nil { return nil, err } @@ -473,7 +473,7 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter } buffer.Write(encodedData) } else if typedData.Types[field.Type] != nil { - mapValue, ok := encValue.(map[string]interface{}) + mapValue, ok := encValue.(map[string]any) if !ok { return nil, dataMismatchError(encType, encValue) } @@ -493,7 +493,7 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter return buffer.Bytes(), nil } -func (typedData *TypedData) encodeArrayValue(encValue interface{}, encType string, depth int) (hexutil.Bytes, error) { +func (typedData *TypedData) encodeArrayValue(encValue any, encType string, depth int) (hexutil.Bytes, error) { arrayValue, err := convertDataToSlice(encValue) if err != nil { return nil, dataMismatchError(encType, encValue) @@ -520,7 +520,7 @@ func (typedData *TypedData) encodeArrayValue(encValue interface{}, encType strin arrayBuffer.Write(encodedData) } else { if typedData.Types[parsedType] != nil { - mapValue, ok := item.(map[string]interface{}) + mapValue, ok := item.(map[string]any) if !ok { return nil, dataMismatchError(parsedType, item) } @@ -543,7 +543,7 @@ func (typedData *TypedData) encodeArrayValue(encValue interface{}, encType strin } // Attempt to parse bytes in different formats: byte array, hex string, hexutil.Bytes. -func parseBytes(encType interface{}) ([]byte, bool) { +func parseBytes(encType any) ([]byte, bool) { // Handle array types. val := reflect.ValueOf(encType) if val.Kind() == reflect.Array && val.Type().Elem().Kind() == reflect.Uint8 { @@ -568,7 +568,7 @@ func parseBytes(encType interface{}) ([]byte, bool) { } } -func parseInteger(encType string, encValue interface{}) (*big.Int, error) { +func parseInteger(encType string, encValue any) (*big.Int, error) { var ( length int signed = strings.HasPrefix(encType, "int") @@ -623,7 +623,7 @@ func parseInteger(encType string, encValue interface{}) (*big.Int, error) { // EncodePrimitiveValue deals with the primitive values found // while searching through the typed data -func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error) { +func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue any, depth int) ([]byte, error) { switch encType { case "address": retval := make([]byte, 32) @@ -695,12 +695,12 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf // dataMismatchError generates an error for a mismatch between // the provided type and data -func dataMismatchError(encType string, encValue interface{}) error { +func dataMismatchError(encType string, encValue any) error { return fmt.Errorf("provided data '%v' doesn't match type '%s'", encValue, encType) } -func convertDataToSlice(encValue interface{}) ([]interface{}, error) { - var outEncValue []interface{} +func convertDataToSlice(encValue any) ([]any, error) { + var outEncValue []any rv := reflect.ValueOf(encValue) if rv.Kind() == reflect.Slice { for i := 0; i < rv.Len(); i++ { @@ -724,8 +724,8 @@ func (typedData *TypedData) validate() error { } // Map generates a map version of the typed data -func (typedData *TypedData) Map() map[string]interface{} { - dataMap := map[string]interface{}{ +func (typedData *TypedData) Map() map[string]any { + dataMap := map[string]any{ "types": typedData.Types, "domain": typedData.Domain.Map(), "primaryType": typedData.PrimaryType, @@ -759,7 +759,7 @@ func (typedData *TypedData) Format() ([]*NameValueType, error) { return nvts, nil } -func (typedData *TypedData) formatData(primaryType string, data map[string]interface{}) ([]*NameValueType, error) { +func (typedData *TypedData) formatData(primaryType string, data map[string]any) ([]*NameValueType, error) { var output []*NameValueType // Add field contents. Structs and arrays have special handlers. @@ -775,7 +775,7 @@ func (typedData *TypedData) formatData(primaryType string, data map[string]inter parsedType := field.typeName() for _, v := range arrayValue { if typedData.Types[parsedType] != nil { - mapValue, _ := v.(map[string]interface{}) + mapValue, _ := v.(map[string]any) mapOutput, err := typedData.formatData(parsedType, mapValue) if err != nil { return nil, err @@ -790,7 +790,7 @@ func (typedData *TypedData) formatData(primaryType string, data map[string]inter } } } else if typedData.Types[field.Type] != nil { - if mapValue, ok := encValue.(map[string]interface{}); ok { + if mapValue, ok := encValue.(map[string]any); ok { mapOutput, err := typedData.formatData(field.Type, mapValue) if err != nil { return nil, err @@ -811,7 +811,7 @@ func (typedData *TypedData) formatData(primaryType string, data map[string]inter return output, nil } -func formatPrimitiveValue(encType string, encValue interface{}) (string, error) { +func formatPrimitiveValue(encType string, encValue any) (string, error) { switch encType { case "address": if stringValue, ok := encValue.(string); !ok { @@ -915,8 +915,8 @@ func (domain *TypedDataDomain) validate() error { } // Map is a helper function to generate a map version of the domain -func (domain *TypedDataDomain) Map() map[string]interface{} { - dataMap := map[string]interface{}{} +func (domain *TypedDataDomain) Map() map[string]any { + dataMap := map[string]any{} if domain.ChainId != nil { dataMap["chainId"] = domain.ChainId @@ -943,9 +943,9 @@ func (domain *TypedDataDomain) Map() map[string]interface{} { // NameValueType is a very simple struct with Name, Value and Type. It's meant for simple // json structures used to communicate signing-info about typed data with the UI type NameValueType struct { - Name string `json:"name"` - Value interface{} `json:"value"` - Typ string `json:"type"` + Name string `json:"name"` + Value any `json:"value"` + Typ string `json:"type"` } // Pprint returns a pretty-printed version of nvt diff --git a/signer/core/auditlog.go b/signer/core/auditlog.go index 78785a3b02..3ad1d613c4 100644 --- a/signer/core/auditlog.go +++ b/signer/core/auditlog.go @@ -64,7 +64,7 @@ func (l *AuditLogger) SignTransaction(ctx context.Context, args apitypes.SendTxA return res, e } -func (l *AuditLogger) SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error) { +func (l *AuditLogger) SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data any) (hexutil.Bytes, error) { marshalledData, _ := json.Marshal(data) // can ignore error, marshalling what we just unmarshalled l.log.Info("SignData", "type", "request", "metadata", MetadataFromContext(ctx).String(), "addr", addr.String(), "data", marshalledData, "content-type", contentType) diff --git a/signer/core/signed_data.go b/signer/core/signed_data.go index c62b513145..4311099131 100644 --- a/signer/core/signed_data.go +++ b/signer/core/signed_data.go @@ -74,7 +74,7 @@ func (api *SignerAPI) sign(req *SignDataRequest, legacyV bool) (hexutil.Bytes, e // depending on the content-type specified. // // Different types of validation occur. -func (api *SignerAPI) SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (hexutil.Bytes, error) { +func (api *SignerAPI) SignData(ctx context.Context, contentType string, addr common.MixedcaseAddress, data any) (hexutil.Bytes, error) { var req, transformV, err = api.determineSignatureFormat(ctx, contentType, addr, data) if err != nil { return nil, err @@ -93,7 +93,7 @@ func (api *SignerAPI) SignData(ctx context.Context, contentType string, addr com // charset, ok := params["charset"] // As it is now, we accept any charset and just treat it as 'raw'. // This method returns the mimetype for signing along with the request -func (api *SignerAPI) determineSignatureFormat(ctx context.Context, contentType string, addr common.MixedcaseAddress, data interface{}) (*SignDataRequest, bool, error) { +func (api *SignerAPI) determineSignatureFormat(ctx context.Context, contentType string, addr common.MixedcaseAddress, data any) (*SignDataRequest, bool, error) { var ( req *SignDataRequest useEthereumV = true // Default to use V = 27 or 28, the legacy Ethereum format @@ -319,8 +319,8 @@ func (api *SignerAPI) EcRecover(ctx context.Context, data hexutil.Bytes, sig hex } // UnmarshalValidatorData converts the bytes input to typed data -func UnmarshalValidatorData(data interface{}) (apitypes.ValidatorData, error) { - raw, ok := data.(map[string]interface{}) +func UnmarshalValidatorData(data any) (apitypes.ValidatorData, error) { + raw, ok := data.(map[string]any) if !ok { return apitypes.ValidatorData{}, errors.New("validator input is not a map[string]interface{}") } diff --git a/signer/core/signed_data_test.go b/signer/core/signed_data_test.go index 8455aaf9c5..b57bf0fbb1 100644 --- a/signer/core/signed_data_test.go +++ b/signer/core/signed_data_test.go @@ -163,12 +163,12 @@ var domainStandard = apitypes.TypedDataDomain{ Salt: "", } -var messageStandard = map[string]interface{}{ - "from": map[string]interface{}{ +var messageStandard = map[string]any{ + "from": map[string]any{ "name": "Cow", "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826", }, - "to": map[string]interface{}{ + "to": map[string]any{ "name": "Bob", "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB", }, @@ -1042,7 +1042,7 @@ var recursiveBytesTypesStandard = apitypes.Types{ }, } -var recursiveBytesMessageStandard = map[string]interface{}{ +var recursiveBytesMessageStandard = map[string]any{ "field": [][][]byte{{{1}, {2}}, {{3}, {4}}}, } diff --git a/signer/core/stdioui.go b/signer/core/stdioui.go index a0ce684417..a006bc60fc 100644 --- a/signer/core/stdioui.go +++ b/signer/core/stdioui.go @@ -42,7 +42,7 @@ func (ui *StdIOUI) RegisterUIServer(api *UIServerAPI) { } // dispatch sends a request over the stdio -func (ui *StdIOUI) dispatch(serviceMethod string, args interface{}, reply interface{}) error { +func (ui *StdIOUI) dispatch(serviceMethod string, args any, reply any) error { err := ui.client.Call(&reply, serviceMethod, args) if err != nil { log.Info("Error", "exc", err.Error()) @@ -51,7 +51,7 @@ func (ui *StdIOUI) dispatch(serviceMethod string, args interface{}, reply interf } // notify sends a request over the stdio, and does not listen for a response -func (ui *StdIOUI) notify(serviceMethod string, args interface{}) error { +func (ui *StdIOUI) notify(serviceMethod string, args any) error { ctx := context.Background() err := ui.client.Notify(ctx, serviceMethod, args) if err != nil { diff --git a/signer/fourbyte/abi.go b/signer/fourbyte/abi.go index bdfbd05a1e..be046f235a 100644 --- a/signer/fourbyte/abi.go +++ b/signer/fourbyte/abi.go @@ -38,7 +38,7 @@ type decodedCallData struct { // to an ABI method signature. type decodedArgument struct { soltype abi.Argument - value interface{} + value any } // String implements stringer interface, tries to use the underlying value-type diff --git a/signer/fourbyte/abi_test.go b/signer/fourbyte/abi_test.go index 9656732dff..0fde9d23f2 100644 --- a/signer/fourbyte/abi_test.go +++ b/signer/fourbyte/abi_test.go @@ -26,7 +26,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func verify(t *testing.T, jsondata, calldata string, exp []interface{}) { +func verify(t *testing.T, jsondata, calldata string, exp []any) { abispec, err := abi.JSON(strings.NewReader(jsondata)) if err != nil { t.Fatal(err) @@ -56,14 +56,14 @@ func TestNewUnpacker(t *testing.T) { type unpackTest struct { jsondata string calldata string - exp []interface{} + exp []any } testcases := []unpackTest{ { // https://solidity.readthedocs.io/en/develop/abi-spec.html#use-of-dynamic-types `[{"type":"function","name":"f", "inputs":[{"type":"uint256"},{"type":"uint32[]"},{"type":"bytes10"},{"type":"bytes"}]}]`, // 0x123, [0x456, 0x789], "1234567890", "Hello, world!" "8be65246" + "00000000000000000000000000000000000000000000000000000000000001230000000000000000000000000000000000000000000000000000000000000080313233343536373839300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004560000000000000000000000000000000000000000000000000000000000000789000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20776f726c642100000000000000000000000000000000000000", - []interface{}{ + []any{ big.NewInt(0x123), []uint32{0x456, 0x789}, [10]byte{49, 50, 51, 52, 53, 54, 55, 56, 57, 48}, @@ -73,7 +73,7 @@ func TestNewUnpacker(t *testing.T) { `[{"type":"function","name":"sam","inputs":[{"type":"bytes"},{"type":"bool"},{"type":"uint256[]"}]}]`, // "dave", true and [1,2,3] "a5643bf20000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000464617665000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003", - []interface{}{ + []any{ []byte{0x64, 0x61, 0x76, 0x65}, true, []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}, @@ -81,11 +81,11 @@ func TestNewUnpacker(t *testing.T) { }, { `[{"type":"function","name":"send","inputs":[{"type":"uint256"}]}]`, "a52c101e0000000000000000000000000000000000000000000000000000000000000012", - []interface{}{big.NewInt(0x12)}, + []any{big.NewInt(0x12)}, }, { `[{"type":"function","name":"compareAndApprove","inputs":[{"type":"address"},{"type":"uint256"},{"type":"uint256"}]}]`, "751e107900000000000000000000000000000133700000deadbeef00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", - []interface{}{ + []any{ common.HexToAddress("0x00000133700000deadbeef000000000000000000"), new(big.Int).SetBytes([]byte{0x00}), big.NewInt(0x1), diff --git a/signer/rules/rules.go b/signer/rules/rules.go index c9921e57a9..e4dceacfdd 100644 --- a/signer/rules/rules.go +++ b/signer/rules/rules.go @@ -68,7 +68,7 @@ func (r *rulesetUI) Init(javascriptRules string) error { r.jsRules = javascriptRules return nil } -func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (goja.Value, error) { +func (r *rulesetUI) execute(jsfunc string, jsarg any) (goja.Value, error) { // Instantiate a fresh vm engine every time vm := goja.New() diff --git a/tests/init_test.go b/tests/init_test.go index b933c9808c..992111627d 100644 --- a/tests/init_test.go +++ b/tests/init_test.go @@ -47,7 +47,7 @@ var ( benchmarksDir = filepath.Join(".", "evm-benchmarks", "benchmarks") ) -func readJSON(reader io.Reader, value interface{}) error { +func readJSON(reader io.Reader, value any) error { data, err := io.ReadAll(reader) if err != nil { return fmt.Errorf("error reading JSON file: %v", err) @@ -62,7 +62,7 @@ func readJSON(reader io.Reader, value interface{}) error { return nil } -func readJSONFile(fn string, value interface{}) error { +func readJSONFile(fn string, value any) error { file, err := os.Open(fn) if err != nil { return err @@ -193,7 +193,7 @@ func (tm *testMatcher) checkFailure(t *testing.T, err error) error { // // runTest should be a function of type func(t *testing.T, name string, x ), // where TestType is the type of the test contained in test files. -func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) { +func (tm *testMatcher) walk(t *testing.T, dir string, runTest any) { // Walk the directory. dirinfo, err := os.Stat(dir) if os.IsNotExist(err) || !dirinfo.IsDir() { @@ -218,7 +218,7 @@ func (tm *testMatcher) walk(t *testing.T, dir string, runTest interface{}) { } } -func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest interface{}) { +func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest any) { if r, _ := tm.findSkip(name); r != "" { t.Skip(r) } @@ -252,7 +252,7 @@ func (tm *testMatcher) runTestFile(t *testing.T, path, name string, runTest inte } } -func makeMapFromTestFunc(f interface{}) reflect.Value { +func makeMapFromTestFunc(f any) reflect.Value { stringT := reflect.TypeOf("") testingT := reflect.TypeOf((*testing.T)(nil)) ftyp := reflect.TypeOf(f) @@ -273,7 +273,7 @@ func sortedMapKeys(m reflect.Value) []string { return keys } -func runTestFunc(runTest interface{}, t *testing.T, name string, m reflect.Value, key string) { +func runTestFunc(runTest any, t *testing.T, name string, m reflect.Value, key string) { reflect.ValueOf(runTest).Call([]reflect.Value{ reflect.ValueOf(t), reflect.ValueOf(name), diff --git a/tests/rlp_test_util.go b/tests/rlp_test_util.go index e4bd5450a8..00a10b1521 100644 --- a/tests/rlp_test_util.go +++ b/tests/rlp_test_util.go @@ -36,7 +36,7 @@ type RLPTest struct { // For other JSON values, In is treated as a driver for // calls to rlp.Stream. The test also verifies that encoding // In produces the bytes in Out. - In interface{} + In any // Out is a hex-encoded RLP value. Out string @@ -82,7 +82,7 @@ func (t *RLPTest) Run() error { } func checkDecodeInterface(b []byte, isValid bool) error { - err := rlp.DecodeBytes(b, new(interface{})) + err := rlp.DecodeBytes(b, new(any)) switch { case isValid && err != nil: return fmt.Errorf("decoding failed: %v", err) @@ -93,7 +93,7 @@ func checkDecodeInterface(b []byte, isValid bool) error { } // translateJSON makes test json values encodable with RLP. -func translateJSON(v interface{}) interface{} { +func translateJSON(v any) any { switch v := v.(type) { case float64: return uint64(v) @@ -106,8 +106,8 @@ func translateJSON(v interface{}) interface{} { return big } return []byte(v) - case []interface{}: - new := make([]interface{}, len(v)) + case []any: + new := make([]any, len(v)) for i := range v { new[i] = translateJSON(v[i]) } @@ -121,7 +121,7 @@ func translateJSON(v interface{}) interface{} { // Stream by invoking decoding operations (Uint, Big, List, ...) based // on the type of each value. The value decoded from the RLP stream // must match the JSON value. -func checkDecodeFromJSON(s *rlp.Stream, exp interface{}) error { +func checkDecodeFromJSON(s *rlp.Stream, exp any) error { switch exp := exp.(type) { case uint64: i, err := s.Uint64() @@ -147,7 +147,7 @@ func checkDecodeFromJSON(s *rlp.Stream, exp interface{}) error { if !bytes.Equal(b, exp) { return addStack("Bytes", exp, fmt.Errorf("result mismatch: got %x", b)) } - case []interface{}: + case []any: if _, err := s.List(); err != nil { return addStack("List", exp, err) } @@ -165,7 +165,7 @@ func checkDecodeFromJSON(s *rlp.Stream, exp interface{}) error { return nil } -func addStack(op string, val interface{}, err error) error { +func addStack(op string, val any, err error) error { lines := strings.Split(err.Error(), "\n") lines = append(lines, fmt.Sprintf("\t%s: %v", op, val)) return errors.New(strings.Join(lines, "\n")) diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 3c1df35157..bb38654c20 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -495,7 +495,7 @@ func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (*core.Mess return msg, nil } -func rlpHash(x interface{}) (h common.Hash) { +func rlpHash(x any) (h common.Hash) { hw := sha3.NewLegacyKeccak256() rlp.Encode(hw, x) hw.Sum(h[:0]) diff --git a/trie/hasher.go b/trie/hasher.go index a2a1f5b662..dc1b8117e3 100644 --- a/trie/hasher.go +++ b/trie/hasher.go @@ -125,7 +125,7 @@ func (h *hasher) encodeShortNode(n *shortNode) []byte { // fnEncoderPool is the pool for storing shared fullNode encoder to mitigate // the significant memory allocation overhead. var fnEncoderPool = sync.Pool{ - New: func() interface{} { + New: func() any { var enc fullnodeEncoder return &enc }, diff --git a/trie/iterator.go b/trie/iterator.go index 3d3191ffba..88702cf34c 100644 --- a/trie/iterator.go +++ b/trie/iterator.go @@ -724,11 +724,11 @@ func (it *differenceIterator) Error() error { type nodeIteratorHeap []NodeIterator -func (h nodeIteratorHeap) Len() int { return len(h) } -func (h nodeIteratorHeap) Less(i, j int) bool { return compareNodes(h[i], h[j]) < 0 } -func (h nodeIteratorHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *nodeIteratorHeap) Push(x interface{}) { *h = append(*h, x.(NodeIterator)) } -func (h *nodeIteratorHeap) Pop() interface{} { +func (h nodeIteratorHeap) Len() int { return len(h) } +func (h nodeIteratorHeap) Less(i, j int) bool { return compareNodes(h[i], h[j]) < 0 } +func (h nodeIteratorHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *nodeIteratorHeap) Push(x any) { *h = append(*h, x.(NodeIterator)) } +func (h *nodeIteratorHeap) Pop() any { n := len(*h) x := (*h)[n-1] *h = (*h)[0 : n-1] diff --git a/trie/node_test.go b/trie/node_test.go index 875f6e38dc..30973d2279 100644 --- a/trie/node_test.go +++ b/trie/node_test.go @@ -27,8 +27,8 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -func newTestFullNode(v []byte) []interface{} { - fullNodeData := []interface{}{} +func newTestFullNode(v []byte) []any { + fullNodeData := []any{} for i := 0; i < 16; i++ { k := bytes.Repeat([]byte{byte(i + 1)}, 32) fullNodeData = append(fullNodeData, k) diff --git a/triedb/pathdb/config.go b/triedb/pathdb/config.go index 3745a63edd..e372749e30 100644 --- a/triedb/pathdb/config.go +++ b/triedb/pathdb/config.go @@ -94,8 +94,8 @@ func (c *Config) sanitize() *Config { } // fields returns a list of attributes of config for printing. -func (c *Config) fields() []interface{} { - var list []interface{} +func (c *Config) fields() []any { + var list []any if c.ReadOnly { list = append(list, "readonly", true) } diff --git a/triedb/pathdb/context.go b/triedb/pathdb/context.go index a5704de81a..67b327ead0 100644 --- a/triedb/pathdb/context.go +++ b/triedb/pathdb/context.go @@ -51,22 +51,22 @@ type generatorStats struct { // log creates a contextual log with the given message and the context pulled // from the internally maintained statistics. func (gs *generatorStats) log(msg string, root common.Hash, marker []byte) { - var ctx []interface{} + var ctx []any if root != (common.Hash{}) { - ctx = append(ctx, []interface{}{"root", root}...) + ctx = append(ctx, []any{"root", root}...) } // Figure out whether we're after or within an account switch len(marker) { case common.HashLength: - ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...) + ctx = append(ctx, []any{"at", common.BytesToHash(marker)}...) case 2 * common.HashLength: - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "in", common.BytesToHash(marker[:common.HashLength]), "at", common.BytesToHash(marker[common.HashLength:]), }...) } // Add the usual measurements - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "accounts", gs.accounts, "slots", gs.slots, "storage", gs.storage, @@ -79,7 +79,7 @@ func (gs *generatorStats) log(msg string, root common.Hash, marker []byte) { left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8]) speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond), }...) } diff --git a/triedb/pathdb/generate.go b/triedb/pathdb/generate.go index d3d26fff26..c45824eeac 100644 --- a/triedb/pathdb/generate.go +++ b/triedb/pathdb/generate.go @@ -429,7 +429,7 @@ func (g *generator) generateRange(ctx *generatorContext, trieId *trie.ID, prefix last := result.last() // Construct contextual logger - logCtx := []interface{}{"kind", kind, "prefix", hexutil.Encode(prefix)} + logCtx := []any{"kind", kind, "prefix", hexutil.Encode(prefix)} if len(origin) > 0 { logCtx = append(logCtx, "origin", hexutil.Encode(origin)) } diff --git a/triedb/pathdb/verifier.go b/triedb/pathdb/verifier.go index a69b10f4f3..7a63741b54 100644 --- a/triedb/pathdb/verifier.go +++ b/triedb/pathdb/verifier.go @@ -157,7 +157,7 @@ func (stat *generateStats) report() { stat.lock.RLock() defer stat.lock.RUnlock() - ctx := []interface{}{ + ctx := []any{ "accounts", stat.accounts, "slots", stat.slots, "elapsed", common.PrettyDuration(time.Since(stat.start)), @@ -181,7 +181,7 @@ func (stat *generateStats) report() { } } } - ctx = append(ctx, []interface{}{ + ctx = append(ctx, []any{ "eta", common.PrettyDuration(eta), }...) } @@ -194,12 +194,12 @@ func (stat *generateStats) reportDone() { stat.lock.RLock() defer stat.lock.RUnlock() - var ctx []interface{} - ctx = append(ctx, []interface{}{"accounts", stat.accounts}...) + var ctx []any + ctx = append(ctx, []any{"accounts", stat.accounts}...) if stat.slots != 0 { - ctx = append(ctx, []interface{}{"slots", stat.slots}...) + ctx = append(ctx, []any{"slots", stat.slots}...) } - ctx = append(ctx, []interface{}{"elapsed", common.PrettyDuration(time.Since(stat.start))}...) + ctx = append(ctx, []any{"elapsed", common.PrettyDuration(time.Since(stat.start))}...) log.Info("Iterated snapshot", ctx...) }