diff --git a/accounts/keystore/account_cache.go b/accounts/keystore/account_cache.go index 12f92d2619..002813fca8 100644 --- a/accounts/keystore/account_cache.go +++ b/accounts/keystore/account_cache.go @@ -28,6 +28,7 @@ import ( "time" mapset "github.com/deckarep/golang-set/v2" + "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" diff --git a/accounts/keystore/file_cache.go b/accounts/keystore/file_cache.go index 63eb850374..87cc73a921 100644 --- a/accounts/keystore/file_cache.go +++ b/accounts/keystore/file_cache.go @@ -24,6 +24,7 @@ import ( "time" mapset "github.com/deckarep/golang-set/v2" + "github.com/ethereum/go-ethereum/log" ) diff --git a/accounts/keystore/watch.go b/accounts/keystore/watch.go index 3f64b89c58..20071374f4 100644 --- a/accounts/keystore/watch.go +++ b/accounts/keystore/watch.go @@ -24,6 +24,8 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/fsnotify/fsnotify" + + "github.com/ethereum/go-ethereum/log" ) type watcher struct { diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go index 896cc58009..80d2addfe9 100644 --- a/cmd/abigen/main.go +++ b/cmd/abigen/main.go @@ -30,7 +30,6 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/log" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/checkpoint-admin/common.go b/cmd/checkpoint-admin/common.go index acbe3f19b9..82e246a269 100644 --- a/cmd/checkpoint-admin/common.go +++ b/cmd/checkpoint-admin/common.go @@ -28,7 +28,6 @@ import ( "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" - "github.com/urfave/cli/v2" ) // newClient creates a client with specified remote URL. diff --git a/cmd/checkpoint-admin/exec.go b/cmd/checkpoint-admin/exec.go index cb67d0306d..7d17490005 100644 --- a/cmd/checkpoint-admin/exec.go +++ b/cmd/checkpoint-admin/exec.go @@ -36,7 +36,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" - "github.com/urfave/cli/v2" ) var commandDeploy = &cli.Command{ diff --git a/cmd/checkpoint-admin/main.go b/cmd/checkpoint-admin/main.go index ca0bae7375..766c9be8ea 100644 --- a/cmd/checkpoint-admin/main.go +++ b/cmd/checkpoint-admin/main.go @@ -25,7 +25,6 @@ import ( "github.com/ethereum/go-ethereum/common/fdlimit" "github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/log" - "github.com/urfave/cli/v2" ) var app = flags.NewApp("ethereum checkpoint helper tool") diff --git a/cmd/checkpoint-admin/status.go b/cmd/checkpoint-admin/status.go index bec97aed12..d0231b4661 100644 --- a/cmd/checkpoint-admin/status.go +++ b/cmd/checkpoint-admin/status.go @@ -21,6 +21,8 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/common" ) var commandStatus = &cli.Command{ diff --git a/cmd/clef/run_test.go b/cmd/clef/run_test.go index ecf0d576a3..a491260a3d 100644 --- a/cmd/clef/run_test.go +++ b/cmd/clef/run_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/docker/docker/pkg/reexec" + "github.com/ethereum/go-ethereum/internal/cmdtest" ) diff --git a/cmd/devp2p/discv4cmd.go b/cmd/devp2p/discv4cmd.go index f7b76777e6..35cc1cbbd3 100644 --- a/cmd/devp2p/discv4cmd.go +++ b/cmd/devp2p/discv4cmd.go @@ -30,7 +30,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/params" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/discv5cmd.go b/cmd/devp2p/discv5cmd.go index 832a4bc1f4..f706563e30 100644 --- a/cmd/devp2p/discv5cmd.go +++ b/cmd/devp2p/discv5cmd.go @@ -24,7 +24,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/p2p/discover" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/dns_cloudflare.go b/cmd/devp2p/dns_cloudflare.go index 7f6749cf0b..aeb861eece 100644 --- a/cmd/devp2p/dns_cloudflare.go +++ b/cmd/devp2p/dns_cloudflare.go @@ -24,7 +24,6 @@ import ( "github.com/cloudflare/cloudflare-go" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p/dnsdisc" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/dns_route53.go b/cmd/devp2p/dns_route53.go index c98a4cd4fe..fbab05e709 100644 --- a/cmd/devp2p/dns_route53.go +++ b/cmd/devp2p/dns_route53.go @@ -32,7 +32,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/route53/types" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p/dnsdisc" - "github.com/urfave/cli/v2" ) const ( diff --git a/cmd/devp2p/dnscmd.go b/cmd/devp2p/dnscmd.go index 88baed51a9..43c3c63601 100644 --- a/cmd/devp2p/dnscmd.go +++ b/cmd/devp2p/dnscmd.go @@ -29,7 +29,6 @@ import ( "github.com/ethereum/go-ethereum/console/prompt" "github.com/ethereum/go-ethereum/p2p/dnsdisc" "github.com/ethereum/go-ethereum/p2p/enode" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/enrcmd.go b/cmd/devp2p/enrcmd.go index 2110437103..cb333a00ea 100644 --- a/cmd/devp2p/enrcmd.go +++ b/cmd/devp2p/enrcmd.go @@ -30,7 +30,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/rlp" - "github.com/urfave/cli/v2" ) var fileFlag = &cli.StringFlag{Name: "file"} diff --git a/cmd/devp2p/keycmd.go b/cmd/devp2p/keycmd.go index c2de9ad185..3ec28581b2 100644 --- a/cmd/devp2p/keycmd.go +++ b/cmd/devp2p/keycmd.go @@ -23,7 +23,6 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enr" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/main.go b/cmd/devp2p/main.go index 2bb7506cce..c6e75f172a 100644 --- a/cmd/devp2p/main.go +++ b/cmd/devp2p/main.go @@ -23,7 +23,6 @@ import ( "github.com/ethereum/go-ethereum/internal/debug" "github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/p2p/enode" - "github.com/urfave/cli/v2" ) var app = flags.NewApp("go-ethereum devp2p tool") diff --git a/cmd/devp2p/nodesetcmd.go b/cmd/devp2p/nodesetcmd.go index 093545affb..aaffd56b2c 100644 --- a/cmd/devp2p/nodesetcmd.go +++ b/cmd/devp2p/nodesetcmd.go @@ -29,7 +29,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/rlpxcmd.go b/cmd/devp2p/rlpxcmd.go index a1d6fe2f95..a36171e738 100644 --- a/cmd/devp2p/rlpxcmd.go +++ b/cmd/devp2p/rlpxcmd.go @@ -25,7 +25,6 @@ import ( "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/rlpx" "github.com/ethereum/go-ethereum/rlp" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/devp2p/runtest.go b/cmd/devp2p/runtest.go index f72aa91119..bf19d62b14 100644 --- a/cmd/devp2p/runtest.go +++ b/cmd/devp2p/runtest.go @@ -22,7 +22,6 @@ import ( "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test" "github.com/ethereum/go-ethereum/internal/utesting" "github.com/ethereum/go-ethereum/log" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/ethkey/changepassword.go b/cmd/ethkey/changepassword.go index 4298e2b834..8eb1b64a0a 100644 --- a/cmd/ethkey/changepassword.go +++ b/cmd/ethkey/changepassword.go @@ -23,7 +23,6 @@ import ( "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/cmd/utils" - "github.com/urfave/cli/v2" ) var newPassphraseFlag = &cli.StringFlag{ diff --git a/cmd/ethkey/inspect.go b/cmd/ethkey/inspect.go index 29b1c13e85..0164085e22 100644 --- a/cmd/ethkey/inspect.go +++ b/cmd/ethkey/inspect.go @@ -24,7 +24,6 @@ import ( "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/crypto" - "github.com/urfave/cli/v2" ) type outputInspect struct { diff --git a/cmd/ethkey/main.go b/cmd/ethkey/main.go index 25c0d104f6..1acc13af9e 100644 --- a/cmd/ethkey/main.go +++ b/cmd/ethkey/main.go @@ -22,6 +22,8 @@ import ( "github.com/ethereum/go-ethereum/internal/flags" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/internal/flags" ) const ( diff --git a/cmd/ethkey/message.go b/cmd/ethkey/message.go index 0f12f7b7bf..1ca610ebb9 100644 --- a/cmd/ethkey/message.go +++ b/cmd/ethkey/message.go @@ -26,7 +26,6 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" - "github.com/urfave/cli/v2" ) type outputSign struct { diff --git a/cmd/ethkey/utils.go b/cmd/ethkey/utils.go index 2821145089..94e55c52a0 100644 --- a/cmd/ethkey/utils.go +++ b/cmd/ethkey/utils.go @@ -24,6 +24,8 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/cmd/utils" ) // getPassphrase obtains a passphrase given by the user. It first checks the diff --git a/cmd/evm/blockrunner.go b/cmd/evm/blockrunner.go index a50e7d9bca..8adc10183d 100644 --- a/cmd/evm/blockrunner.go +++ b/cmd/evm/blockrunner.go @@ -22,9 +22,10 @@ import ( "fmt" "os" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/tests" - "github.com/urfave/cli/v2" ) var blockTestCommand = &cli.Command{ diff --git a/cmd/evm/disasm.go b/cmd/evm/disasm.go index a6a16fd13b..d4137400df 100644 --- a/cmd/evm/disasm.go +++ b/cmd/evm/disasm.go @@ -24,6 +24,8 @@ import ( "github.com/ethereum/go-ethereum/core/asm" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/core/asm" ) var disasmCommand = &cli.Command{ diff --git a/cmd/evm/internal/t8ntool/block.go b/cmd/evm/internal/t8ntool/block.go index 75f04bc4a0..d6ec6d3f4e 100644 --- a/cmd/evm/internal/t8ntool/block.go +++ b/cmd/evm/internal/t8ntool/block.go @@ -34,7 +34,6 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" - "github.com/urfave/cli/v2" ) //go:generate go run github.com/fjl/gencodec -type header -field-override headerMarshaling -out gen_header.go diff --git a/cmd/evm/internal/t8ntool/flags.go b/cmd/evm/internal/t8ntool/flags.go index 339523593a..b53e294f1a 100644 --- a/cmd/evm/internal/t8ntool/flags.go +++ b/cmd/evm/internal/t8ntool/flags.go @@ -22,7 +22,6 @@ import ( "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/tests" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/evm/internal/t8ntool/transaction.go b/cmd/evm/internal/t8ntool/transaction.go index 945a9b53be..74a36e4d31 100644 --- a/cmd/evm/internal/t8ntool/transaction.go +++ b/cmd/evm/internal/t8ntool/transaction.go @@ -32,7 +32,6 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/tests" - "github.com/urfave/cli/v2" ) type result struct { diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go index a5dc03d6dc..70cd753122 100644 --- a/cmd/evm/internal/t8ntool/transition.go +++ b/cmd/evm/internal/t8ntool/transition.go @@ -39,7 +39,6 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/tests" - "github.com/urfave/cli/v2" ) const ( diff --git a/cmd/evm/main.go b/cmd/evm/main.go index 35f3e37ae5..7655babdcf 100644 --- a/cmd/evm/main.go +++ b/cmd/evm/main.go @@ -24,7 +24,6 @@ import ( "github.com/ethereum/go-ethereum/cmd/evm/internal/t8ntool" "github.com/ethereum/go-ethereum/internal/flags" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/evm/runner.go b/cmd/evm/runner.go index 870fee5368..16fb8f1eae 100644 --- a/cmd/evm/runner.go +++ b/cmd/evm/runner.go @@ -41,7 +41,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/trie" - "github.com/urfave/cli/v2" ) var runCommand = &cli.Command{ diff --git a/cmd/evm/staterunner.go b/cmd/evm/staterunner.go index 462530f7f8..42cdf7279d 100644 --- a/cmd/evm/staterunner.go +++ b/cmd/evm/staterunner.go @@ -28,7 +28,6 @@ import ( "github.com/ethereum/go-ethereum/eth/tracers/logger" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/tests" - "github.com/urfave/cli/v2" ) var stateTestCommand = &cli.Command{ diff --git a/cmd/geth/accountcmd.go b/cmd/geth/accountcmd.go index eb4de5d930..9bd437d7b4 100644 --- a/cmd/geth/accountcmd.go +++ b/cmd/geth/accountcmd.go @@ -25,7 +25,6 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/chaincmd.go b/cmd/geth/chaincmd.go index a0f38f2eb2..16472617e4 100644 --- a/cmd/geth/chaincmd.go +++ b/cmd/geth/chaincmd.go @@ -40,7 +40,6 @@ import ( "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/trie" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/consolecmd.go b/cmd/geth/consolecmd.go index 4eb1c2bc33..e44b75ec50 100644 --- a/cmd/geth/consolecmd.go +++ b/cmd/geth/consolecmd.go @@ -18,7 +18,6 @@ package main import ( "fmt" - "github.com/ethereum/go-ethereum/node" "os" "path/filepath" "strings" @@ -26,7 +25,6 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/console" "github.com/ethereum/go-ethereum/internal/flags" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/misccmd.go b/cmd/geth/misccmd.go index 76baa9a8ed..130619c4be 100644 --- a/cmd/geth/misccmd.go +++ b/cmd/geth/misccmd.go @@ -27,7 +27,6 @@ import ( "github.com/ethereum/go-ethereum/consensus/ethash" "github.com/ethereum/go-ethereum/internal/version" "github.com/ethereum/go-ethereum/params" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/snapshot.go b/cmd/geth/snapshot.go index ac2f3d1045..2262a9b0cb 100644 --- a/cmd/geth/snapshot.go +++ b/cmd/geth/snapshot.go @@ -35,7 +35,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/trie" - "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/verkle.go b/cmd/geth/verkle.go index 0c6299b444..95449ebe3a 100644 --- a/cmd/geth/verkle.go +++ b/cmd/geth/verkle.go @@ -23,13 +23,14 @@ import ( "fmt" "os" + "github.com/gballet/go-verkle" + cli "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/log" - "github.com/gballet/go-verkle" - cli "github.com/urfave/cli/v2" ) var ( diff --git a/cmd/geth/version_check.go b/cmd/geth/version_check.go index 237556788e..e459d78c65 100644 --- a/cmd/geth/version_check.go +++ b/cmd/geth/version_check.go @@ -29,6 +29,8 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/jedisct1/go-minisign" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/log" ) var gethPubKeys []string = []string{ diff --git a/cmd/p2psim/main.go b/cmd/p2psim/main.go index a3546d405b..2424509ca3 100644 --- a/cmd/p2psim/main.go +++ b/cmd/p2psim/main.go @@ -51,7 +51,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations" "github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/rpc" - "github.com/urfave/cli/v2" ) var client *simulations.Client diff --git a/cmd/utils/bor_flags.go b/cmd/utils/bor_flags.go index 43d83c86a6..72b66984dd 100644 --- a/cmd/utils/bor_flags.go +++ b/cmd/utils/bor_flags.go @@ -2,8 +2,6 @@ package utils import ( "encoding/json" - "github.com/ethereum/go-ethereum/eth/ethconfig" - "github.com/urfave/cli/v2" "os" "github.com/ethereum/go-ethereum/core" diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 5fbd8a15b8..e9f2e24b40 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -41,7 +41,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/rlp" - "github.com/urfave/cli/v2" ) const ( diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 34899d00d4..67b246c03e 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -24,7 +24,6 @@ import ( "encoding/hex" "errors" "fmt" - "github.com/ethereum/go-ethereum/trie" "math" "math/big" "net/http" @@ -75,9 +74,6 @@ import ( "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rpc" - pcsclite "github.com/gballet/go-libpcsclite" - gopsutil "github.com/shirou/gopsutil/mem" - "github.com/urfave/cli/v2" ) // These are all the command line flags we support. diff --git a/cmd/utils/flags_legacy.go b/cmd/utils/flags_legacy.go index 973bd0c1a9..1b49423569 100644 --- a/cmd/utils/flags_legacy.go +++ b/cmd/utils/flags_legacy.go @@ -19,8 +19,9 @@ package utils import ( "fmt" - "github.com/ethereum/go-ethereum/internal/flags" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/internal/flags" ) var ShowDeprecated = &cli.Command{ diff --git a/common/bytes.go b/common/bytes.go index d1f5c6c995..9ae94f5cef 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -101,6 +101,7 @@ func ParseHexOrString(str string) ([]byte, error) { if errors.Is(err, hexutil.ErrMissingPrefix) { return []byte(str), nil } + return b, err } diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index 9de94017c2..232163ed5f 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -70,9 +70,11 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) } + if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil { return nil, fmt.Errorf("solc: error reading userdoc definition (%v)", err) } + if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil { return nil, fmt.Errorf("solc: error reading devdoc definition (%v)", err) } diff --git a/common/lru/basiclru.go b/common/lru/basiclru.go index a429157fe5..a7f8875beb 100644 --- a/common/lru/basiclru.go +++ b/common/lru/basiclru.go @@ -37,11 +37,13 @@ func NewBasicLRU[K comparable, V any](capacity int) BasicLRU[K, V] { if capacity <= 0 { capacity = 1 } + c := BasicLRU[K, V]{ items: make(map[K]cacheItem[K, V]), list: newList[K](), cap: capacity, } + return c } @@ -53,6 +55,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) { item.value = value c.items[key] = item c.list.moveToFront(item.elem) + return false } @@ -60,6 +63,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) { if c.Len() >= c.cap { elem = c.list.removeLast() delete(c.items, elem.v) + evicted = true } else { elem = new(listElem[K]) @@ -70,6 +74,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) { elem.v = key c.items[key] = cacheItem[K, V]{elem, value} c.list.pushElem(elem) + return evicted } @@ -85,7 +90,9 @@ func (c *BasicLRU[K, V]) Get(key K) (value V, ok bool) { if !ok { return value, false } + c.list.moveToFront(item.elem) + return item.value, true } @@ -96,8 +103,10 @@ func (c *BasicLRU[K, V]) GetOldest() (key K, value V, ok bool) { if lastElem == nil { return key, value, false } + key = lastElem.v item := c.items[key] + return key, item.value, true } @@ -115,6 +124,7 @@ func (c *BasicLRU[K, V]) Peek(key K) (value V, ok bool) { // Purge empties the cache. func (c *BasicLRU[K, V]) Purge() { c.list.init() + for k := range c.items { delete(c.items, k) } @@ -127,6 +137,7 @@ func (c *BasicLRU[K, V]) Remove(key K) bool { delete(c.items, key) c.list.remove(item.elem) } + return ok } @@ -141,6 +152,7 @@ func (c *BasicLRU[K, V]) RemoveOldest() (key K, value V, ok bool) { item := c.items[key] delete(c.items, key) c.list.remove(lastElem) + return key, item.value, true } @@ -165,6 +177,7 @@ type listElem[T any] struct { func newList[T any]() *list[T] { l := new(list[T]) l.init() + return l } @@ -202,6 +215,7 @@ func (l *list[T]) removeLast() *listElem[T] { if last != nil { l.remove(last) } + return last } @@ -211,6 +225,7 @@ func (l *list[T]) last() *listElem[T] { if e == &l.root { return nil } + return e } @@ -219,5 +234,6 @@ func (l *list[T]) appendTo(slice []T) []T { for e := l.root.prev; e != &l.root; e = e.prev { slice = append(slice, e.v) } + return slice } diff --git a/common/lru/basiclru_test.go b/common/lru/basiclru_test.go index 27ba770879..0b29a1f15d 100644 --- a/common/lru/basiclru_test.go +++ b/common/lru/basiclru_test.go @@ -33,6 +33,7 @@ func TestBasicLRU(t *testing.T) { for i := 0; i < 256; i++ { cache.Add(i, i) } + if cache.Len() != 128 { t.Fatalf("bad len: %v", cache.Len()) } @@ -42,14 +43,17 @@ func TestBasicLRU(t *testing.T) { if len(keys) != 128 { t.Fatal("wrong Keys() length", len(keys)) } + for i, k := range keys { v, ok := cache.Peek(k) if !ok { t.Fatalf("expected key %d be present", i) } + if v != k { t.Fatalf("expected %d == %d", k, v) } + if v != i+128 { t.Fatalf("wrong value at key %d: %d, want %d", i, v, i+128) } @@ -61,6 +65,7 @@ func TestBasicLRU(t *testing.T) { t.Fatalf("%d should be evicted", i) } } + for i := 128; i < 256; i++ { _, ok := cache.Get(i) if !ok { @@ -73,11 +78,15 @@ func TestBasicLRU(t *testing.T) { if !ok { t.Fatalf("%d should be in cache", i) } + ok = cache.Remove(i) + if ok { t.Fatalf("%d should not be in cache", i) } + _, ok = cache.Get(i) + if ok { t.Fatalf("%d should be deleted", i) } @@ -93,9 +102,11 @@ func TestBasicLRU(t *testing.T) { } cache.Purge() + if cache.Len() != 0 { t.Fatalf("bad len: %v", cache.Len()) } + if _, ok := cache.Get(200); ok { t.Fatalf("should contain nothing") } @@ -128,6 +139,7 @@ func TestBasicLRUGetOldest(t *testing.T) { if !ok { t.Fatalf("missing") } + if k != 128 { t.Fatalf("bad: %v", k) } @@ -136,6 +148,7 @@ func TestBasicLRUGetOldest(t *testing.T) { if !ok { t.Fatalf("missing") } + if k != 128 { t.Fatalf("bad: %v", k) } @@ -144,6 +157,7 @@ func TestBasicLRUGetOldest(t *testing.T) { if !ok { t.Fatalf("missing oldest item") } + if k != 129 { t.Fatalf("wrong oldest item: %v", k) } @@ -157,6 +171,7 @@ func TestBasicLRUAddReturnValue(t *testing.T) { if cache.Add(1, 1) { t.Errorf("first add shouldn't have evicted") } + if !cache.Add(2, 2) { t.Errorf("second add should have evicted") } @@ -169,10 +184,13 @@ func TestBasicLRUContains(t *testing.T) { cache := NewBasicLRU[int, int](2) cache.Add(1, 1) cache.Add(2, 2) + if !cache.Contains(1) { t.Errorf("1 should be in the cache") } + cache.Add(3, 3) + if cache.Contains(1) { t.Errorf("Contains should not have updated recency of 1") } @@ -185,9 +203,11 @@ func BenchmarkLRU(b *testing.B) { keys = make([]string, capacity) values = make([][]byte, capacity) ) + for i := range indexes { indexes[i] = rand.Intn(capacity) } + for i := range keys { b := make([]byte, 32) crand.Read(b) diff --git a/common/lru/blob_lru.go b/common/lru/blob_lru.go index c9b3398503..2ae39a092b 100644 --- a/common/lru/blob_lru.go +++ b/common/lru/blob_lru.go @@ -63,15 +63,20 @@ func (c *SizeConstrainedCache[K, V]) Add(key K, value V) (evicted bool) { for targetSize > c.maxSize { evicted = true _, v, ok := c.lru.RemoveOldest() + if !ok { // list is now empty. Break break } + targetSize -= uint64(len(v)) } + c.size = targetSize } + c.lru.Add(key, value) + return evicted } diff --git a/common/lru/blob_lru_test.go b/common/lru/blob_lru_test.go index 83e12c99ee..30ca368206 100644 --- a/common/lru/blob_lru_test.go +++ b/common/lru/blob_lru_test.go @@ -33,6 +33,7 @@ func TestSizeConstrainedCache(t *testing.T) { t.Parallel() lru := NewSizeConstrainedCache[testKey, []byte](100) + var want uint64 // Add 11 items of 10 byte each. First item should be swapped out for i := 0; i < 11; i++ { @@ -40,9 +41,11 @@ func TestSizeConstrainedCache(t *testing.T) { v := fmt.Sprintf("value-%04d", i) lru.Add(k, []byte(v)) want += uint64(len(v)) + if want > 100 { want = 100 } + if have := lru.size; have != want { t.Fatalf("size wrong, have %d want %d", have, want) } @@ -59,9 +62,11 @@ func TestSizeConstrainedCache(t *testing.T) { k := mkKey(i) want := fmt.Sprintf("value-%04d", i) have, ok := lru.Get(k) + if !ok { t.Fatalf("missing key %v", k) } + if string(have) != want { t.Fatalf("wrong value, have %v want %v", have, want) } @@ -118,6 +123,7 @@ func TestSizeConstrainedCacheSameItem(t *testing.T) { // Add one 10 byte-item 10 times. k := mkKey(0) v := fmt.Sprintf("value-%04d", 0) + for i := 0; i < 10; i++ { lru.Add(k, []byte(v)) } diff --git a/common/math/big.go b/common/math/big.go index 5937c73721..d814eed2ec 100644 --- a/common/math/big.go +++ b/common/math/big.go @@ -59,6 +59,7 @@ func (i *HexOrDecimal256) UnmarshalJSON(input []byte) error { if len(input) > 0 && input[0] == '"' { input = input[1 : len(input)-1] } + return i.UnmarshalText(input) } diff --git a/common/math/integer.go b/common/math/integer.go index da01c0a08e..bdb19af146 100644 --- a/common/math/integer.go +++ b/common/math/integer.go @@ -49,6 +49,7 @@ func (i *HexOrDecimal64) UnmarshalJSON(input []byte) error { if len(input) > 0 && input[0] == '"' { input = input[1 : len(input)-1] } + return i.UnmarshalText(input) } diff --git a/common/mclock/alarm.go b/common/mclock/alarm.go index e83810a6a0..7907174e63 100644 --- a/common/mclock/alarm.go +++ b/common/mclock/alarm.go @@ -38,6 +38,7 @@ func NewAlarm(clock Clock) *Alarm { if clock == nil { panic("nil clock") } + return &Alarm{ ch: make(chan struct{}, 1), clock: clock, @@ -57,6 +58,7 @@ func (e *Alarm) Stop() { if e.timer != nil { e.timer.Stop() } + e.deadline = 0 // Drain the channel. @@ -84,16 +86,19 @@ func (e *Alarm) schedule(now, newDeadline AbsTime) { // to be rescheduled. return } + e.timer.Stop() } // Set the timer. d := time.Duration(0) + if newDeadline < now { newDeadline = now } else { d = newDeadline.Sub(now) } + e.timer = e.clock.AfterFunc(d, e.send) e.deadline = newDeadline } diff --git a/common/mclock/alarm_test.go b/common/mclock/alarm_test.go index 01ba7299ec..8efc3007db 100644 --- a/common/mclock/alarm_test.go +++ b/common/mclock/alarm_test.go @@ -27,37 +27,47 @@ func TestAlarm(t *testing.T) { a := NewAlarm(clk) a.Schedule(clk.Now() + 10) + if recv(a.C()) { t.Fatal("Alarm fired before scheduled deadline") } + if ntimers := clk.ActiveTimers(); ntimers != 1 { t.Fatal("clock has", ntimers, "active timers, want", 1) } + clk.Run(5) + if recv(a.C()) { t.Fatal("Alarm fired too early") } clk.Run(5) + if !recv(a.C()) { t.Fatal("Alarm did not fire") } + if recv(a.C()) { t.Fatal("Alarm fired twice") } + if ntimers := clk.ActiveTimers(); ntimers != 0 { t.Fatal("clock has", ntimers, "active timers, want", 0) } a.Schedule(clk.Now() + 5) + if recv(a.C()) { t.Fatal("Alarm fired before scheduled deadline when scheduling the second event") } clk.Run(5) + if !recv(a.C()) { t.Fatal("Alarm did not fire when scheduling the second event") } + if recv(a.C()) { t.Fatal("Alarm fired twice when scheduling the second event") } @@ -76,6 +86,7 @@ func TestAlarmScheduleEarlier(t *testing.T) { clk.Run(5) a.Schedule(clk.Now() + 1) clk.Run(3) + if !recv(a.C()) { t.Fatal("Alarm did not fire") } @@ -94,6 +105,7 @@ func TestAlarmScheduleLater(t *testing.T) { clk.Run(5) a.Schedule(clk.Now() + 100) clk.Run(50) + if !recv(a.C()) { t.Fatal("Alarm did not fire") } @@ -109,6 +121,7 @@ func TestAlarmNegative(t *testing.T) { a.Schedule(-1) clk.Run(1) // needed to process timers + if !recv(a.C()) { t.Fatal("Alarm did not fire for negative time") } diff --git a/common/prque/lazyqueue.go b/common/prque/lazyqueue.go index 59bda72fa7..ee0bd7e47f 100644 --- a/common/prque/lazyqueue.go +++ b/common/prque/lazyqueue.go @@ -22,6 +22,8 @@ import ( "github.com/ethereum/go-ethereum/common/mclock" "golang.org/x/exp/constraints" + + "github.com/ethereum/go-ethereum/common/mclock" ) // LazyQueue is a priority queue data structure where priorities can change over diff --git a/common/types_test.go b/common/types_test.go index 02a92f8c6c..4e6d4d1a70 100644 --- a/common/types_test.go +++ b/common/types_test.go @@ -167,28 +167,34 @@ func TestMixedcaseAddressMarshal(t *testing.T) { output string input = "0xae967917c465db8578ca9024c205720b1a3651A9" ) + addr, err := NewMixedcaseAddressFromString(input) + if err != nil { t.Fatal(err) } + blob, err := json.Marshal(*addr) + if err != nil { t.Fatal(err) } json.Unmarshal(blob, &output) + if output != input { t.Fatal("Failed to marshal/unmarshal MixedcaseAddress object") } } func TestMixedcaseAccount_Address(t *testing.T) { - // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md - // Note: 0X{checksum_addr} is not valid according to spec above - + t.Parallel() var res []struct { A MixedcaseAddress Valid bool } + + // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md + // Note: 0X{checksum_addr} is not valid according to spec above if err := json.Unmarshal([]byte(`[ {"A" : "0xae967917c465db8578ca9024c205720b1a3651A9", "Valid": false}, {"A" : "0xAe967917c465db8578ca9024c205720b1a3651A9", "Valid": true}, diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index a3d2626ff6..81aba374ba 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -26,6 +26,8 @@ import ( "time" mapset "github.com/deckarep/golang-set/v2" + "golang.org/x/crypto/sha3" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/consensus" diff --git a/consensus/misc/eip1559.go b/consensus/misc/eip1559.go index 50e18d3d82..4679efa2f1 100644 --- a/consensus/misc/eip1559.go +++ b/consensus/misc/eip1559.go @@ -67,8 +67,8 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int { } var ( - num = new(big.Int) - denom = new(big.Int) + num = new(big.Int) + denom = new(big.Int) baseFeeChangeDenominatorUint64 = params.BaseFeeChangeDenominator(config.Bor, parent.Number) ) diff --git a/core/blockchain.go b/core/blockchain.go index 07003e4753..87b2fdb2fc 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -22,7 +22,6 @@ import ( "context" "errors" "fmt" - "github.com/ethereum/go-ethereum/rlp" "io" "math/big" "os" diff --git a/core/blockchain_reader.go b/core/blockchain_reader.go index 6601f915ae..b15664415e 100644 --- a/core/blockchain_reader.go +++ b/core/blockchain_reader.go @@ -17,7 +17,6 @@ package core import ( - "github.com/ethereum/go-ethereum/ethdb" "math/big" "github.com/ethereum/go-ethereum/common" diff --git a/core/forkchoice_test.go b/core/forkchoice_test.go index be78488cca..03e684ac35 100644 --- a/core/forkchoice_test.go +++ b/core/forkchoice_test.go @@ -1,7 +1,6 @@ package core import ( - "github.com/ethereum/go-ethereum/trie" "math/big" "testing" diff --git a/core/rawdb/accessors_trie.go b/core/rawdb/accessors_trie.go index e240213025..cbc8579ede 100644 --- a/core/rawdb/accessors_trie.go +++ b/core/rawdb/accessors_trie.go @@ -20,11 +20,12 @@ import ( "fmt" "sync" + "golang.org/x/crypto/sha3" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" - "golang.org/x/crypto/sha3" ) // HashScheme is the legacy hash-based state scheme with which trie nodes are diff --git a/core/rawdb/freezer.go b/core/rawdb/freezer.go index 213fb1de5b..6e763c2b51 100644 --- a/core/rawdb/freezer.go +++ b/core/rawdb/freezer.go @@ -30,7 +30,6 @@ import ( "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" - "github.com/gofrs/flock" ) var ( diff --git a/core/txpool/list_test.go b/core/txpool/list_test.go index cb6a24c1c2..19d721a743 100644 --- a/core/txpool/list_test.go +++ b/core/txpool/list_test.go @@ -17,7 +17,6 @@ package txpool import ( - "github.com/holiman/uint256" "math/big" "math/rand" "testing" diff --git a/core/types/receipt_test.go b/core/types/receipt_test.go index 376177f976..a5d28a0a7e 100644 --- a/core/types/receipt_test.go +++ b/core/types/receipt_test.go @@ -27,7 +27,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" - "github.com/kylelemons/godebug/diff" ) var ( diff --git a/eth/backend.go b/eth/backend.go index 746472b070..820442f10a 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -21,7 +21,6 @@ import ( "context" "errors" "fmt" - "github.com/ethereum/go-ethereum/trie" "math/big" "runtime" "sync" diff --git a/eth/fetcher/tx_fetcher.go b/eth/fetcher/tx_fetcher.go index 2883713036..7854a9a5a8 100644 --- a/eth/fetcher/tx_fetcher.go +++ b/eth/fetcher/tx_fetcher.go @@ -25,6 +25,7 @@ import ( "time" mapset "github.com/deckarep/golang-set/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/core/txpool" diff --git a/eth/protocols/eth/peer.go b/eth/protocols/eth/peer.go index 219f486c8e..433858893c 100644 --- a/eth/protocols/eth/peer.go +++ b/eth/protocols/eth/peer.go @@ -22,6 +22,7 @@ import ( "sync" mapset "github.com/deckarep/golang-set/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/p2p" diff --git a/eth/protocols/snap/sync.go b/eth/protocols/snap/sync.go index 466a48e36b..4292ba8ac9 100644 --- a/eth/protocols/snap/sync.go +++ b/eth/protocols/snap/sync.go @@ -43,7 +43,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/msgrate" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/trie" - "golang.org/x/crypto/sha3" ) const ( diff --git a/eth/tracers/js/internal/tracers/tracers.go b/eth/tracers/js/internal/tracers/tracers.go index 6547f1b088..9ca3b08064 100644 --- a/eth/tracers/js/internal/tracers/tracers.go +++ b/eth/tracers/js/internal/tracers/tracers.go @@ -31,6 +31,7 @@ var files embed.FS // returns a mapping of tracer name to source. func Load() (map[string]string, error) { var assetTracers = make(map[string]string) + err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error { if err != nil { return err @@ -46,6 +47,7 @@ func Load() (map[string]string, error) { assetTracers[name] = string(b) return nil }) + return assetTracers, err } @@ -55,5 +57,6 @@ func camel(str string) string { for i := 1; i < len(pieces); i++ { pieces[i] = string(unicode.ToUpper(rune(pieces[i][0]))) + pieces[i][1:] } + return strings.Join(pieces, "") } diff --git a/ethclient/gethclient/gethclient_test.go b/ethclient/gethclient/gethclient_test.go index b1889f7935..ad7909d14d 100644 --- a/ethclient/gethclient/gethclient_test.go +++ b/ethclient/gethclient/gethclient_test.go @@ -392,17 +392,17 @@ func TestOverrideAccountMarshal(t *testing.T) { t.Parallel() om := map[common.Address]OverrideAccount{ - common.Address{0x11}: OverrideAccount{ + {0x11}: { // Zero-valued nonce is not overriddden, but simply dropped by the encoder. Nonce: 0, }, - common.Address{0xaa}: OverrideAccount{ + {0xaa}: { Nonce: 5, }, - common.Address{0xbb}: OverrideAccount{ + {0xbb}: { Code: []byte{1}, }, - common.Address{0xcc}: OverrideAccount{ + {0xcc}: { // 'code', 'balance', 'state' should be set when input is // a non-nil but empty value. Code: []byte{}, diff --git a/ethdb/dbtest/testsuite.go b/ethdb/dbtest/testsuite.go index bd924f97d0..98305a528f 100644 --- a/ethdb/dbtest/testsuite.go +++ b/ethdb/dbtest/testsuite.go @@ -499,18 +499,22 @@ func randBytes(length int) []byte { if n, err := rand.Read(buf); n != length || err != nil { panic(err) } + return buf } func makeDataset(size, ksize, vsize int, order bool) ([][]byte, [][]byte) { var keys [][]byte var vals [][]byte + for i := 0; i < size; i += 1 { keys = append(keys, randBytes(ksize)) vals = append(vals, randBytes(vsize)) } + if order { sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 }) } + return keys, vals } diff --git a/ethdb/memorydb/memorydb.go b/ethdb/memorydb/memorydb.go index 7e4fd7e5e7..08799425c6 100644 --- a/ethdb/memorydb/memorydb.go +++ b/ethdb/memorydb/memorydb.go @@ -292,7 +292,9 @@ func (it *iterator) Next() bool { if it.index >= len(it.keys) { return false } + it.index += 1 + return it.index < len(it.keys) } @@ -310,6 +312,7 @@ func (it *iterator) Key() []byte { if it.index < 0 || it.index >= len(it.keys) { return nil } + return []byte(it.keys[it.index]) } @@ -321,6 +324,7 @@ func (it *iterator) Value() []byte { if it.index < 0 || it.index >= len(it.keys) { return nil } + return it.values[it.index] } diff --git a/ethdb/pebble/pebble.go b/ethdb/pebble/pebble.go index 7c01b879b8..5bd310a0a3 100644 --- a/ethdb/pebble/pebble.go +++ b/ethdb/pebble/pebble.go @@ -29,6 +29,7 @@ import ( "github.com/cockroachdb/pebble" "github.com/cockroachdb/pebble/bloom" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" @@ -89,7 +90,9 @@ func (d *Database) onCompactionBegin(info pebble.CompactionInfo) { if d.activeComp == 0 { d.compStartTime = time.Now() } + l0 := info.Input[0] + if l0.Level == 0 { d.level0Comp.Add(1) } else { @@ -122,9 +125,11 @@ func New(file string, cache int, handles int, namespace string, readonly bool) ( if cache < minCache { cache = minCache } + if handles < minHandles { handles = minHandles } + logger := log.New("database", file) logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*1024*1024), "handles", handles) @@ -137,9 +142,11 @@ func New(file string, cache int, handles int, namespace string, readonly bool) ( // including a frozen memory table and another live one. memTableLimit := 2 memTableSize := cache * 1024 * 1024 / 2 / memTableLimit + if memTableSize > maxMemTableSize { memTableSize = maxMemTableSize } + db := &Database{ fn: file, log: logger, @@ -195,6 +202,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool) ( if err != nil { return nil, err } + db.db = innerDB db.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil) @@ -213,6 +221,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool) ( // Start up the metrics gathering and return go db.meter(metricsGatheringInterval) + return db, nil } @@ -225,11 +234,14 @@ func (d *Database) Close() error { if d.quitChan != nil { errc := make(chan error) d.quitChan <- errc + if err := <-errc; err != nil { d.log.Error("Metrics collection failed", "err", err) } + d.quitChan = nil } + return d.db.Close() } @@ -241,7 +253,9 @@ func (d *Database) Has(key []byte) (bool, error) { } else if err != nil { return false, err } + closer.Close() + return true, nil } @@ -251,9 +265,11 @@ func (d *Database) Get(key []byte) ([]byte, error) { if err != nil { return nil, err } + ret := make([]byte, len(dat)) copy(ret, dat) closer.Close() + return ret, nil } @@ -311,7 +327,9 @@ func (snap *snapshot) Has(key []byte) (bool, error) { return false, nil } } + closer.Close() + return true, nil } @@ -322,9 +340,11 @@ func (snap *snapshot) Get(key []byte) ([]byte, error) { if err != nil { return nil, err } + ret := make([]byte, len(dat)) copy(ret, dat) closer.Close() + return ret, nil } @@ -341,11 +361,14 @@ func upperBound(prefix []byte) (limit []byte) { if c == 0xff { continue } + limit = make([]byte, i+1) copy(limit, prefix) limit[i] = c + 1 + break } + return limit } @@ -373,6 +396,7 @@ func (d *Database) Compact(start []byte, limit []byte) error { if limit == nil { limit = bytes.Repeat([]byte{0xff}, 32) } + return d.db.Compact(start, limit, true) // Parallelization is preferred } @@ -385,7 +409,9 @@ func (d *Database) Path() string { // the metrics subsystem. func (d *Database) meter(refresh time.Duration) { var errc chan error + timer := time.NewTimer(refresh) + defer timer.Stop() // Create storage and warning log tracer for write delay. @@ -413,6 +439,7 @@ func (d *Database) meter(refresh time.Duration) { nonLevel0CompCount = int64(d.nonLevel0Comp.Load()) level0CompCount = int64(d.level0Comp.Load()) ) + writeDelayTimes[i%2] = writeDelayTime writeDelayCounts[i%2] = writeDelayCount compTimes[i%2] = compTime @@ -433,24 +460,31 @@ func (d *Database) meter(refresh time.Duration) { if d.writeDelayNMeter != nil { d.writeDelayNMeter.Mark(writeDelayCounts[i%2] - writeDelayCounts[(i-1)%2]) } + if d.writeDelayMeter != nil { d.writeDelayMeter.Mark(writeDelayTimes[i%2] - writeDelayTimes[(i-1)%2]) } + if d.compTimeMeter != nil { d.compTimeMeter.Mark(compTimes[i%2] - compTimes[(i-1)%2]) } + if d.compReadMeter != nil { d.compReadMeter.Mark(compReads[i%2] - compReads[(i-1)%2]) } + if d.compWriteMeter != nil { d.compWriteMeter.Mark(compWrites[i%2] - compWrites[(i-1)%2]) } + if d.diskSizeGauge != nil { d.diskSizeGauge.Update(int64(metrics.DiskSpaceUsage())) } + if d.diskReadMeter != nil { d.diskReadMeter.Mark(0) // pebble doesn't track non-compaction reads } + if d.diskWriteMeter != nil { d.diskWriteMeter.Mark(nWrites[i%2] - nWrites[(i-1)%2]) } @@ -467,8 +501,8 @@ func (d *Database) meter(refresh time.Duration) { case errc = <-d.quitChan: // Quit requesting, stop hammering the database case <-timer.C: - timer.Reset(refresh) // Timeout, gather a new set of stats + timer.Reset(refresh) } } errc <- nil @@ -485,6 +519,7 @@ type batch struct { func (b *batch) Put(key, value []byte) error { b.b.Set(key, value, nil) b.size += len(key) + len(value) + return nil } @@ -492,6 +527,7 @@ func (b *batch) Put(key, value []byte) error { func (b *batch) Delete(key []byte) error { b.b.Delete(key, nil) b.size += len(key) + return nil } @@ -514,6 +550,7 @@ func (b *batch) Reset() { // Replay replays the batch contents. func (b *batch) Replay(w ethdb.KeyValueWriter) error { reader := b.b.Reader() + for { kind, k, v, ok := reader.Next() if !ok { @@ -529,6 +566,7 @@ func (b *batch) Replay(w ethdb.KeyValueWriter) error { return fmt.Errorf("unhandled operation, keytype: %v", kind) } } + return nil } @@ -548,6 +586,7 @@ func (d *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { UpperBound: upperBound(prefix), }) iter.First() + return &pebbleIterator{iter: iter, moved: true} } @@ -558,6 +597,7 @@ func (iter *pebbleIterator) Next() bool { iter.moved = false return iter.iter.Valid() } + return iter.iter.Next() } diff --git a/ethdb/pebble/pebble_test.go b/ethdb/pebble/pebble_test.go index 4ab40389bf..785dea17bc 100644 --- a/ethdb/pebble/pebble_test.go +++ b/ethdb/pebble/pebble_test.go @@ -23,6 +23,7 @@ import ( "github.com/cockroachdb/pebble" "github.com/cockroachdb/pebble/vfs" + "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb/dbtest" ) diff --git a/ethdb/remotedb/remotedb.go b/ethdb/remotedb/remotedb.go index 7a89897685..ba44bd90a9 100644 --- a/ethdb/remotedb/remotedb.go +++ b/ethdb/remotedb/remotedb.go @@ -37,15 +37,18 @@ func (db *Database) Has(key []byte) (bool, error) { //nolint:nilerr return false, nil } + return true, nil } func (db *Database) Get(key []byte) ([]byte, error) { var resp hexutil.Bytes err := db.remote.Call(&resp, "debug_dbGet", hexutil.Bytes(key)) + if err != nil { return nil, err } + return resp, nil } @@ -54,15 +57,18 @@ func (db *Database) HasAncient(kind string, number uint64) (bool, error) { //nolint:nilerr return false, nil } + return true, nil } func (db *Database) Ancient(kind string, number uint64) ([]byte, error) { var resp hexutil.Bytes err := db.remote.Call(&resp, "debug_dbAncient", kind, number) + if err != nil { return nil, err } + return resp, nil } @@ -73,6 +79,7 @@ func (db *Database) AncientRange(kind string, start, count, maxBytes uint64) ([] func (db *Database) Ancients() (uint64, error) { var resp uint64 err := db.remote.Call(&resp, "debug_dbAncients") + return resp, err } diff --git a/event/feedof.go b/event/feedof.go index 4a24e37f12..a709129039 100644 --- a/event/feedof.go +++ b/event/feedof.go @@ -58,8 +58,10 @@ func (f *FeedOf[T]) Subscribe(channel chan<- T) Subscription { // The next Send will add it to f.sendCases. f.mu.Lock() defer f.mu.Unlock() + cas := reflect.SelectCase{Dir: reflect.SelectSend, Chan: chanval} f.inbox = append(f.inbox, cas) + return sub } @@ -68,9 +70,11 @@ func (f *FeedOf[T]) remove(sub *feedOfSub[T]) { // that have not been added to f.sendCases yet. f.mu.Lock() index := f.inbox.find(sub.channel) + if index != -1 { f.inbox = f.inbox.delete(index) f.mu.Unlock() + return } f.mu.Unlock() @@ -108,6 +112,7 @@ func (f *FeedOf[T]) Send(value T) (nsent int) { // of sendCases. When a send succeeds, the corresponding case moves to the end of // 'cases' and it shrinks by one element. cases := f.sendCases + for { // Fast path: try sending without blocking before adding to the select set. // This should usually succeed if subscribers are fast enough and have free @@ -115,10 +120,12 @@ func (f *FeedOf[T]) Send(value T) (nsent int) { for i := firstSubSendCase; i < len(cases); i++ { if cases[i].Chan.TrySend(rvalue) { nsent++ + cases = cases.deactivate(i) i-- } } + if len(cases) == firstSubSendCase { break } @@ -127,6 +134,7 @@ func (f *FeedOf[T]) Send(value T) (nsent int) { if chosen == 0 /* <-f.removeSub */ { index := f.sendCases.find(recv.Interface()) f.sendCases = f.sendCases.delete(index) + if index >= 0 && index < len(cases) { // Shrink 'cases' too because the removed case was still active. cases = f.sendCases[:len(cases)-1] @@ -142,6 +150,7 @@ func (f *FeedOf[T]) Send(value T) (nsent int) { f.sendCases[i].Send = reflect.Value{} } f.sendLock <- struct{}{} + return nsent } diff --git a/event/feedof_test.go b/event/feedof_test.go index a776308268..bc9b65cf0a 100644 --- a/event/feedof_test.go +++ b/event/feedof_test.go @@ -26,12 +26,15 @@ func TestFeedOf(t *testing.T) { t.Parallel() var feed FeedOf[int] + var done, subscribed sync.WaitGroup + subscriber := func(i int) { defer done.Done() subchan := make(chan int) sub := feed.Subscribe(subchan) + timeout := time.NewTimer(2 * time.Second) defer timeout.Stop() subscribed.Done() @@ -57,18 +60,23 @@ func TestFeedOf(t *testing.T) { } const n = 1000 + done.Add(n) subscribed.Add(n) + for i := 0; i < n; i++ { go subscriber(i) } subscribed.Wait() + if nsent := feed.Send(1); nsent != n { t.Errorf("first send delivered %d times, want %d", nsent, n) } + if nsent := feed.Send(2); nsent != 0 { t.Errorf("second send delivered %d times, want 0", nsent) } + done.Wait() } @@ -83,10 +91,12 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) { sub2 = feed.Subscribe(ch) _ = feed.Subscribe(ch) ) + expectSends := func(value, n int) { if nsent := feed.Send(value); nsent != n { t.Errorf("send delivered %d times, want %d", nsent, n) } + done.Done() } expectRecv := func(wantValue, n int) { @@ -98,6 +108,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) { } done.Add(1) + go expectSends(1, 3) expectRecv(1, 3) done.Wait() @@ -105,6 +116,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) { sub1.Unsubscribe() done.Add(1) + go expectSends(2, 2) expectRecv(2, 2) done.Wait() @@ -112,6 +124,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) { sub2.Unsubscribe() done.Add(1) + go expectSends(3, 1) expectRecv(3, 1) done.Wait() @@ -127,10 +140,12 @@ func TestFeedOfSubscribeBlockedPost(t *testing.T) { ch2 = make(chan int) wg sync.WaitGroup ) + defer wg.Wait() feed.Subscribe(ch1) wg.Add(nsends) + for i := 0; i < nsends; i++ { go func() { feed.Send(99) @@ -164,12 +179,14 @@ func TestFeedOfUnsubscribeBlockedPost(t *testing.T) { bsub = feed.Subscribe(bchan) wg sync.WaitGroup ) + for i := range chans { chans[i] = make(chan int, nsends) } // Queue up some Sends. None of these can make progress while bchan isn't read. wg.Add(nsends) + for i := 0; i < nsends; i++ { go func() { feed.Send(99) @@ -202,9 +219,11 @@ func TestFeedOfUnsubscribeSentChan(t *testing.T) { sub2 = feed.Subscribe(ch2) wg sync.WaitGroup ) + defer sub2.Unsubscribe() wg.Add(1) + go func() { feed.Send(0) wg.Done() @@ -222,6 +241,7 @@ func TestFeedOfUnsubscribeSentChan(t *testing.T) { // Send again. This should send to ch2 only, so the wait group will unblock // as soon as a value is received on ch2. wg.Add(1) + go func() { feed.Send(0) wg.Done() @@ -241,9 +261,11 @@ func TestFeedOfUnsubscribeFromInbox(t *testing.T) { sub2 = feed.Subscribe(ch1) sub3 = feed.Subscribe(ch2) ) + if len(feed.inbox) != 3 { t.Errorf("inbox length != 3 after subscribe") } + if len(feed.sendCases) != 1 { t.Errorf("sendCases is non-empty after unsubscribe") } @@ -251,9 +273,11 @@ func TestFeedOfUnsubscribeFromInbox(t *testing.T) { sub1.Unsubscribe() sub2.Unsubscribe() sub3.Unsubscribe() + if len(feed.inbox) != 0 { t.Errorf("inbox is non-empty after unsubscribe") } + if len(feed.sendCases) != 1 { t.Errorf("sendCases is non-empty after unsubscribe") } @@ -265,21 +289,26 @@ func BenchmarkFeedOfSend1000(b *testing.B) { feed FeedOf[int] nsubs = 1000 ) + subscriber := func(ch <-chan int) { for i := 0; i < b.N; i++ { <-ch } done.Done() } + done.Add(nsubs) + for i := 0; i < nsubs; i++ { ch := make(chan int, 200) feed.Subscribe(ch) + go subscriber(ch) } // The actual benchmark. b.ResetTimer() + for i := 0; i < b.N; i++ { if feed.Send(i) != nsubs { panic("wrong number of sends") diff --git a/internal/build/gotool.go b/internal/build/gotool.go index 08c8b2ef05..4a2a969c41 100644 --- a/internal/build/gotool.go +++ b/internal/build/gotool.go @@ -85,6 +85,7 @@ func (g *GoToolchain) goTool(command string, args ...string) *exec.Cmd { if g.Root == "" { g.Root = runtime.GOROOT() } + tool := exec.Command(filepath.Join(g.Root, "bin", "go"), command) // nolint: gosec tool.Args = append(tool.Args, args...) tool.Env = append(tool.Env, "GOROOT="+g.Root) diff --git a/internal/build/util.go b/internal/build/util.go index 9a721e9b83..c21e2e8f9c 100644 --- a/internal/build/util.go +++ b/internal/build/util.go @@ -52,15 +52,19 @@ func MustRun(cmd *exec.Cmd) { func printArgs(args []string) string { var s strings.Builder + for i, arg := range args { if i > 0 { s.WriteByte(' ') } + if strings.IndexByte(arg, ' ') >= 0 { arg = strconv.QuoteToASCII(arg) } + s.WriteString(arg) } + return s.String() } @@ -191,6 +195,7 @@ func UploadSFTP(identityFile, host, dir string, files []string) error { // package paths. func FindMainPackages(dir string) []string { var commands []string + cmds, err := os.ReadDir(dir) if err != nil { log.Fatal(err) diff --git a/internal/cli/server/server.go b/internal/cli/server/server.go index 6d8f64d6d8..7e73361669 100644 --- a/internal/cli/server/server.go +++ b/internal/cli/server/server.go @@ -3,8 +3,6 @@ package server import ( "context" "fmt" - "github.com/ethereum/go-ethereum/cmd/utils" - "github.com/ethereum/go-ethereum/eth/ethconfig" "io" "math/big" "net" diff --git a/internal/debug/flags.go b/internal/debug/flags.go index 0b3c2904e3..02602786e7 100644 --- a/internal/debug/flags.go +++ b/internal/debug/flags.go @@ -25,15 +25,16 @@ import ( "path/filepath" "runtime" - "github.com/ethereum/go-ethereum/internal/flags" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/metrics" - "github.com/ethereum/go-ethereum/metrics/exp" "github.com/fjl/memsize/memsizeui" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" "github.com/urfave/cli/v2" "gopkg.in/natefinch/lumberjack.v2" + + "github.com/ethereum/go-ethereum/internal/flags" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/metrics" + "github.com/ethereum/go-ethereum/metrics/exp" ) var Memsize memsizeui.Handler diff --git a/internal/flags/flags.go b/internal/flags/flags.go index b0756b4e0a..edcdccdd03 100644 --- a/internal/flags/flags.go +++ b/internal/flags/flags.go @@ -26,8 +26,9 @@ import ( "path/filepath" "strings" - "github.com/ethereum/go-ethereum/common/math" "github.com/urfave/cli/v2" + + "github.com/ethereum/go-ethereum/common/math" ) // DirectoryString is custom type which is registered in the flags library which cli uses for diff --git a/internal/flags/helpers.go b/internal/flags/helpers.go index f210e729dd..6f9e4f7e82 100644 --- a/internal/flags/helpers.go +++ b/internal/flags/helpers.go @@ -22,7 +22,6 @@ import ( "github.com/ethereum/go-ethereum/internal/version" "github.com/ethereum/go-ethereum/params" - "github.com/urfave/cli/v2" ) // NewApp creates an app with sane defaults. diff --git a/internal/jsre/jsre_test.go b/internal/jsre/jsre_test.go index 60fdb12720..9e34eb2362 100644 --- a/internal/jsre/jsre_test.go +++ b/internal/jsre/jsre_test.go @@ -49,6 +49,7 @@ func newWithTestJS(t *testing.T, testjs string) *JSRE { } } jsre := New(dir, os.Stdout) + return jsre } diff --git a/internal/version/vcs.go b/internal/version/vcs.go index 21de8946e8..be7922de76 100644 --- a/internal/version/vcs.go +++ b/internal/version/vcs.go @@ -45,8 +45,10 @@ func buildInfoVCS(info *debug.BuildInfo) (s VCSInfo, ok bool) { } } } + if s.Commit != "" && s.Date != "" { ok = true } + return } diff --git a/internal/version/version.go b/internal/version/version.go index e044deee5c..737d383f00 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -45,11 +45,13 @@ func VCS() (VCSInfo, bool) { // Use information set by the build script if present. return VCSInfo{Commit: gitCommit, Date: gitDate}, true } + if buildInfo, ok := debug.ReadBuildInfo(); ok { if buildInfo.Main.Path == ourPath { return buildInfoVCS(buildInfo) } } + return VCSInfo{}, false } @@ -57,6 +59,7 @@ func VCS() (VCSInfo, bool) { // conventions in the Ethereum p2p network. func ClientName(clientIdentifier string) string { git, _ := VCS() + return fmt.Sprintf("%s/v%v/%v-%v/%v", //nolint: staticcheck strings.Title(clientIdentifier), @@ -66,8 +69,7 @@ func ClientName(clientIdentifier string) string { ) } -// runtimeInfo returns build and platform information about the current binary. -// +// Info returns build and platform information about the current binary. // If the package that is currently executing is a prefixed by our go-ethereum // module path, it will print out commit and date VCS information. Otherwise, // it will assume it's imported by a third-party and will return the imported @@ -75,21 +77,28 @@ func ClientName(clientIdentifier string) string { func Info() (version, vcs string) { version = params.VersionWithMeta buildInfo, ok := debug.ReadBuildInfo() + if !ok { return version, "" } + version = versionInfo(buildInfo) + if status, ok := VCS(); ok { modified := "" if status.Dirty { modified = " (dirty)" } + commit := status.Commit + if len(commit) > 8 { commit = commit[:8] } + vcs = commit + "-" + status.Date + modified } + return version, vcs } @@ -111,7 +120,9 @@ func versionInfo(info *debug.BuildInfo) string { // These can be empty when invoked with "go run". version = fmt.Sprintf("%s@%s ", info.Main.Path, info.Main.Version) } + mod := findModule(info, ourPath) + if mod == nil { // If our module path wasn't imported, it's unclear which // version of our code they are running. Fallback to hardcoded @@ -125,6 +136,7 @@ func versionInfo(info *debug.BuildInfo) string { // If our package was replaced by something else, also note that. version += fmt.Sprintf(" (replaced by %s@%s)", mod.Replace.Path, mod.Replace.Version) } + return version } @@ -133,10 +145,12 @@ func findModule(info *debug.BuildInfo, path string) *debug.Module { if info.Path == ourPath { return &info.Main } + for _, mod := range info.Deps { if mod.Path == path { return mod } } + return nil } diff --git a/les/client.go b/les/client.go index 348a20547a..204a7567ab 100644 --- a/les/client.go +++ b/les/client.go @@ -19,7 +19,6 @@ package les import ( "fmt" - "github.com/ethereum/go-ethereum/eth/downloader/whitelist" "strings" "time" diff --git a/log/format.go b/log/format.go index b10786efa0..20314b2144 100644 --- a/log/format.go +++ b/log/format.go @@ -354,6 +354,7 @@ func formatLogfmtValue(value interface{}, term bool) string { if v == nil { return "" } + return formatLogfmtUint256(v) } if term { @@ -484,12 +485,14 @@ func formatLogfmtUint256(n *uint256.Int) string { if n.IsUint64() { return FormatLogfmtUint64(n.Uint64()) } + var ( text = n.Dec() buf = make([]byte, len(text)+len(text)/3) comma = 0 i = len(buf) - 1 ) + for j := len(text) - 1; j >= 0; j, i = j-1, i-1 { c := text[j] @@ -499,13 +502,16 @@ func formatLogfmtUint256(n *uint256.Int) string { case comma == 3: buf[i] = ',' i-- + comma = 0 + fallthrough default: buf[i] = c comma++ } } + return string(buf[i+1:]) } @@ -531,6 +537,7 @@ func escapeString(s string) string { // for spaces and linebreaks to occur without needing quoting. func escapeMessage(s string) string { needsQuoting := false + for _, r := range s { // Allow CR/LF/TAB. This is to make multi-line messages work. if r == '\r' || r == '\n' || r == '\t' { @@ -543,8 +550,10 @@ func escapeMessage(s string) string { break } } + if !needsQuoting { return s } + return strconv.Quote(s) } diff --git a/log/format_test.go b/log/format_test.go index 63811dd8e8..e3398cf965 100644 --- a/log/format_test.go +++ b/log/format_test.go @@ -96,6 +96,7 @@ func TestPrettyUint256(t *testing.T) { for _, tt := range tests { v := new(uint256.Int) v.SetFromDecimal(tt.int) + if have := formatLogfmtUint256(v); have != tt.s { t.Errorf("invalid output %s, want %s", have, tt.s) } @@ -156,8 +157,10 @@ func TestSanitation(t *testing.T) { logger = New() out = new(strings.Builder) ) + logger.SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(out, TerminalFormat(false)))) logger.Info(tt.msg, tt.msg, tt.msg) + if have := out.String()[24:]; tt.want != have { t.Fatalf("test %d: want / have: \n%v\n%v", i, tt.want, have) } diff --git a/metrics/counter.go b/metrics/counter.go index 55e1c59540..0562061ff8 100644 --- a/metrics/counter.go +++ b/metrics/counter.go @@ -38,6 +38,7 @@ func NewCounter() Counter { if !Enabled { return NilCounter{} } + return &StandardCounter{} } diff --git a/metrics/counter_float64.go b/metrics/counter_float64.go index d1197bb8e0..a3634f490e 100644 --- a/metrics/counter_float64.go +++ b/metrics/counter_float64.go @@ -20,6 +20,7 @@ func GetOrRegisterCounterFloat64(name string, r Registry) CounterFloat64 { if nil == r { r = DefaultRegistry } + return r.GetOrRegister(name, NewCounterFloat64).(CounterFloat64) } @@ -31,6 +32,7 @@ func GetOrRegisterCounterFloat64Forced(name string, r Registry) CounterFloat64 { if nil == r { r = DefaultRegistry } + return r.GetOrRegister(name, NewCounterFloat64Forced).(CounterFloat64) } @@ -39,6 +41,7 @@ func NewCounterFloat64() CounterFloat64 { if !Enabled { return NilCounterFloat64{} } + return &StandardCounterFloat64{} } @@ -51,10 +54,12 @@ func NewCounterFloat64Forced() CounterFloat64 { // NewRegisteredCounterFloat64 constructs and registers a new StandardCounterFloat64. func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 { c := NewCounterFloat64() + if nil == r { r = DefaultRegistry } r.Register(name, c) + return c } @@ -64,10 +69,12 @@ func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 { // allow for garbage collection. func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 { c := NewCounterFloat64Forced() + if nil == r { r = DefaultRegistry } r.Register(name, c) + return c } @@ -148,6 +155,7 @@ func atomicAddFloat(fbits *atomic.Uint64, v float64) { for { loadedBits := fbits.Load() newBits := math.Float64bits(math.Float64frombits(loadedBits) + v) + if fbits.CompareAndSwap(loadedBits, newBits) { break } diff --git a/metrics/counter_float_64_test.go b/metrics/counter_float_64_test.go index c07ed4b33e..3557f47128 100644 --- a/metrics/counter_float_64_test.go +++ b/metrics/counter_float_64_test.go @@ -7,7 +7,9 @@ import ( func BenchmarkCounterFloat64(b *testing.B) { c := NewCounterFloat64() + b.ResetTimer() + for i := 0; i < b.N; i++ { c.Inc(1.0) } @@ -15,10 +17,14 @@ func BenchmarkCounterFloat64(b *testing.B) { func BenchmarkCounterFloat64Parallel(b *testing.B) { c := NewCounterFloat64() + b.ResetTimer() + var wg sync.WaitGroup + for i := 0; i < 10; i++ { wg.Add(1) + go func() { for i := 0; i < b.N; i++ { c.Inc(1.0) @@ -27,6 +33,7 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) { }() } wg.Wait() + if have, want := c.Count(), 10.0*float64(b.N); have != want { b.Fatalf("have %f want %f", have, want) } @@ -34,9 +41,11 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) { func TestCounterFloat64Clear(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Inc(1.0) c.Clear() + if count := c.Count(); count != 0 { t.Errorf("c.Count(): 0 != %v\n", count) } @@ -44,8 +53,10 @@ func TestCounterFloat64Clear(t *testing.T) { func TestCounterFloat64Dec1(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Dec(1.0) + if count := c.Count(); count != -1.0 { t.Errorf("c.Count(): -1.0 != %v\n", count) } @@ -53,8 +64,10 @@ func TestCounterFloat64Dec1(t *testing.T) { func TestCounterFloat64Dec2(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Dec(2.0) + if count := c.Count(); count != -2.0 { t.Errorf("c.Count(): -2.0 != %v\n", count) } @@ -62,6 +75,7 @@ func TestCounterFloat64Dec2(t *testing.T) { func TestCounterFloat64Inc1(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Inc(1.0) if count := c.Count(); count != 1.0 { @@ -71,8 +85,10 @@ func TestCounterFloat64Inc1(t *testing.T) { func TestCounterFloat64Inc2(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Inc(2.0) + if count := c.Count(); count != 2.0 { t.Errorf("c.Count(): 2.0 != %v\n", count) } @@ -80,10 +96,12 @@ func TestCounterFloat64Inc2(t *testing.T) { func TestCounterFloat64Snapshot(t *testing.T) { t.Parallel() + c := NewCounterFloat64() c.Inc(1.0) snapshot := c.Snapshot() c.Inc(1.0) + if count := snapshot.Count(); count != 1.0 { t.Errorf("c.Count(): 1.0 != %v\n", count) } @@ -91,7 +109,9 @@ func TestCounterFloat64Snapshot(t *testing.T) { func TestCounterFloat64Zero(t *testing.T) { t.Parallel() + c := NewCounterFloat64() + if count := c.Count(); count != 0 { t.Errorf("c.Count(): 0 != %v\n", count) } @@ -99,6 +119,7 @@ func TestCounterFloat64Zero(t *testing.T) { func TestGetOrRegisterCounterFloat64(t *testing.T) { t.Parallel() + r := NewRegistry() NewRegisteredCounterFloat64("foo", r).Inc(47.0) if c := GetOrRegisterCounterFloat64("foo", r); c.Count() != 47.0 { diff --git a/metrics/cputime_unix.go b/metrics/cputime_unix.go index ad4f812fd2..15ceb2df48 100644 --- a/metrics/cputime_unix.go +++ b/metrics/cputime_unix.go @@ -32,5 +32,6 @@ func getProcessCPUTime() float64 { log.Warn("Failed to retrieve CPU time", "err", err) return 0 } + return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1000000 //nolint:unconvert } diff --git a/metrics/gauge.go b/metrics/gauge.go index 81137d7f7c..88110ae155 100644 --- a/metrics/gauge.go +++ b/metrics/gauge.go @@ -25,6 +25,7 @@ func NewGauge() Gauge { if !Enabled { return NilGauge{} } + return &StandardGauge{} } diff --git a/metrics/gauge_float64.go b/metrics/gauge_float64.go index 237ff8036e..588bf76cba 100644 --- a/metrics/gauge_float64.go +++ b/metrics/gauge_float64.go @@ -26,6 +26,7 @@ func NewGaugeFloat64() GaugeFloat64 { if !Enabled { return NilGaugeFloat64{} } + return &StandardGaugeFloat64{} } diff --git a/metrics/gauge_float64_test.go b/metrics/gauge_float64_test.go index 647d090009..ea0901644c 100644 --- a/metrics/gauge_float64_test.go +++ b/metrics/gauge_float64_test.go @@ -15,9 +15,12 @@ func BenchmarkGaugeFloat64(b *testing.B) { func BenchmarkGaugeFloat64Parallel(b *testing.B) { c := NewGaugeFloat64() + var wg sync.WaitGroup + for i := 0; i < 10; i++ { wg.Add(1) + go func() { for i := 0; i < b.N; i++ { c.Update(float64(i)) @@ -26,6 +29,7 @@ func BenchmarkGaugeFloat64Parallel(b *testing.B) { }() } wg.Wait() + if have, want := c.Value(), float64(b.N-1); have != want { b.Fatalf("have %f want %f", have, want) } diff --git a/metrics/influxdb/influxdb.go b/metrics/influxdb/influxdb.go index 5dfbbab3ed..4bf1e19501 100644 --- a/metrics/influxdb/influxdb.go +++ b/metrics/influxdb/influxdb.go @@ -13,30 +13,35 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf fields := map[string]interface{}{ "value": metric.Count(), } + return measurement, fields case metrics.CounterFloat64: measurement := fmt.Sprintf("%s%s.count", namespace, name) fields := map[string]interface{}{ "value": metric.Count(), } + return measurement, fields case metrics.Gauge: measurement := fmt.Sprintf("%s%s.gauge", namespace, name) fields := map[string]interface{}{ "value": metric.Snapshot().Value(), } + return measurement, fields case metrics.GaugeFloat64: measurement := fmt.Sprintf("%s%s.gauge", namespace, name) fields := map[string]interface{}{ "value": metric.Snapshot().Value(), } + return measurement, fields case metrics.Histogram: ms := metric.Snapshot() if ms.Count() <= 0 { break } + 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{}{ @@ -54,6 +59,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf "p999": ps[5], "p9999": ps[6], } + return measurement, fields case metrics.Meter: ms := metric.Snapshot() @@ -65,6 +71,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf "m15": ms.Rate15(), "mean": ms.RateMean(), } + return measurement, fields case metrics.Timer: ms := metric.Snapshot() @@ -89,12 +96,14 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf "m15": ms.Rate15(), "meanrate": ms.RateMean(), } + return measurement, fields case metrics.ResettingTimer: t := metric.Snapshot() if len(t.Values()) == 0 { break } + ps := t.Percentiles([]float64{50, 95, 99}) val := t.Values() measurement := fmt.Sprintf("%s%s.span", namespace, name) @@ -107,7 +116,9 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf "p95": ps[1], "p99": ps[2], } + return measurement, fields } + return "", nil } diff --git a/metrics/influxdb/influxdbv1.go b/metrics/influxdb/influxdbv1.go index f65d30ef95..bee696a8b7 100644 --- a/metrics/influxdb/influxdbv1.go +++ b/metrics/influxdb/influxdbv1.go @@ -5,9 +5,10 @@ import ( uurl "net/url" "time" + client "github.com/influxdata/influxdb1-client/v2" + "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" - client "github.com/influxdata/influxdb1-client/v2" ) type reporter struct { @@ -131,6 +132,7 @@ func (r *reporter) send() error { if err != nil { return err } + r.reg.Each(func(name string, i interface{}) { now := time.Now() measurement, fields := readMeter(r.namespace, name, i) @@ -141,5 +143,6 @@ func (r *reporter) send() error { bps.AddPoint(p) } }) + return r.client.Write(bps) } diff --git a/metrics/metrics.go b/metrics/metrics.go index a11bb1e394..e649957230 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -145,6 +145,7 @@ var runtimeSamples = []metrics.Sample{ func readRuntimeStats(v *runtimeStats) { metrics.Read(runtimeSamples) + for _, s := range runtimeSamples { // Skip invalid/unknown metrics. This is needed because some metrics // are unavailable in older Go versions, and attempting to read a 'bad' @@ -226,12 +227,15 @@ func CollectProcessMetrics(refresh time.Duration) { // Iterate loading the different stats and updating the meters. now, prev := 0, 1 + for ; ; now, prev = prev, now { // Gather CPU times. ReadCPUStats(&cpustats[now]) + collectTime := time.Now() secondsSinceLastCollect := collectTime.Sub(lastCollectTime).Seconds() lastCollectTime = collectTime + if secondsSinceLastCollect > 0 { sysLoad := cpustats[now].GlobalTime - cpustats[prev].GlobalTime sysWait := cpustats[now].GlobalWait - cpustats[prev].GlobalWait diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index 1af0fa9217..bc65d37e80 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -11,7 +11,9 @@ const FANOUT = 128 func TestReadRuntimeValues(t *testing.T) { t.Parallel() + var v runtimeStats + readRuntimeStats(&v) t.Logf("%+v", v) } diff --git a/metrics/runtimehistogram.go b/metrics/runtimehistogram.go index c68939af1e..134f5adf24 100644 --- a/metrics/runtimehistogram.go +++ b/metrics/runtimehistogram.go @@ -11,7 +11,9 @@ func getOrRegisterRuntimeHistogram(name string, scale float64, r Registry) *runt if r == nil { r = DefaultRegistry } + constructor := func() Histogram { return newRuntimeHistogram(scale) } + return r.GetOrRegister(name, constructor).(*runtimeHistogram) } @@ -24,6 +26,7 @@ type runtimeHistogram struct { func newRuntimeHistogram(scale float64) *runtimeHistogram { h := &runtimeHistogram{scaleFactor: scale} h.update(&metrics.Float64Histogram{}) + return h } @@ -41,9 +44,11 @@ func (h *runtimeHistogram) update(mh *metrics.Float64Histogram) { } copy(s.Counts, mh.Counts) copy(s.Buckets, mh.Buckets) + for i, b := range s.Buckets { s.Buckets[i] = b * h.scaleFactor } + h.v.Store(&s) } @@ -133,6 +138,7 @@ func (h *runtimeHistogramSnapshot) Count() int64 { for _, c := range h.Counts { count += int64(c) } + return count } @@ -141,35 +147,42 @@ func (h *runtimeHistogramSnapshot) Mean() float64 { if len(h.Counts) == 0 { return 0 } + mean, _ := h.mean() + return mean } // mean computes the mean and also the total sample count. func (h *runtimeHistogramSnapshot) mean() (mean, totalCount float64) { var sum float64 + for i, c := range h.Counts { midpoint := h.midpoint(i) sum += midpoint * float64(c) totalCount += float64(c) } + return sum / totalCount, totalCount } func (h *runtimeHistogramSnapshot) midpoint(bucket int) float64 { high := h.Buckets[bucket+1] low := h.Buckets[bucket] + if math.IsInf(high, 1) { // The edge of the highest bucket can be +Inf, and it's supposed to mean that this // bucket contains all remaining samples > low. We can't get the middle of an // infinite range, so just return the lower bound of this bucket instead. return low } + if math.IsInf(low, -1) { // Similarly, we can get -Inf in the left edge of the lowest bucket, // and it means the bucket contains all remaining values < high. return high } + return (low + high) / 2 } @@ -191,11 +204,13 @@ func (h *runtimeHistogramSnapshot) Variance() float64 { } var sum float64 + for i, c := range h.Counts { midpoint := h.midpoint(i) d := midpoint - mean sum += float64(c) * (d * d) } + return sum / (totalCount - 1) } @@ -204,6 +219,7 @@ func (h *runtimeHistogramSnapshot) Percentile(p float64) float64 { threshold := float64(h.Count()) * p values := [1]float64{threshold} h.computePercentiles(values[:]) + return values[0] } @@ -215,10 +231,12 @@ func (h *runtimeHistogramSnapshot) Percentiles(ps []float64) []float64 { count := float64(h.Count()) thresholds := make([]float64, len(ps)) indexes := make([]int, len(ps)) + for i, percentile := range ps { thresholds[i] = count * math.Max(0, math.Min(1.0, percentile)) indexes[i] = i } + sort.Sort(floatsAscendingKeepingIndex{thresholds, indexes}) // Now compute. The result is stored back into the thresholds slice. @@ -226,6 +244,7 @@ func (h *runtimeHistogramSnapshot) Percentiles(ps []float64) []float64 { // Put the result back into the requested order. sort.Sort(floatsByIndex{thresholds, indexes}) + return thresholds } @@ -238,6 +257,7 @@ func (h *runtimeHistogramSnapshot) computePercentiles(thresh []float64) { thresh[0] = h.Buckets[i] thresh = thresh[1:] } + if len(thresh) == 0 { return } @@ -257,9 +277,11 @@ func (h *runtimeHistogramSnapshot) Max() int64 { if math.IsInf(edge, 1) { edge = h.Buckets[i] } + return int64(math.Ceil(edge)) } } + return 0 } @@ -270,6 +292,7 @@ func (h *runtimeHistogramSnapshot) Min() int64 { return int64(math.Floor(h.Buckets[i])) } } + return 0 } @@ -279,6 +302,7 @@ func (h *runtimeHistogramSnapshot) Sum() int64 { for i := range h.Counts { sum += h.Buckets[i] * float64(h.Counts[i]) } + return int64(math.Ceil(sum)) } diff --git a/metrics/runtimehistogram_test.go b/metrics/runtimehistogram_test.go index 88e6f9da08..fad6c697a8 100644 --- a/metrics/runtimehistogram_test.go +++ b/metrics/runtimehistogram_test.go @@ -27,6 +27,7 @@ type runtimeHistogramTest struct { // by runtimeHistogramSnapshot. func TestRuntimeHistogramStats(t *testing.T) { t.Parallel() + tests := []runtimeHistogramTest{ 0: { h: metrics.Float64Histogram{ @@ -113,12 +114,15 @@ func approxEqual(x, y, ε float64) bool { if math.IsInf(x, -1) && math.IsInf(y, -1) { return true } + if math.IsInf(x, 1) && math.IsInf(y, 1) { return true } + if math.IsNaN(x) && math.IsNaN(y) { return true } + return math.Abs(x-y) < ε } @@ -126,12 +130,14 @@ func approxEqual(x, y, ε float64) bool { // returns them in the requested order. func TestRuntimeHistogramStatsPercentileOrder(t *testing.T) { t.Parallel() + p := runtimeHistogramSnapshot{ Counts: []uint64{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, Buckets: []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, } result := p.Percentiles([]float64{1, 0.2, 0.5, 0.1, 0.2}) expected := []float64{10, 2, 5, 1, 2} + if !reflect.DeepEqual(result, expected) { t.Fatal("wrong result:", result) } diff --git a/metrics/sample.go b/metrics/sample.go index afcaa21184..5bf59bb239 100644 --- a/metrics/sample.go +++ b/metrics/sample.go @@ -175,7 +175,9 @@ func (s *ExpDecaySample) update(t time.Time, v int64) { if s.values.Size() == s.reservoirSize { s.values.Pop() } + var f64 float64 + if s.rand != nil { f64 = s.rand.Float64() } else { diff --git a/node/jwt_auth.go b/node/jwt_auth.go index d4f8193ca7..5fa23fd5b8 100644 --- a/node/jwt_auth.go +++ b/node/jwt_auth.go @@ -21,8 +21,9 @@ import ( "net/http" "time" - "github.com/ethereum/go-ethereum/rpc" "github.com/golang-jwt/jwt/v4" + + "github.com/ethereum/go-ethereum/rpc" ) // NewJWTAuth creates an rpc client authentication provider that uses JWT. The diff --git a/node/node.go b/node/node.go index 1a4defbf81..39e7321504 100644 --- a/node/node.go +++ b/node/node.go @@ -38,7 +38,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rpc" - "github.com/gofrs/flock" ) // Node is a container on which services can be registered. @@ -429,9 +428,9 @@ func (n *Node) startRPC() error { return err } if err := server.enableWS(openAPIs, wsConfig{ - Modules: n.config.WSModules, - Origins: n.config.WSOrigins, - prefix: n.config.WSPathPrefix, + Modules: n.config.WSModules, + Origins: n.config.WSOrigins, + prefix: n.config.WSPathPrefix, executionPoolSize: n.config.WSJsonRPCExecutionPoolSize, executionPoolRequestTimeout: n.config.WSJsonRPCExecutionPoolRequestTimeout, }); err != nil { diff --git a/node/node_auth_test.go b/node/node_auth_test.go index b558cf5ac7..043ce30ec1 100644 --- a/node/node_auth_test.go +++ b/node/node_auth_test.go @@ -26,9 +26,10 @@ import ( "testing" "time" + "github.com/golang-jwt/jwt/v4" + "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/rpc" - "github.com/golang-jwt/jwt/v4" ) type helloRPC string diff --git a/node/rpcstack.go b/node/rpcstack.go index 3da357330a..8dafea2fb1 100644 --- a/node/rpcstack.go +++ b/node/rpcstack.go @@ -32,7 +32,6 @@ import ( "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rpc" - "github.com/rs/cors" ) // httpConfig is the JSON-RPC/HTTP configuration. diff --git a/p2p/discover/v5_udp_test.go b/p2p/discover/v5_udp_test.go index 727ec11fd5..90fab253b7 100644 --- a/p2p/discover/v5_udp_test.go +++ b/p2p/discover/v5_udp_test.go @@ -34,7 +34,6 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/rlp" - "github.com/stretchr/testify/require" ) // Real sockets, real crypto: this test checks end-to-end connectivity for UDPv5. diff --git a/p2p/msgrate/msgrate.go b/p2p/msgrate/msgrate.go index ff29c9620a..c9010e3ed3 100644 --- a/p2p/msgrate/msgrate.go +++ b/p2p/msgrate/msgrate.go @@ -296,6 +296,7 @@ func (t *Trackers) medianRoundTrip() time.Duration { sort.Float64s(rtts) var median time.Duration + switch len(rtts) { case 0: median = rttMaxEstimate diff --git a/p2p/simulations/mocker_test.go b/p2p/simulations/mocker_test.go index eea2f96d71..a577fc8e7e 100644 --- a/p2p/simulations/mocker_test.go +++ b/p2p/simulations/mocker_test.go @@ -21,7 +21,6 @@ package simulations import ( "context" "encoding/json" - "github.com/ethereum/go-ethereum/log" "net/http" "net/url" "strconv" diff --git a/params/config.go b/params/config.go index dfa303cbd6..f645bf7178 100644 --- a/params/config.go +++ b/params/config.go @@ -797,6 +797,7 @@ func (c *ChainConfig) Description() string { if network == "" { network = "unknown" } + banner += fmt.Sprintf("Chain ID: %v (%s)\n", c.ChainID, network) switch { case c.Ethash != nil: @@ -820,6 +821,7 @@ func (c *ChainConfig) Description() string { default: banner += "Consensus: unknown\n" } + banner += "\n" // Create a list of forks with a short description of them. Forks that only @@ -827,9 +829,11 @@ func (c *ChainConfig) Description() string { // the output for testnets and private networks. banner += "Pre-Merge hard forks (block based):\n" banner += fmt.Sprintf(" - Homestead: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/homestead.md)\n", c.HomesteadBlock) + if c.DAOForkBlock != nil { banner += fmt.Sprintf(" - DAO Fork: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/dao-fork.md)\n", c.DAOForkBlock) } + banner += fmt.Sprintf(" - Tangerine Whistle (EIP 150): #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/tangerine-whistle.md)\n", c.EIP150Block) banner += fmt.Sprintf(" - Spurious Dragon/1 (EIP 155): #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/spurious-dragon.md)\n", c.EIP155Block) banner += fmt.Sprintf(" - Spurious Dragon/2 (EIP 158): #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/spurious-dragon.md)\n", c.EIP155Block) @@ -837,17 +841,22 @@ func (c *ChainConfig) Description() string { banner += fmt.Sprintf(" - Constantinople: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/constantinople.md)\n", c.ConstantinopleBlock) banner += fmt.Sprintf(" - Petersburg: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/petersburg.md)\n", c.PetersburgBlock) banner += fmt.Sprintf(" - Istanbul: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/istanbul.md)\n", c.IstanbulBlock) + if c.MuirGlacierBlock != nil { banner += fmt.Sprintf(" - Muir Glacier: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/muir-glacier.md)\n", c.MuirGlacierBlock) } + banner += fmt.Sprintf(" - Berlin: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/berlin.md)\n", c.BerlinBlock) banner += fmt.Sprintf(" - London: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/london.md)\n", c.LondonBlock) + if c.ArrowGlacierBlock != nil { banner += fmt.Sprintf(" - Arrow Glacier: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/arrow-glacier.md)\n", c.ArrowGlacierBlock) } + if c.GrayGlacierBlock != nil { banner += fmt.Sprintf(" - Gray Glacier: #%-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md)\n", c.GrayGlacierBlock) } + banner += "\n" // Add a special section for the merge as it's non-obvious @@ -863,6 +872,7 @@ func (c *ChainConfig) Description() string { banner += fmt.Sprintf(" - Merge netsplit block: #%-8v\n", c.MergeNetsplitBlock) } } + banner += "\n" // Create a list of forks post-merge @@ -870,12 +880,15 @@ func (c *ChainConfig) Description() string { if c.ShanghaiTime != nil { banner += fmt.Sprintf(" - Shanghai: @%-10v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)\n", *c.ShanghaiTime) } + if c.CancunTime != nil { banner += fmt.Sprintf(" - Cancun: @%-10v\n", *c.CancunTime) } + if c.PragueTime != nil { banner += fmt.Sprintf(" - Prague: @%-10v\n", *c.PragueTime) } + return banner } @@ -1071,30 +1084,39 @@ func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, headNumber *big.Int, if isForkBlockIncompatible(c.HomesteadBlock, newcfg.HomesteadBlock, headNumber) { return newBlockCompatError("Homestead fork block", c.HomesteadBlock, newcfg.HomesteadBlock) } + if isForkBlockIncompatible(c.DAOForkBlock, newcfg.DAOForkBlock, headNumber) { return newBlockCompatError("DAO fork block", c.DAOForkBlock, newcfg.DAOForkBlock) } + if c.IsDAOFork(headNumber) && c.DAOForkSupport != newcfg.DAOForkSupport { return newBlockCompatError("DAO fork support flag", c.DAOForkBlock, newcfg.DAOForkBlock) } + if isForkBlockIncompatible(c.EIP150Block, newcfg.EIP150Block, headNumber) { return newBlockCompatError("EIP150 fork block", c.EIP150Block, newcfg.EIP150Block) } + if isForkBlockIncompatible(c.EIP155Block, newcfg.EIP155Block, headNumber) { return newBlockCompatError("EIP155 fork block", c.EIP155Block, newcfg.EIP155Block) } + if isForkBlockIncompatible(c.EIP158Block, newcfg.EIP158Block, headNumber) { return newBlockCompatError("EIP158 fork block", c.EIP158Block, newcfg.EIP158Block) } + if c.IsEIP158(headNumber) && !configBlockEqual(c.ChainID, newcfg.ChainID) { return newBlockCompatError("EIP158 chain ID", c.EIP158Block, newcfg.EIP158Block) } + if isForkBlockIncompatible(c.ByzantiumBlock, newcfg.ByzantiumBlock, headNumber) { return newBlockCompatError("Byzantium fork block", c.ByzantiumBlock, newcfg.ByzantiumBlock) } + if isForkBlockIncompatible(c.ConstantinopleBlock, newcfg.ConstantinopleBlock, headNumber) { return newBlockCompatError("Constantinople fork block", c.ConstantinopleBlock, newcfg.ConstantinopleBlock) } + if isForkBlockIncompatible(c.PetersburgBlock, newcfg.PetersburgBlock, headNumber) { // the only case where we allow Petersburg to be set in the past is if it is equal to Constantinople // mainly to satisfy fork ordering requirements which state that Petersburg fork be set if Constantinople fork is set @@ -1102,33 +1124,43 @@ func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, headNumber *big.Int, return newBlockCompatError("Petersburg fork block", c.PetersburgBlock, newcfg.PetersburgBlock) } } + if isForkBlockIncompatible(c.IstanbulBlock, newcfg.IstanbulBlock, headNumber) { return newBlockCompatError("Istanbul fork block", c.IstanbulBlock, newcfg.IstanbulBlock) } + if isForkBlockIncompatible(c.MuirGlacierBlock, newcfg.MuirGlacierBlock, headNumber) { return newBlockCompatError("Muir Glacier fork block", c.MuirGlacierBlock, newcfg.MuirGlacierBlock) } + if isForkBlockIncompatible(c.BerlinBlock, newcfg.BerlinBlock, headNumber) { return newBlockCompatError("Berlin fork block", c.BerlinBlock, newcfg.BerlinBlock) } + if isForkBlockIncompatible(c.LondonBlock, newcfg.LondonBlock, headNumber) { return newBlockCompatError("London fork block", c.LondonBlock, newcfg.LondonBlock) } + if isForkBlockIncompatible(c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock, headNumber) { return newBlockCompatError("Arrow Glacier fork block", c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock) } + if isForkBlockIncompatible(c.GrayGlacierBlock, newcfg.GrayGlacierBlock, headNumber) { return newBlockCompatError("Gray Glacier fork block", c.GrayGlacierBlock, newcfg.GrayGlacierBlock) } + if isForkBlockIncompatible(c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock, headNumber) { return newBlockCompatError("Merge netsplit fork block", c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock) } + if isForkTimestampIncompatible(c.ShanghaiTime, newcfg.ShanghaiTime, headTimestamp) { return newTimestampCompatError("Shanghai fork timestamp", c.ShanghaiTime, newcfg.ShanghaiTime) } + if isForkTimestampIncompatible(c.CancunTime, newcfg.CancunTime, headTimestamp) { return newTimestampCompatError("Cancun fork timestamp", c.CancunTime, newcfg.CancunTime) } + if isForkTimestampIncompatible(c.PragueTime, newcfg.PragueTime, headTimestamp) { return newTimestampCompatError("Prague fork timestamp", c.PragueTime, newcfg.PragueTime) } @@ -1184,6 +1216,7 @@ func isTimestampForked(s *uint64, head uint64) bool { if s == nil { return false } + return *s <= head } @@ -1191,9 +1224,11 @@ func configTimestampEqual(x, y *uint64) bool { if x == nil { return y == nil } + if y == nil { return x == nil } + return *x == *y } @@ -1225,6 +1260,7 @@ func newBlockCompatError(what string, storedblock, newblock *big.Int) *ConfigCom default: rew = newblock } + err := &ConfigCompatError{ What: what, StoredBlock: storedblock, @@ -1234,11 +1270,13 @@ func newBlockCompatError(what string, storedblock, newblock *big.Int) *ConfigCom if rew != nil && rew.Sign() > 0 { err.RewindToBlock = rew.Uint64() - 1 } + return err } func newTimestampCompatError(what string, storedtime, newtime *uint64) *ConfigCompatError { var rew *uint64 + switch { case storedtime == nil: rew = newtime @@ -1247,12 +1285,14 @@ func newTimestampCompatError(what string, storedtime, newtime *uint64) *ConfigCo default: rew = newtime } + err := &ConfigCompatError{ What: what, StoredTime: storedtime, NewTime: newtime, RewindToTime: 0, } + if rew != nil { err.RewindToTime = *rew - 1 } @@ -1263,6 +1303,7 @@ func (err *ConfigCompatError) Error() string { if err.StoredBlock != nil { return fmt.Sprintf("mismatching %s in database (have block %d, want block %d, rewindto block %d)", err.What, err.StoredBlock, err.NewBlock, err.RewindToBlock) } + return fmt.Sprintf("mismatching %s in database (have timestamp %d, want timestamp %d, rewindto timestamp %d)", err.What, err.StoredTime, err.NewTime, err.RewindToTime) } diff --git a/params/config_test.go b/params/config_test.go index 57ae6d4def..b07b736fe4 100644 --- a/params/config_test.go +++ b/params/config_test.go @@ -125,15 +125,21 @@ func TestConfigRules(t *testing.T) { c := &ChainConfig{ ShanghaiTime: newUint64(500), } + var stamp uint64 + if r := c.Rules(big.NewInt(0), true, stamp); r.IsShanghai { t.Errorf("expected %v to not be shanghai", stamp) } + stamp = 500 + if r := c.Rules(big.NewInt(0), true, stamp); !r.IsShanghai { t.Errorf("expected %v to be shanghai", stamp) } + stamp = math.MaxInt64 + if r := c.Rules(big.NewInt(0), true, stamp); !r.IsShanghai { t.Errorf("expected %v to be shanghai", stamp) } diff --git a/params/protocol_params.go b/params/protocol_params.go index b89ada75c0..1de8e88bd7 100644 --- a/params/protocol_params.go +++ b/params/protocol_params.go @@ -126,8 +126,8 @@ const ( ElasticityMultiplier = 2 // Bounds the maximum gas limit an EIP-1559 block may have. InitialBaseFee = 1000000000 // Initial base fee for EIP-1559 blocks. - DefaultBaseFeeChangeDenominator = 8 // Bounds the amount the base fee can change between blocks. - DefaultElasticityMultiplier = 2 // Bounds the maximum gas limit an EIP-1559 block may have. + DefaultBaseFeeChangeDenominator = 8 // Bounds the amount the base fee can change between blocks. + DefaultElasticityMultiplier = 2 // Bounds the maximum gas limit an EIP-1559 block may have. MaxCodeSize = 24576 // Maximum bytecode to permit for a contract MaxInitCodeSize = 2 * MaxCodeSize // Maximum initcode to permit in a creation transaction and create instructions diff --git a/rlp/decode.go b/rlp/decode.go index c9b50e8c18..8df281aaa6 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -30,6 +30,8 @@ import ( "github.com/ethereum/go-ethereum/rlp/internal/rlpstruct" "github.com/holiman/uint256" + + "github.com/ethereum/go-ethereum/rlp/internal/rlpstruct" ) //lint:ignore ST1012 EOL is not an error. diff --git a/rlp/decode_test.go b/rlp/decode_test.go index 07d9c579a6..c93fef7991 100644 --- a/rlp/decode_test.go +++ b/rlp/decode_test.go @@ -29,6 +29,8 @@ import ( "github.com/ethereum/go-ethereum/common/math" "github.com/holiman/uint256" + + "github.com/ethereum/go-ethereum/common/math" ) func TestStreamKind(t *testing.T) { diff --git a/rlp/encode.go b/rlp/encode.go index 3fac0bd2d3..06f6885615 100644 --- a/rlp/encode.go +++ b/rlp/encode.go @@ -25,6 +25,8 @@ import ( "github.com/ethereum/go-ethereum/rlp/internal/rlpstruct" "github.com/holiman/uint256" + + "github.com/ethereum/go-ethereum/rlp/internal/rlpstruct" ) var ( diff --git a/rlp/encode_test.go b/rlp/encode_test.go index 02be47d0ef..911fb5a3a9 100644 --- a/rlp/encode_test.go +++ b/rlp/encode_test.go @@ -28,6 +28,8 @@ import ( "github.com/ethereum/go-ethereum/common/math" "github.com/holiman/uint256" + + "github.com/ethereum/go-ethereum/common/math" ) type testEncoder struct { diff --git a/rlp/rlpgen/gen.go b/rlp/rlpgen/gen.go index 0c65864826..a0d20970b3 100644 --- a/rlp/rlpgen/gen.go +++ b/rlp/rlpgen/gen.go @@ -342,6 +342,7 @@ func (op uint256Op) genWrite(ctx *genContext, v string) string { if !op.pointer { dst = "&" + v } + fmt.Fprintf(&b, "w.WriteUint256(%s)\n", dst) // Wrap with nil check. @@ -362,6 +363,7 @@ func (op uint256Op) genDecode(ctx *genContext) (string, string) { ctx.addImport("github.com/holiman/uint256") var b bytes.Buffer + resultV := ctx.temp() fmt.Fprintf(&b, "var %s uint256.Int\n", resultV) fmt.Fprintf(&b, "if err := dec.ReadUint256(&%s); err != nil { return err }\n", resultV) @@ -370,6 +372,7 @@ func (op uint256Op) genDecode(ctx *genContext) (string, string) { if op.pointer { result = "&" + resultV } + return result, b.String() } @@ -678,6 +681,7 @@ func (bctx *buildContext) makeOp(name *types.Named, typ types.Type, tags rlpstru if isBigInt(typ) { return bigIntOp{}, nil } + if isUint256(typ) { return uint256Op{}, nil } @@ -693,6 +697,7 @@ func (bctx *buildContext) makeOp(name *types.Named, typ types.Type, tags rlpstru if isBigInt(typ.Elem()) { return bigIntOp{pointer: true}, nil } + if isUint256(typ.Elem()) { return uint256Op{pointer: true}, nil } diff --git a/rlp/rlpgen/types.go b/rlp/rlpgen/types.go index ea7dc96d88..d87c1e83b8 100644 --- a/rlp/rlpgen/types.go +++ b/rlp/rlpgen/types.go @@ -103,7 +103,9 @@ func isUint256(typ types.Type) bool { if !ok { return false } + name := named.Obj() + return name.Pkg().Path() == "github.com/holiman/uint256" && name.Name() == "Int" } diff --git a/rpc/client.go b/rpc/client.go index 546e5abba2..573cbf2940 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -202,6 +202,7 @@ func DialOptions(ctx context.Context, rawurl string, options ...ClientOption) (* if err != nil { return nil, err } + reconnect = rc case "stdio": reconnect = newClientTransportIO(os.Stdin, os.Stdout) @@ -348,6 +349,7 @@ func (c *Client) CallContext(ctx context.Context, result interface{}, method str if result == nil { return nil } + return json.Unmarshal(resp.Result, result) } } @@ -530,6 +532,7 @@ func (c *Client) write(ctx context.Context, msg interface{}, retry bool) error { return err } } + err := c.writeConn.writeJSON(ctx, msg, false) if err != nil { c.writeConn = nil diff --git a/rpc/client_opt.go b/rpc/client_opt.go index 5ad7c22b3c..72b5001319 100644 --- a/rpc/client_opt.go +++ b/rpc/client_opt.go @@ -93,6 +93,7 @@ func WithHTTPAuth(a HTTPAuth) ClientOption { if a == nil { panic("nil auth") } + return optionFunc(func(cfg *clientConfig) { cfg.httpAuth = a }) diff --git a/rpc/client_opt_test.go b/rpc/client_opt_test.go index d7cc2572a7..9a4c32f7c2 100644 --- a/rpc/client_opt_test.go +++ b/rpc/client_opt_test.go @@ -18,8 +18,10 @@ func ExampleDialOptions() { ctx := context.Background() c, err := rpc.DialOptions(ctx, "http://rpc.example.com", httpClient, tokenHeader) + if err != nil { panic(err) } + c.Close() } diff --git a/rpc/client_test.go b/rpc/client_test.go index c792bef82e..5e10b6d454 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -86,9 +86,11 @@ func TestClientNullResponse(t *testing.T) { if err := client.Call(&result, "test_null"); err != nil { t.Fatal(err) } + if result == nil { t.Fatal("Expected non-nil result") } + if !reflect.DeepEqual(result, json.RawMessage("null")) { t.Errorf("Expected null, got %s", result) } @@ -185,6 +187,7 @@ func TestClientBatchRequest_len(t *testing.T) { if err != nil { t.Fatal("failed to encode jsonrpc message:", err) } + s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { _, err := rw.Write(b) if err != nil { diff --git a/rpc/context_headers.go b/rpc/context_headers.go index 29a58150e3..79e451744d 100644 --- a/rpc/context_headers.go +++ b/rpc/context_headers.go @@ -32,12 +32,15 @@ func NewContextWithHeaders(ctx context.Context, h http.Header) context.Context { } var ctxh http.Header + prev, ok := ctx.Value(mdHeaderKey{}).(http.Header) + if ok { ctxh = setHeaders(prev.Clone(), h) } else { ctxh = h.Clone() } + return context.WithValue(ctx, mdHeaderKey{}, ctxh) } @@ -52,5 +55,6 @@ func setHeaders(dst http.Header, src http.Header) http.Header { for key, values := range src { dst[http.CanonicalHeaderKey(key)] = values } + return dst } diff --git a/rpc/handler.go b/rpc/handler.go index 64cfb554d6..08fbf9a83d 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -117,6 +117,7 @@ func (b *batchCallBuffer) nextCall() *jsonrpcMessage { // The popping happens in `pushAnswer`. The in progress call is kept // so we can return an error for it in case of timeout. msg := b.calls[0] + return msg } @@ -128,6 +129,7 @@ func (b *batchCallBuffer) pushResponse(answer *jsonrpcMessage) { if answer != nil { b.resp = append(b.resp, answer) } + b.calls = b.calls[1:] } @@ -151,6 +153,7 @@ func (b *batchCallBuffer) timeout(ctx context.Context, conn jsonWriter) { b.resp = append(b.resp, resp) } } + b.doWrite(ctx, conn, true) } @@ -160,7 +163,9 @@ func (b *batchCallBuffer) doWrite(ctx context.Context, conn jsonWriter, isErrorR if b.wrote { return } + b.wrote = true // can only write once + if len(b.resp) > 0 { conn.writeJSON(ctx, b.resp, isErrorResponse) } diff --git a/rpc/http.go b/rpc/http.go index 810da3fa9c..e9c6e5ff58 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -139,6 +139,7 @@ func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error) { var cfg clientConfig cfg.httpClient = client fn := newClientTransportHTTP(endpoint, &cfg) + return newClient(context.Background(), fn) } @@ -146,6 +147,7 @@ func newClientTransportHTTP(endpoint string, cfg *clientConfig) reconnectFunc { headers := make(http.Header, 2+len(cfg.httpHeaders)) headers.Set("accept", contentType) headers.Set("content-type", contentType) + for key, values := range cfg.httpHeaders { headers[key] = values } @@ -195,6 +197,7 @@ func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonr if err := json.NewDecoder(respBody).Decode(&respmsgs); err != nil { return err } + if len(respmsgs) != len(msgs) { return fmt.Errorf("batch has %d requests but response has %d: %w", len(msgs), len(respmsgs), ErrBadResult) } @@ -209,6 +212,7 @@ func (hc *httpConn) doRequest(ctx context.Context, msg interface{}) (io.ReadClos if err != nil { return nil, err } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, hc.url, io.NopCloser(bytes.NewReader(body))) if err != nil { return nil, err @@ -275,6 +279,7 @@ func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec { if err != nil { return err } + w.Header().Set("content-length", strconv.Itoa(len(encdata))) // If this request is wrapped in a handler that might remove Content-Length (such @@ -285,9 +290,11 @@ func newHTTPServerConn(r *http.Request, w http.ResponseWriter) ServerCodec { w.Header().Set("transfer-encoding", "identity") _, err = w.Write(encdata) + if f, ok := w.(http.Flusher); ok { f.Flush() } + return err } diff --git a/rpc/http_test.go b/rpc/http_test.go index fba1a40f0d..85bc617eec 100644 --- a/rpc/http_test.go +++ b/rpc/http_test.go @@ -94,6 +94,7 @@ func confirmHTTPRequestYieldsStatusCode(t *testing.T, method, contentType, body if err != nil { t.Fatalf("request failed: %v", err) } + resp.Body.Close() confirmStatusCode(t, resp.StatusCode, expectedStatusCode) } @@ -216,6 +217,7 @@ func TestNewContextWithHeaders(t *testing.T) { writer.WriteHeader(http.StatusOK) _, _ = writer.Write([]byte(`{}`)) })) + defer server.Close() client, err := Dial(server.URL) @@ -227,6 +229,7 @@ func TestNewContextWithHeaders(t *testing.T) { newHdr := func(k, v string) http.Header { header := http.Header{} header.Set(k, v) + return header } ctx1 := NewContextWithHeaders(context.Background(), newHdr("key-0", "val-0")) @@ -234,11 +237,13 @@ func TestNewContextWithHeaders(t *testing.T) { ctx3 := NewContextWithHeaders(ctx2, newHdr("key-2", "val-2")) expectedHeaders = 3 + if err := client.CallContext(ctx3, nil, "test"); err != ErrNoResult { t.Error("call failed", err) } expectedHeaders = 2 + if err := client.CallContext(ctx2, nil, "test"); err != ErrNoResult { t.Error("call failed:", err) } diff --git a/rpc/json.go b/rpc/json.go index 8a3b162cab..d2d0b0c64a 100644 --- a/rpc/json.go +++ b/rpc/json.go @@ -206,6 +206,7 @@ func NewCodec(conn Conn) ServerCodec { encode := func(v interface{}, isErrorResponse bool) error { return enc.Encode(v) } + return NewFuncCodec(conn, encode, dec.Decode) } @@ -245,6 +246,7 @@ func (c *jsonCodec) writeJSON(ctx context.Context, v interface{}, isErrorRespons deadline = time.Now().Add(defaultWriteTimeout) } c.conn.SetWriteDeadline(deadline) + return c.encode(v, isErrorResponse) } diff --git a/rpc/metrics.go b/rpc/metrics.go index b1f1284535..ffd179be2a 100644 --- a/rpc/metrics.go +++ b/rpc/metrics.go @@ -40,6 +40,7 @@ func updateServeTimeHistogram(method string, success bool, elapsed time.Duration if !success { note = "failure" } + h := fmt.Sprintf("%s/%s/%s", serveTimeHistName, method, note) sampler := func() metrics.Sample { return metrics.ResettingSample( diff --git a/rpc/server.go b/rpc/server.go index 5d74c5278c..2e12b802d4 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -50,7 +50,7 @@ type Server struct { mutex sync.Mutex codecs map[ServerCodec]struct{} - run int32 + run int32 BatchLimit uint64 executionPool *SafePool @@ -60,7 +60,7 @@ type Server struct { func NewServer(executionPoolSize uint64, executionPoolRequesttimeout time.Duration) *Server { server := &Server{ idgen: randomIDGenerator(), - codecs: make(map[ServerCodec]struct{}), + codecs: make(map[ServerCodec]struct{}), run: 1, executionPool: NewExecutionPool(int(executionPoolSize), executionPoolRequesttimeout), } @@ -125,7 +125,9 @@ func (s *Server) trackCodec(codec ServerCodec) bool { if atomic.LoadInt32(&s.run) == 0 { return false // Don't serve if server is stopped. } + s.codecs[codec] = struct{}{} + return true } @@ -184,6 +186,7 @@ func (s *Server) Stop() { if atomic.CompareAndSwapInt32(&s.run, 1, 0) { log.Debug("RPC server shutting down") + for codec := range s.codecs { codec.close() } diff --git a/rpc/service.go b/rpc/service.go index cfdfba023a..a666b7c2c7 100644 --- a/rpc/service.go +++ b/rpc/service.go @@ -198,6 +198,7 @@ func (c *callback) call(ctx context.Context, method string, args []reflect.Value buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] log.Error("RPC method " + method + " crashed: " + fmt.Sprintf("%v\n%s", err, buf)) + errRes = &internalServerError{errcodePanic, "method handler crashed"} } }() diff --git a/rpc/subscription.go b/rpc/subscription.go index 334ead3ace..91c4b0c1f6 100644 --- a/rpc/subscription.go +++ b/rpc/subscription.go @@ -181,6 +181,7 @@ func (n *Notifier) send(sub *Subscription, data json.RawMessage) error { Method: n.namespace + notificationMethodSuffix, Params: params, } + return n.h.conn.writeJSON(ctx, msg, false) } diff --git a/rpc/types.go b/rpc/types.go index 9dda067e7f..130f71c276 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -171,14 +171,17 @@ func (bnh *BlockNumberOrHash) UnmarshalJSON(data []byte) error { case "pending": bn := PendingBlockNumber bnh.BlockNumber = &bn + return nil case "finalized": bn := FinalizedBlockNumber bnh.BlockNumber = &bn + return nil case "safe": bn := SafeBlockNumber bnh.BlockNumber = &bn + return nil default: if len(input) == 66 { diff --git a/rpc/websocket.go b/rpc/websocket.go index a6b95dd2ac..43fa140f9c 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -190,13 +190,16 @@ func parseOriginURL(origin string) (string, string, string, error) { func DialWebsocketWithDialer(ctx context.Context, endpoint, origin string, dialer websocket.Dialer) (*Client, error) { cfg := new(clientConfig) cfg.wsDialer = &dialer + if origin != "" { cfg.setHeader("origin", origin) } + connect, err := newClientTransportWS(endpoint, cfg) if err != nil { return nil, err } + return newClient(ctx, connect) } @@ -210,10 +213,13 @@ func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error if origin != "" { cfg.setHeader("origin", origin) } + connect, err := newClientTransportWS(endpoint, cfg) + if err != nil { return nil, err } + return newClient(ctx, connect) } @@ -231,6 +237,7 @@ func newClientTransportWS(endpoint string, cfg *clientConfig) (reconnectFunc, er if err != nil { return nil, err } + for key, values := range cfg.httpHeaders { header[key] = values } @@ -242,16 +249,23 @@ func newClientTransportWS(endpoint string, cfg *clientConfig) (reconnectFunc, er return nil, err } } + conn, resp, err := dialer.DialContext(ctx, dialURL, header) + if err != nil { hErr := wsHandshakeError{err: err} if resp != nil { hErr.status = resp.Status } + return nil, hErr } + + resp.Body.Close() + return newWebsocketCodec(conn, dialURL, header), nil } + return connect, nil } diff --git a/signer/storage/aes_gcm_storage.go b/signer/storage/aes_gcm_storage.go index 928d643dd6..c222648bb0 100644 --- a/signer/storage/aes_gcm_storage.go +++ b/signer/storage/aes_gcm_storage.go @@ -135,6 +135,7 @@ func (s *AESEncryptedStorage) writeEncryptedStorage(creds map[string]storedCrede if err != nil { return err } + if err = os.WriteFile(s.filename, raw, 0600); err != nil { return err } diff --git a/signer/storage/aes_gcm_storage_test.go b/signer/storage/aes_gcm_storage_test.go index e1fea59280..a25bce61cb 100644 --- a/signer/storage/aes_gcm_storage_test.go +++ b/signer/storage/aes_gcm_storage_test.go @@ -139,6 +139,7 @@ func TestSwappedKeys(t *testing.T) { if err != nil { t.Fatal(err) } + if err = os.WriteFile(s1.filename, raw, 0600); err != nil { t.Fatal(err) } diff --git a/tests/bor/bor_sprint_length_change_test.go b/tests/bor/bor_sprint_length_change_test.go index 5aef2ade1c..bab5170f86 100644 --- a/tests/bor/bor_sprint_length_change_test.go +++ b/tests/bor/bor_sprint_length_change_test.go @@ -5,7 +5,6 @@ import ( "encoding/csv" "encoding/json" "fmt" - "github.com/ethereum/go-ethereum/core/txpool" "io/ioutil" // nolint: staticcheck _log "log" "math/big" diff --git a/tests/fuzzers/rlp/rlp_fuzzer.go b/tests/fuzzers/rlp/rlp_fuzzer.go index 9fcdb57769..79a1ac1ecb 100644 --- a/tests/fuzzers/rlp/rlp_fuzzer.go +++ b/tests/fuzzers/rlp/rlp_fuzzer.go @@ -23,7 +23,6 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" - "github.com/holiman/uint256" ) func decodeEncode(input []byte, val interface{}, i int) {