dev: fix: more wsl lint issues

This commit is contained in:
marcello33 2023-06-15 13:06:10 +02:00
parent 3af5e435c7
commit 218917076c
141 changed files with 478 additions and 89 deletions

View file

@ -28,6 +28,7 @@ import (
"time" "time"
mapset "github.com/deckarep/golang-set/v2" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"

View file

@ -24,6 +24,7 @@ import (
"time" "time"
mapset "github.com/deckarep/golang-set/v2" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
) )

View file

@ -24,6 +24,8 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
"github.com/ethereum/go-ethereum/log"
) )
type watcher struct { type watcher struct {

View file

@ -30,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -28,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/urfave/cli/v2"
) )
// newClient creates a client with specified remote URL. // newClient creates a client with specified remote URL.

View file

@ -36,7 +36,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/urfave/cli/v2"
) )
var commandDeploy = &cli.Command{ var commandDeploy = &cli.Command{

View file

@ -25,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/common/fdlimit" "github.com/ethereum/go-ethereum/common/fdlimit"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/urfave/cli/v2"
) )
var app = flags.NewApp("ethereum checkpoint helper tool") var app = flags.NewApp("ethereum checkpoint helper tool")

View file

@ -21,6 +21,8 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/common"
) )
var commandStatus = &cli.Command{ var commandStatus = &cli.Command{

View file

@ -22,6 +22,7 @@ import (
"testing" "testing"
"github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/reexec"
"github.com/ethereum/go-ethereum/internal/cmdtest" "github.com/ethereum/go-ethereum/internal/cmdtest"
) )

View file

@ -30,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -24,7 +24,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/discover"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -24,7 +24,6 @@ import (
"github.com/cloudflare/cloudflare-go" "github.com/cloudflare/cloudflare-go"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/dnsdisc" "github.com/ethereum/go-ethereum/p2p/dnsdisc"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -32,7 +32,6 @@ import (
"github.com/aws/aws-sdk-go-v2/service/route53/types" "github.com/aws/aws-sdk-go-v2/service/route53/types"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/dnsdisc" "github.com/ethereum/go-ethereum/p2p/dnsdisc"
"github.com/urfave/cli/v2"
) )
const ( const (

View file

@ -29,7 +29,6 @@ import (
"github.com/ethereum/go-ethereum/console/prompt" "github.com/ethereum/go-ethereum/console/prompt"
"github.com/ethereum/go-ethereum/p2p/dnsdisc" "github.com/ethereum/go-ethereum/p2p/dnsdisc"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -30,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/p2p/enr"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/urfave/cli/v2"
) )
var fileFlag = &cli.StringFlag{Name: "file"} var fileFlag = &cli.StringFlag{Name: "file"}

View file

@ -23,7 +23,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/p2p/enr"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -23,7 +23,6 @@ import (
"github.com/ethereum/go-ethereum/internal/debug" "github.com/ethereum/go-ethereum/internal/debug"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/p2p/enode"
"github.com/urfave/cli/v2"
) )
var app = flags.NewApp("go-ethereum devp2p tool") var app = flags.NewApp("go-ethereum devp2p tool")

View file

@ -29,7 +29,6 @@ import (
"github.com/ethereum/go-ethereum/p2p/enr" "github.com/ethereum/go-ethereum/p2p/enr"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -25,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/rlpx" "github.com/ethereum/go-ethereum/p2p/rlpx"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -22,7 +22,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test" "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test"
"github.com/ethereum/go-ethereum/internal/utesting" "github.com/ethereum/go-ethereum/internal/utesting"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -23,7 +23,6 @@ import (
"github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/urfave/cli/v2"
) )
var newPassphraseFlag = &cli.StringFlag{ var newPassphraseFlag = &cli.StringFlag{

View file

@ -24,7 +24,6 @@ import (
"github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/urfave/cli/v2"
) )
type outputInspect struct { type outputInspect struct {

View file

@ -22,6 +22,8 @@ import (
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/internal/flags"
) )
const ( const (

View file

@ -26,7 +26,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/urfave/cli/v2"
) )
type outputSign struct { type outputSign struct {

View file

@ -24,6 +24,8 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/utils"
) )
// getPassphrase obtains a passphrase given by the user. It first checks the // getPassphrase obtains a passphrase given by the user. It first checks the

View file

@ -22,9 +22,10 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
) )
var blockTestCommand = &cli.Command{ var blockTestCommand = &cli.Command{

View file

@ -24,6 +24,8 @@ import (
"github.com/ethereum/go-ethereum/core/asm" "github.com/ethereum/go-ethereum/core/asm"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/core/asm"
) )
var disasmCommand = &cli.Command{ var disasmCommand = &cli.Command{

View file

@ -34,7 +34,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp" "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 //go:generate go run github.com/fjl/gencodec -type header -field-override headerMarshaling -out gen_header.go

View file

@ -22,7 +22,6 @@ import (
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -32,7 +32,6 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
) )
type result struct { type result struct {

View file

@ -39,7 +39,6 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
) )
const ( const (

View file

@ -24,7 +24,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/evm/internal/t8ntool" "github.com/ethereum/go-ethereum/cmd/evm/internal/t8ntool"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -41,7 +41,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"github.com/urfave/cli/v2"
) )
var runCommand = &cli.Command{ var runCommand = &cli.Command{

View file

@ -28,7 +28,6 @@ import (
"github.com/ethereum/go-ethereum/eth/tracers/logger" "github.com/ethereum/go-ethereum/eth/tracers/logger"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/tests" "github.com/ethereum/go-ethereum/tests"
"github.com/urfave/cli/v2"
) )
var stateTestCommand = &cli.Command{ var stateTestCommand = &cli.Command{

View file

@ -25,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -40,7 +40,6 @@ import (
"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -18,7 +18,6 @@ package main
import ( import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/node"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -26,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/console" "github.com/ethereum/go-ethereum/console"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -27,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/consensus/ethash" "github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/internal/version" "github.com/ethereum/go-ethereum/internal/version"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -35,7 +35,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -23,13 +23,14 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/gballet/go-verkle"
cli "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/gballet/go-verkle"
cli "github.com/urfave/cli/v2"
) )
var ( var (

View file

@ -29,6 +29,8 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/jedisct1/go-minisign" "github.com/jedisct1/go-minisign"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/log"
) )
var gethPubKeys []string = []string{ var gethPubKeys []string = []string{

View file

@ -51,7 +51,6 @@ import (
"github.com/ethereum/go-ethereum/p2p/simulations" "github.com/ethereum/go-ethereum/p2p/simulations"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters" "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/urfave/cli/v2"
) )
var client *simulations.Client var client *simulations.Client

View file

@ -2,8 +2,6 @@ package utils
import ( import (
"encoding/json" "encoding/json"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/urfave/cli/v2"
"os" "os"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"

View file

@ -41,7 +41,6 @@ import (
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node" "github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/urfave/cli/v2"
) )
const ( const (

View file

@ -24,7 +24,6 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/trie"
"math" "math"
"math/big" "math/big"
"net/http" "net/http"
@ -75,9 +74,6 @@ import (
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc" "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. // These are all the command line flags we support.

View file

@ -19,8 +19,9 @@ package utils
import ( import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/internal/flags"
) )
var ShowDeprecated = &cli.Command{ var ShowDeprecated = &cli.Command{

View file

@ -101,6 +101,7 @@ func ParseHexOrString(str string) ([]byte, error) {
if errors.Is(err, hexutil.ErrMissingPrefix) { if errors.Is(err, hexutil.ErrMissingPrefix) {
return []byte(str), nil return []byte(str), nil
} }
return b, err return b, err
} }

View file

@ -70,9 +70,11 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin
if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil {
return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) return nil, fmt.Errorf("solc: error reading abi definition (%v)", err)
} }
if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil { if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil {
return nil, fmt.Errorf("solc: error reading userdoc definition (%v)", err) return nil, fmt.Errorf("solc: error reading userdoc definition (%v)", err)
} }
if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil { if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil {
return nil, fmt.Errorf("solc: error reading devdoc definition (%v)", err) return nil, fmt.Errorf("solc: error reading devdoc definition (%v)", err)
} }

View file

@ -37,11 +37,13 @@ func NewBasicLRU[K comparable, V any](capacity int) BasicLRU[K, V] {
if capacity <= 0 { if capacity <= 0 {
capacity = 1 capacity = 1
} }
c := BasicLRU[K, V]{ c := BasicLRU[K, V]{
items: make(map[K]cacheItem[K, V]), items: make(map[K]cacheItem[K, V]),
list: newList[K](), list: newList[K](),
cap: capacity, cap: capacity,
} }
return c return c
} }
@ -53,6 +55,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) {
item.value = value item.value = value
c.items[key] = item c.items[key] = item
c.list.moveToFront(item.elem) c.list.moveToFront(item.elem)
return false return false
} }
@ -60,6 +63,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) {
if c.Len() >= c.cap { if c.Len() >= c.cap {
elem = c.list.removeLast() elem = c.list.removeLast()
delete(c.items, elem.v) delete(c.items, elem.v)
evicted = true evicted = true
} else { } else {
elem = new(listElem[K]) elem = new(listElem[K])
@ -70,6 +74,7 @@ func (c *BasicLRU[K, V]) Add(key K, value V) (evicted bool) {
elem.v = key elem.v = key
c.items[key] = cacheItem[K, V]{elem, value} c.items[key] = cacheItem[K, V]{elem, value}
c.list.pushElem(elem) c.list.pushElem(elem)
return evicted return evicted
} }
@ -85,7 +90,9 @@ func (c *BasicLRU[K, V]) Get(key K) (value V, ok bool) {
if !ok { if !ok {
return value, false return value, false
} }
c.list.moveToFront(item.elem) c.list.moveToFront(item.elem)
return item.value, true return item.value, true
} }
@ -96,8 +103,10 @@ func (c *BasicLRU[K, V]) GetOldest() (key K, value V, ok bool) {
if lastElem == nil { if lastElem == nil {
return key, value, false return key, value, false
} }
key = lastElem.v key = lastElem.v
item := c.items[key] item := c.items[key]
return key, item.value, true 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. // Purge empties the cache.
func (c *BasicLRU[K, V]) Purge() { func (c *BasicLRU[K, V]) Purge() {
c.list.init() c.list.init()
for k := range c.items { for k := range c.items {
delete(c.items, k) delete(c.items, k)
} }
@ -127,6 +137,7 @@ func (c *BasicLRU[K, V]) Remove(key K) bool {
delete(c.items, key) delete(c.items, key)
c.list.remove(item.elem) c.list.remove(item.elem)
} }
return ok return ok
} }
@ -141,6 +152,7 @@ func (c *BasicLRU[K, V]) RemoveOldest() (key K, value V, ok bool) {
item := c.items[key] item := c.items[key]
delete(c.items, key) delete(c.items, key)
c.list.remove(lastElem) c.list.remove(lastElem)
return key, item.value, true return key, item.value, true
} }
@ -165,6 +177,7 @@ type listElem[T any] struct {
func newList[T any]() *list[T] { func newList[T any]() *list[T] {
l := new(list[T]) l := new(list[T])
l.init() l.init()
return l return l
} }
@ -202,6 +215,7 @@ func (l *list[T]) removeLast() *listElem[T] {
if last != nil { if last != nil {
l.remove(last) l.remove(last)
} }
return last return last
} }
@ -211,6 +225,7 @@ func (l *list[T]) last() *listElem[T] {
if e == &l.root { if e == &l.root {
return nil return nil
} }
return e 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 { for e := l.root.prev; e != &l.root; e = e.prev {
slice = append(slice, e.v) slice = append(slice, e.v)
} }
return slice return slice
} }

View file

@ -33,6 +33,7 @@ func TestBasicLRU(t *testing.T) {
for i := 0; i < 256; i++ { for i := 0; i < 256; i++ {
cache.Add(i, i) cache.Add(i, i)
} }
if cache.Len() != 128 { if cache.Len() != 128 {
t.Fatalf("bad len: %v", cache.Len()) t.Fatalf("bad len: %v", cache.Len())
} }
@ -42,14 +43,17 @@ func TestBasicLRU(t *testing.T) {
if len(keys) != 128 { if len(keys) != 128 {
t.Fatal("wrong Keys() length", len(keys)) t.Fatal("wrong Keys() length", len(keys))
} }
for i, k := range keys { for i, k := range keys {
v, ok := cache.Peek(k) v, ok := cache.Peek(k)
if !ok { if !ok {
t.Fatalf("expected key %d be present", i) t.Fatalf("expected key %d be present", i)
} }
if v != k { if v != k {
t.Fatalf("expected %d == %d", k, v) t.Fatalf("expected %d == %d", k, v)
} }
if v != i+128 { if v != i+128 {
t.Fatalf("wrong value at key %d: %d, want %d", i, 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) t.Fatalf("%d should be evicted", i)
} }
} }
for i := 128; i < 256; i++ { for i := 128; i < 256; i++ {
_, ok := cache.Get(i) _, ok := cache.Get(i)
if !ok { if !ok {
@ -73,11 +78,15 @@ func TestBasicLRU(t *testing.T) {
if !ok { if !ok {
t.Fatalf("%d should be in cache", i) t.Fatalf("%d should be in cache", i)
} }
ok = cache.Remove(i) ok = cache.Remove(i)
if ok { if ok {
t.Fatalf("%d should not be in cache", i) t.Fatalf("%d should not be in cache", i)
} }
_, ok = cache.Get(i) _, ok = cache.Get(i)
if ok { if ok {
t.Fatalf("%d should be deleted", i) t.Fatalf("%d should be deleted", i)
} }
@ -93,9 +102,11 @@ func TestBasicLRU(t *testing.T) {
} }
cache.Purge() cache.Purge()
if cache.Len() != 0 { if cache.Len() != 0 {
t.Fatalf("bad len: %v", cache.Len()) t.Fatalf("bad len: %v", cache.Len())
} }
if _, ok := cache.Get(200); ok { if _, ok := cache.Get(200); ok {
t.Fatalf("should contain nothing") t.Fatalf("should contain nothing")
} }
@ -128,6 +139,7 @@ func TestBasicLRUGetOldest(t *testing.T) {
if !ok { if !ok {
t.Fatalf("missing") t.Fatalf("missing")
} }
if k != 128 { if k != 128 {
t.Fatalf("bad: %v", k) t.Fatalf("bad: %v", k)
} }
@ -136,6 +148,7 @@ func TestBasicLRUGetOldest(t *testing.T) {
if !ok { if !ok {
t.Fatalf("missing") t.Fatalf("missing")
} }
if k != 128 { if k != 128 {
t.Fatalf("bad: %v", k) t.Fatalf("bad: %v", k)
} }
@ -144,6 +157,7 @@ func TestBasicLRUGetOldest(t *testing.T) {
if !ok { if !ok {
t.Fatalf("missing oldest item") t.Fatalf("missing oldest item")
} }
if k != 129 { if k != 129 {
t.Fatalf("wrong oldest item: %v", k) t.Fatalf("wrong oldest item: %v", k)
} }
@ -157,6 +171,7 @@ func TestBasicLRUAddReturnValue(t *testing.T) {
if cache.Add(1, 1) { if cache.Add(1, 1) {
t.Errorf("first add shouldn't have evicted") t.Errorf("first add shouldn't have evicted")
} }
if !cache.Add(2, 2) { if !cache.Add(2, 2) {
t.Errorf("second add should have evicted") t.Errorf("second add should have evicted")
} }
@ -169,10 +184,13 @@ func TestBasicLRUContains(t *testing.T) {
cache := NewBasicLRU[int, int](2) cache := NewBasicLRU[int, int](2)
cache.Add(1, 1) cache.Add(1, 1)
cache.Add(2, 2) cache.Add(2, 2)
if !cache.Contains(1) { if !cache.Contains(1) {
t.Errorf("1 should be in the cache") t.Errorf("1 should be in the cache")
} }
cache.Add(3, 3) cache.Add(3, 3)
if cache.Contains(1) { if cache.Contains(1) {
t.Errorf("Contains should not have updated recency of 1") t.Errorf("Contains should not have updated recency of 1")
} }
@ -185,9 +203,11 @@ func BenchmarkLRU(b *testing.B) {
keys = make([]string, capacity) keys = make([]string, capacity)
values = make([][]byte, capacity) values = make([][]byte, capacity)
) )
for i := range indexes { for i := range indexes {
indexes[i] = rand.Intn(capacity) indexes[i] = rand.Intn(capacity)
} }
for i := range keys { for i := range keys {
b := make([]byte, 32) b := make([]byte, 32)
crand.Read(b) crand.Read(b)

View file

@ -63,15 +63,20 @@ func (c *SizeConstrainedCache[K, V]) Add(key K, value V) (evicted bool) {
for targetSize > c.maxSize { for targetSize > c.maxSize {
evicted = true evicted = true
_, v, ok := c.lru.RemoveOldest() _, v, ok := c.lru.RemoveOldest()
if !ok { if !ok {
// list is now empty. Break // list is now empty. Break
break break
} }
targetSize -= uint64(len(v)) targetSize -= uint64(len(v))
} }
c.size = targetSize c.size = targetSize
} }
c.lru.Add(key, value) c.lru.Add(key, value)
return evicted return evicted
} }

View file

@ -33,6 +33,7 @@ func TestSizeConstrainedCache(t *testing.T) {
t.Parallel() t.Parallel()
lru := NewSizeConstrainedCache[testKey, []byte](100) lru := NewSizeConstrainedCache[testKey, []byte](100)
var want uint64 var want uint64
// Add 11 items of 10 byte each. First item should be swapped out // Add 11 items of 10 byte each. First item should be swapped out
for i := 0; i < 11; i++ { for i := 0; i < 11; i++ {
@ -40,9 +41,11 @@ func TestSizeConstrainedCache(t *testing.T) {
v := fmt.Sprintf("value-%04d", i) v := fmt.Sprintf("value-%04d", i)
lru.Add(k, []byte(v)) lru.Add(k, []byte(v))
want += uint64(len(v)) want += uint64(len(v))
if want > 100 { if want > 100 {
want = 100 want = 100
} }
if have := lru.size; have != want { if have := lru.size; have != want {
t.Fatalf("size wrong, have %d want %d", have, want) t.Fatalf("size wrong, have %d want %d", have, want)
} }
@ -59,9 +62,11 @@ func TestSizeConstrainedCache(t *testing.T) {
k := mkKey(i) k := mkKey(i)
want := fmt.Sprintf("value-%04d", i) want := fmt.Sprintf("value-%04d", i)
have, ok := lru.Get(k) have, ok := lru.Get(k)
if !ok { if !ok {
t.Fatalf("missing key %v", k) t.Fatalf("missing key %v", k)
} }
if string(have) != want { if string(have) != want {
t.Fatalf("wrong value, have %v want %v", 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. // Add one 10 byte-item 10 times.
k := mkKey(0) k := mkKey(0)
v := fmt.Sprintf("value-%04d", 0) v := fmt.Sprintf("value-%04d", 0)
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
lru.Add(k, []byte(v)) lru.Add(k, []byte(v))
} }

View file

@ -59,6 +59,7 @@ func (i *HexOrDecimal256) UnmarshalJSON(input []byte) error {
if len(input) > 0 && input[0] == '"' { if len(input) > 0 && input[0] == '"' {
input = input[1 : len(input)-1] input = input[1 : len(input)-1]
} }
return i.UnmarshalText(input) return i.UnmarshalText(input)
} }

View file

@ -49,6 +49,7 @@ func (i *HexOrDecimal64) UnmarshalJSON(input []byte) error {
if len(input) > 0 && input[0] == '"' { if len(input) > 0 && input[0] == '"' {
input = input[1 : len(input)-1] input = input[1 : len(input)-1]
} }
return i.UnmarshalText(input) return i.UnmarshalText(input)
} }

View file

@ -38,6 +38,7 @@ func NewAlarm(clock Clock) *Alarm {
if clock == nil { if clock == nil {
panic("nil clock") panic("nil clock")
} }
return &Alarm{ return &Alarm{
ch: make(chan struct{}, 1), ch: make(chan struct{}, 1),
clock: clock, clock: clock,
@ -57,6 +58,7 @@ func (e *Alarm) Stop() {
if e.timer != nil { if e.timer != nil {
e.timer.Stop() e.timer.Stop()
} }
e.deadline = 0 e.deadline = 0
// Drain the channel. // Drain the channel.
@ -84,16 +86,19 @@ func (e *Alarm) schedule(now, newDeadline AbsTime) {
// to be rescheduled. // to be rescheduled.
return return
} }
e.timer.Stop() e.timer.Stop()
} }
// Set the timer. // Set the timer.
d := time.Duration(0) d := time.Duration(0)
if newDeadline < now { if newDeadline < now {
newDeadline = now newDeadline = now
} else { } else {
d = newDeadline.Sub(now) d = newDeadline.Sub(now)
} }
e.timer = e.clock.AfterFunc(d, e.send) e.timer = e.clock.AfterFunc(d, e.send)
e.deadline = newDeadline e.deadline = newDeadline
} }

View file

@ -27,37 +27,47 @@ func TestAlarm(t *testing.T) {
a := NewAlarm(clk) a := NewAlarm(clk)
a.Schedule(clk.Now() + 10) a.Schedule(clk.Now() + 10)
if recv(a.C()) { if recv(a.C()) {
t.Fatal("Alarm fired before scheduled deadline") t.Fatal("Alarm fired before scheduled deadline")
} }
if ntimers := clk.ActiveTimers(); ntimers != 1 { if ntimers := clk.ActiveTimers(); ntimers != 1 {
t.Fatal("clock has", ntimers, "active timers, want", 1) t.Fatal("clock has", ntimers, "active timers, want", 1)
} }
clk.Run(5) clk.Run(5)
if recv(a.C()) { if recv(a.C()) {
t.Fatal("Alarm fired too early") t.Fatal("Alarm fired too early")
} }
clk.Run(5) clk.Run(5)
if !recv(a.C()) { if !recv(a.C()) {
t.Fatal("Alarm did not fire") t.Fatal("Alarm did not fire")
} }
if recv(a.C()) { if recv(a.C()) {
t.Fatal("Alarm fired twice") t.Fatal("Alarm fired twice")
} }
if ntimers := clk.ActiveTimers(); ntimers != 0 { if ntimers := clk.ActiveTimers(); ntimers != 0 {
t.Fatal("clock has", ntimers, "active timers, want", 0) t.Fatal("clock has", ntimers, "active timers, want", 0)
} }
a.Schedule(clk.Now() + 5) a.Schedule(clk.Now() + 5)
if recv(a.C()) { if recv(a.C()) {
t.Fatal("Alarm fired before scheduled deadline when scheduling the second event") t.Fatal("Alarm fired before scheduled deadline when scheduling the second event")
} }
clk.Run(5) clk.Run(5)
if !recv(a.C()) { if !recv(a.C()) {
t.Fatal("Alarm did not fire when scheduling the second event") t.Fatal("Alarm did not fire when scheduling the second event")
} }
if recv(a.C()) { if recv(a.C()) {
t.Fatal("Alarm fired twice when scheduling the second event") t.Fatal("Alarm fired twice when scheduling the second event")
} }
@ -76,6 +86,7 @@ func TestAlarmScheduleEarlier(t *testing.T) {
clk.Run(5) clk.Run(5)
a.Schedule(clk.Now() + 1) a.Schedule(clk.Now() + 1)
clk.Run(3) clk.Run(3)
if !recv(a.C()) { if !recv(a.C()) {
t.Fatal("Alarm did not fire") t.Fatal("Alarm did not fire")
} }
@ -94,6 +105,7 @@ func TestAlarmScheduleLater(t *testing.T) {
clk.Run(5) clk.Run(5)
a.Schedule(clk.Now() + 100) a.Schedule(clk.Now() + 100)
clk.Run(50) clk.Run(50)
if !recv(a.C()) { if !recv(a.C()) {
t.Fatal("Alarm did not fire") t.Fatal("Alarm did not fire")
} }
@ -109,6 +121,7 @@ func TestAlarmNegative(t *testing.T) {
a.Schedule(-1) a.Schedule(-1)
clk.Run(1) // needed to process timers clk.Run(1) // needed to process timers
if !recv(a.C()) { if !recv(a.C()) {
t.Fatal("Alarm did not fire for negative time") t.Fatal("Alarm did not fire for negative time")
} }

View file

@ -22,6 +22,8 @@ import (
"github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/common/mclock"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"github.com/ethereum/go-ethereum/common/mclock"
) )
// LazyQueue is a priority queue data structure where priorities can change over // LazyQueue is a priority queue data structure where priorities can change over

View file

@ -167,28 +167,34 @@ func TestMixedcaseAddressMarshal(t *testing.T) {
output string output string
input = "0xae967917c465db8578ca9024c205720b1a3651A9" input = "0xae967917c465db8578ca9024c205720b1a3651A9"
) )
addr, err := NewMixedcaseAddressFromString(input) addr, err := NewMixedcaseAddressFromString(input)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
blob, err := json.Marshal(*addr) blob, err := json.Marshal(*addr)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
json.Unmarshal(blob, &output) json.Unmarshal(blob, &output)
if output != input { if output != input {
t.Fatal("Failed to marshal/unmarshal MixedcaseAddress object") t.Fatal("Failed to marshal/unmarshal MixedcaseAddress object")
} }
} }
func TestMixedcaseAccount_Address(t *testing.T) { func TestMixedcaseAccount_Address(t *testing.T) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md t.Parallel()
// Note: 0X{checksum_addr} is not valid according to spec above
var res []struct { var res []struct {
A MixedcaseAddress A MixedcaseAddress
Valid bool 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(`[ if err := json.Unmarshal([]byte(`[
{"A" : "0xae967917c465db8578ca9024c205720b1a3651A9", "Valid": false}, {"A" : "0xae967917c465db8578ca9024c205720b1a3651A9", "Valid": false},
{"A" : "0xAe967917c465db8578ca9024c205720b1a3651A9", "Valid": true}, {"A" : "0xAe967917c465db8578ca9024c205720b1a3651A9", "Valid": true},

View file

@ -26,6 +26,8 @@ import (
"time" "time"
mapset "github.com/deckarep/golang-set/v2" mapset "github.com/deckarep/golang-set/v2"
"golang.org/x/crypto/sha3"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/consensus"

View file

@ -67,8 +67,8 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int {
} }
var ( var (
num = new(big.Int) num = new(big.Int)
denom = new(big.Int) denom = new(big.Int)
baseFeeChangeDenominatorUint64 = params.BaseFeeChangeDenominator(config.Bor, parent.Number) baseFeeChangeDenominatorUint64 = params.BaseFeeChangeDenominator(config.Bor, parent.Number)
) )

View file

@ -22,7 +22,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/rlp"
"io" "io"
"math/big" "math/big"
"os" "os"

View file

@ -17,7 +17,6 @@
package core package core
import ( import (
"github.com/ethereum/go-ethereum/ethdb"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"

View file

@ -1,7 +1,6 @@
package core package core
import ( import (
"github.com/ethereum/go-ethereum/trie"
"math/big" "math/big"
"testing" "testing"

View file

@ -20,11 +20,12 @@ import (
"fmt" "fmt"
"sync" "sync"
"golang.org/x/crypto/sha3"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"golang.org/x/crypto/sha3"
) )
// HashScheme is the legacy hash-based state scheme with which trie nodes are // HashScheme is the legacy hash-based state scheme with which trie nodes are

View file

@ -30,7 +30,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/metrics"
"github.com/gofrs/flock"
) )
var ( var (

View file

@ -17,7 +17,6 @@
package txpool package txpool
import ( import (
"github.com/holiman/uint256"
"math/big" "math/big"
"math/rand" "math/rand"
"testing" "testing"

View file

@ -27,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/kylelemons/godebug/diff"
) )
var ( var (

View file

@ -21,7 +21,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/trie"
"math/big" "math/big"
"runtime" "runtime"
"sync" "sync"

View file

@ -25,6 +25,7 @@ import (
"time" "time"
mapset "github.com/deckarep/golang-set/v2" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/common/mclock"
"github.com/ethereum/go-ethereum/core/txpool" "github.com/ethereum/go-ethereum/core/txpool"

View file

@ -22,6 +22,7 @@ import (
"sync" "sync"
mapset "github.com/deckarep/golang-set/v2" mapset "github.com/deckarep/golang-set/v2"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"

View file

@ -43,7 +43,6 @@ import (
"github.com/ethereum/go-ethereum/p2p/msgrate" "github.com/ethereum/go-ethereum/p2p/msgrate"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
"golang.org/x/crypto/sha3"
) )
const ( const (

View file

@ -31,6 +31,7 @@ var files embed.FS
// returns a mapping of tracer name to source. // returns a mapping of tracer name to source.
func Load() (map[string]string, error) { func Load() (map[string]string, error) {
var assetTracers = make(map[string]string) var assetTracers = make(map[string]string)
err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error { err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
return err return err
@ -46,6 +47,7 @@ func Load() (map[string]string, error) {
assetTracers[name] = string(b) assetTracers[name] = string(b)
return nil return nil
}) })
return assetTracers, err return assetTracers, err
} }
@ -55,5 +57,6 @@ func camel(str string) string {
for i := 1; i < len(pieces); i++ { for i := 1; i < len(pieces); i++ {
pieces[i] = string(unicode.ToUpper(rune(pieces[i][0]))) + pieces[i][1:] pieces[i] = string(unicode.ToUpper(rune(pieces[i][0]))) + pieces[i][1:]
} }
return strings.Join(pieces, "") return strings.Join(pieces, "")
} }

View file

@ -392,17 +392,17 @@ func TestOverrideAccountMarshal(t *testing.T) {
t.Parallel() t.Parallel()
om := map[common.Address]OverrideAccount{ om := map[common.Address]OverrideAccount{
common.Address{0x11}: OverrideAccount{ {0x11}: {
// Zero-valued nonce is not overriddden, but simply dropped by the encoder. // Zero-valued nonce is not overriddden, but simply dropped by the encoder.
Nonce: 0, Nonce: 0,
}, },
common.Address{0xaa}: OverrideAccount{ {0xaa}: {
Nonce: 5, Nonce: 5,
}, },
common.Address{0xbb}: OverrideAccount{ {0xbb}: {
Code: []byte{1}, Code: []byte{1},
}, },
common.Address{0xcc}: OverrideAccount{ {0xcc}: {
// 'code', 'balance', 'state' should be set when input is // 'code', 'balance', 'state' should be set when input is
// a non-nil but empty value. // a non-nil but empty value.
Code: []byte{}, Code: []byte{},

View file

@ -499,18 +499,22 @@ func randBytes(length int) []byte {
if n, err := rand.Read(buf); n != length || err != nil { if n, err := rand.Read(buf); n != length || err != nil {
panic(err) panic(err)
} }
return buf return buf
} }
func makeDataset(size, ksize, vsize int, order bool) ([][]byte, [][]byte) { func makeDataset(size, ksize, vsize int, order bool) ([][]byte, [][]byte) {
var keys [][]byte var keys [][]byte
var vals [][]byte var vals [][]byte
for i := 0; i < size; i += 1 { for i := 0; i < size; i += 1 {
keys = append(keys, randBytes(ksize)) keys = append(keys, randBytes(ksize))
vals = append(vals, randBytes(vsize)) vals = append(vals, randBytes(vsize))
} }
if order { if order {
sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 }) sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i], keys[j]) < 0 })
} }
return keys, vals return keys, vals
} }

View file

@ -292,7 +292,9 @@ func (it *iterator) Next() bool {
if it.index >= len(it.keys) { if it.index >= len(it.keys) {
return false return false
} }
it.index += 1 it.index += 1
return it.index < len(it.keys) return it.index < len(it.keys)
} }
@ -310,6 +312,7 @@ func (it *iterator) Key() []byte {
if it.index < 0 || it.index >= len(it.keys) { if it.index < 0 || it.index >= len(it.keys) {
return nil return nil
} }
return []byte(it.keys[it.index]) return []byte(it.keys[it.index])
} }
@ -321,6 +324,7 @@ func (it *iterator) Value() []byte {
if it.index < 0 || it.index >= len(it.keys) { if it.index < 0 || it.index >= len(it.keys) {
return nil return nil
} }
return it.values[it.index] return it.values[it.index]
} }

View file

@ -29,6 +29,7 @@ import (
"github.com/cockroachdb/pebble" "github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/bloom" "github.com/cockroachdb/pebble/bloom"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
@ -89,7 +90,9 @@ func (d *Database) onCompactionBegin(info pebble.CompactionInfo) {
if d.activeComp == 0 { if d.activeComp == 0 {
d.compStartTime = time.Now() d.compStartTime = time.Now()
} }
l0 := info.Input[0] l0 := info.Input[0]
if l0.Level == 0 { if l0.Level == 0 {
d.level0Comp.Add(1) d.level0Comp.Add(1)
} else { } else {
@ -122,9 +125,11 @@ func New(file string, cache int, handles int, namespace string, readonly bool) (
if cache < minCache { if cache < minCache {
cache = minCache cache = minCache
} }
if handles < minHandles { if handles < minHandles {
handles = minHandles handles = minHandles
} }
logger := log.New("database", file) logger := log.New("database", file)
logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*1024*1024), "handles", handles) 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. // including a frozen memory table and another live one.
memTableLimit := 2 memTableLimit := 2
memTableSize := cache * 1024 * 1024 / 2 / memTableLimit memTableSize := cache * 1024 * 1024 / 2 / memTableLimit
if memTableSize > maxMemTableSize { if memTableSize > maxMemTableSize {
memTableSize = maxMemTableSize memTableSize = maxMemTableSize
} }
db := &Database{ db := &Database{
fn: file, fn: file,
log: logger, log: logger,
@ -195,6 +202,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool) (
if err != nil { if err != nil {
return nil, err return nil, err
} }
db.db = innerDB db.db = innerDB
db.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil) 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 // Start up the metrics gathering and return
go db.meter(metricsGatheringInterval) go db.meter(metricsGatheringInterval)
return db, nil return db, nil
} }
@ -225,11 +234,14 @@ func (d *Database) Close() error {
if d.quitChan != nil { if d.quitChan != nil {
errc := make(chan error) errc := make(chan error)
d.quitChan <- errc d.quitChan <- errc
if err := <-errc; err != nil { if err := <-errc; err != nil {
d.log.Error("Metrics collection failed", "err", err) d.log.Error("Metrics collection failed", "err", err)
} }
d.quitChan = nil d.quitChan = nil
} }
return d.db.Close() return d.db.Close()
} }
@ -241,7 +253,9 @@ func (d *Database) Has(key []byte) (bool, error) {
} else if err != nil { } else if err != nil {
return false, err return false, err
} }
closer.Close() closer.Close()
return true, nil return true, nil
} }
@ -251,9 +265,11 @@ func (d *Database) Get(key []byte) ([]byte, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
ret := make([]byte, len(dat)) ret := make([]byte, len(dat))
copy(ret, dat) copy(ret, dat)
closer.Close() closer.Close()
return ret, nil return ret, nil
} }
@ -311,7 +327,9 @@ func (snap *snapshot) Has(key []byte) (bool, error) {
return false, nil return false, nil
} }
} }
closer.Close() closer.Close()
return true, nil return true, nil
} }
@ -322,9 +340,11 @@ func (snap *snapshot) Get(key []byte) ([]byte, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
ret := make([]byte, len(dat)) ret := make([]byte, len(dat))
copy(ret, dat) copy(ret, dat)
closer.Close() closer.Close()
return ret, nil return ret, nil
} }
@ -341,11 +361,14 @@ func upperBound(prefix []byte) (limit []byte) {
if c == 0xff { if c == 0xff {
continue continue
} }
limit = make([]byte, i+1) limit = make([]byte, i+1)
copy(limit, prefix) copy(limit, prefix)
limit[i] = c + 1 limit[i] = c + 1
break break
} }
return limit return limit
} }
@ -373,6 +396,7 @@ func (d *Database) Compact(start []byte, limit []byte) error {
if limit == nil { if limit == nil {
limit = bytes.Repeat([]byte{0xff}, 32) limit = bytes.Repeat([]byte{0xff}, 32)
} }
return d.db.Compact(start, limit, true) // Parallelization is preferred return d.db.Compact(start, limit, true) // Parallelization is preferred
} }
@ -385,7 +409,9 @@ func (d *Database) Path() string {
// the metrics subsystem. // the metrics subsystem.
func (d *Database) meter(refresh time.Duration) { func (d *Database) meter(refresh time.Duration) {
var errc chan error var errc chan error
timer := time.NewTimer(refresh) timer := time.NewTimer(refresh)
defer timer.Stop() defer timer.Stop()
// Create storage and warning log tracer for write delay. // 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()) nonLevel0CompCount = int64(d.nonLevel0Comp.Load())
level0CompCount = int64(d.level0Comp.Load()) level0CompCount = int64(d.level0Comp.Load())
) )
writeDelayTimes[i%2] = writeDelayTime writeDelayTimes[i%2] = writeDelayTime
writeDelayCounts[i%2] = writeDelayCount writeDelayCounts[i%2] = writeDelayCount
compTimes[i%2] = compTime compTimes[i%2] = compTime
@ -433,24 +460,31 @@ func (d *Database) meter(refresh time.Duration) {
if d.writeDelayNMeter != nil { if d.writeDelayNMeter != nil {
d.writeDelayNMeter.Mark(writeDelayCounts[i%2] - writeDelayCounts[(i-1)%2]) d.writeDelayNMeter.Mark(writeDelayCounts[i%2] - writeDelayCounts[(i-1)%2])
} }
if d.writeDelayMeter != nil { if d.writeDelayMeter != nil {
d.writeDelayMeter.Mark(writeDelayTimes[i%2] - writeDelayTimes[(i-1)%2]) d.writeDelayMeter.Mark(writeDelayTimes[i%2] - writeDelayTimes[(i-1)%2])
} }
if d.compTimeMeter != nil { if d.compTimeMeter != nil {
d.compTimeMeter.Mark(compTimes[i%2] - compTimes[(i-1)%2]) d.compTimeMeter.Mark(compTimes[i%2] - compTimes[(i-1)%2])
} }
if d.compReadMeter != nil { if d.compReadMeter != nil {
d.compReadMeter.Mark(compReads[i%2] - compReads[(i-1)%2]) d.compReadMeter.Mark(compReads[i%2] - compReads[(i-1)%2])
} }
if d.compWriteMeter != nil { if d.compWriteMeter != nil {
d.compWriteMeter.Mark(compWrites[i%2] - compWrites[(i-1)%2]) d.compWriteMeter.Mark(compWrites[i%2] - compWrites[(i-1)%2])
} }
if d.diskSizeGauge != nil { if d.diskSizeGauge != nil {
d.diskSizeGauge.Update(int64(metrics.DiskSpaceUsage())) d.diskSizeGauge.Update(int64(metrics.DiskSpaceUsage()))
} }
if d.diskReadMeter != nil { if d.diskReadMeter != nil {
d.diskReadMeter.Mark(0) // pebble doesn't track non-compaction reads d.diskReadMeter.Mark(0) // pebble doesn't track non-compaction reads
} }
if d.diskWriteMeter != nil { if d.diskWriteMeter != nil {
d.diskWriteMeter.Mark(nWrites[i%2] - nWrites[(i-1)%2]) 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: case errc = <-d.quitChan:
// Quit requesting, stop hammering the database // Quit requesting, stop hammering the database
case <-timer.C: case <-timer.C:
timer.Reset(refresh)
// Timeout, gather a new set of stats // Timeout, gather a new set of stats
timer.Reset(refresh)
} }
} }
errc <- nil errc <- nil
@ -485,6 +519,7 @@ type batch struct {
func (b *batch) Put(key, value []byte) error { func (b *batch) Put(key, value []byte) error {
b.b.Set(key, value, nil) b.b.Set(key, value, nil)
b.size += len(key) + len(value) b.size += len(key) + len(value)
return nil return nil
} }
@ -492,6 +527,7 @@ func (b *batch) Put(key, value []byte) error {
func (b *batch) Delete(key []byte) error { func (b *batch) Delete(key []byte) error {
b.b.Delete(key, nil) b.b.Delete(key, nil)
b.size += len(key) b.size += len(key)
return nil return nil
} }
@ -514,6 +550,7 @@ func (b *batch) Reset() {
// Replay replays the batch contents. // Replay replays the batch contents.
func (b *batch) Replay(w ethdb.KeyValueWriter) error { func (b *batch) Replay(w ethdb.KeyValueWriter) error {
reader := b.b.Reader() reader := b.b.Reader()
for { for {
kind, k, v, ok := reader.Next() kind, k, v, ok := reader.Next()
if !ok { if !ok {
@ -529,6 +566,7 @@ func (b *batch) Replay(w ethdb.KeyValueWriter) error {
return fmt.Errorf("unhandled operation, keytype: %v", kind) return fmt.Errorf("unhandled operation, keytype: %v", kind)
} }
} }
return nil return nil
} }
@ -548,6 +586,7 @@ func (d *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator {
UpperBound: upperBound(prefix), UpperBound: upperBound(prefix),
}) })
iter.First() iter.First()
return &pebbleIterator{iter: iter, moved: true} return &pebbleIterator{iter: iter, moved: true}
} }
@ -558,6 +597,7 @@ func (iter *pebbleIterator) Next() bool {
iter.moved = false iter.moved = false
return iter.iter.Valid() return iter.iter.Valid()
} }
return iter.iter.Next() return iter.iter.Next()
} }

View file

@ -23,6 +23,7 @@ import (
"github.com/cockroachdb/pebble" "github.com/cockroachdb/pebble"
"github.com/cockroachdb/pebble/vfs" "github.com/cockroachdb/pebble/vfs"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethdb/dbtest" "github.com/ethereum/go-ethereum/ethdb/dbtest"
) )

View file

@ -37,15 +37,18 @@ func (db *Database) Has(key []byte) (bool, error) {
//nolint:nilerr //nolint:nilerr
return false, nil return false, nil
} }
return true, nil return true, nil
} }
func (db *Database) Get(key []byte) ([]byte, error) { func (db *Database) Get(key []byte) ([]byte, error) {
var resp hexutil.Bytes var resp hexutil.Bytes
err := db.remote.Call(&resp, "debug_dbGet", hexutil.Bytes(key)) err := db.remote.Call(&resp, "debug_dbGet", hexutil.Bytes(key))
if err != nil { if err != nil {
return nil, err return nil, err
} }
return resp, nil return resp, nil
} }
@ -54,15 +57,18 @@ func (db *Database) HasAncient(kind string, number uint64) (bool, error) {
//nolint:nilerr //nolint:nilerr
return false, nil return false, nil
} }
return true, nil return true, nil
} }
func (db *Database) Ancient(kind string, number uint64) ([]byte, error) { func (db *Database) Ancient(kind string, number uint64) ([]byte, error) {
var resp hexutil.Bytes var resp hexutil.Bytes
err := db.remote.Call(&resp, "debug_dbAncient", kind, number) err := db.remote.Call(&resp, "debug_dbAncient", kind, number)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return resp, nil return resp, nil
} }
@ -73,6 +79,7 @@ func (db *Database) AncientRange(kind string, start, count, maxBytes uint64) ([]
func (db *Database) Ancients() (uint64, error) { func (db *Database) Ancients() (uint64, error) {
var resp uint64 var resp uint64
err := db.remote.Call(&resp, "debug_dbAncients") err := db.remote.Call(&resp, "debug_dbAncients")
return resp, err return resp, err
} }

View file

@ -58,8 +58,10 @@ func (f *FeedOf[T]) Subscribe(channel chan<- T) Subscription {
// The next Send will add it to f.sendCases. // The next Send will add it to f.sendCases.
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
cas := reflect.SelectCase{Dir: reflect.SelectSend, Chan: chanval} cas := reflect.SelectCase{Dir: reflect.SelectSend, Chan: chanval}
f.inbox = append(f.inbox, cas) f.inbox = append(f.inbox, cas)
return sub return sub
} }
@ -68,9 +70,11 @@ func (f *FeedOf[T]) remove(sub *feedOfSub[T]) {
// that have not been added to f.sendCases yet. // that have not been added to f.sendCases yet.
f.mu.Lock() f.mu.Lock()
index := f.inbox.find(sub.channel) index := f.inbox.find(sub.channel)
if index != -1 { if index != -1 {
f.inbox = f.inbox.delete(index) f.inbox = f.inbox.delete(index)
f.mu.Unlock() f.mu.Unlock()
return return
} }
f.mu.Unlock() 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 // of sendCases. When a send succeeds, the corresponding case moves to the end of
// 'cases' and it shrinks by one element. // 'cases' and it shrinks by one element.
cases := f.sendCases cases := f.sendCases
for { for {
// Fast path: try sending without blocking before adding to the select set. // Fast path: try sending without blocking before adding to the select set.
// This should usually succeed if subscribers are fast enough and have free // 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++ { for i := firstSubSendCase; i < len(cases); i++ {
if cases[i].Chan.TrySend(rvalue) { if cases[i].Chan.TrySend(rvalue) {
nsent++ nsent++
cases = cases.deactivate(i) cases = cases.deactivate(i)
i-- i--
} }
} }
if len(cases) == firstSubSendCase { if len(cases) == firstSubSendCase {
break break
} }
@ -127,6 +134,7 @@ func (f *FeedOf[T]) Send(value T) (nsent int) {
if chosen == 0 /* <-f.removeSub */ { if chosen == 0 /* <-f.removeSub */ {
index := f.sendCases.find(recv.Interface()) index := f.sendCases.find(recv.Interface())
f.sendCases = f.sendCases.delete(index) f.sendCases = f.sendCases.delete(index)
if index >= 0 && index < len(cases) { if index >= 0 && index < len(cases) {
// Shrink 'cases' too because the removed case was still active. // Shrink 'cases' too because the removed case was still active.
cases = f.sendCases[:len(cases)-1] 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.sendCases[i].Send = reflect.Value{}
} }
f.sendLock <- struct{}{} f.sendLock <- struct{}{}
return nsent return nsent
} }

View file

@ -26,12 +26,15 @@ func TestFeedOf(t *testing.T) {
t.Parallel() t.Parallel()
var feed FeedOf[int] var feed FeedOf[int]
var done, subscribed sync.WaitGroup var done, subscribed sync.WaitGroup
subscriber := func(i int) { subscriber := func(i int) {
defer done.Done() defer done.Done()
subchan := make(chan int) subchan := make(chan int)
sub := feed.Subscribe(subchan) sub := feed.Subscribe(subchan)
timeout := time.NewTimer(2 * time.Second) timeout := time.NewTimer(2 * time.Second)
defer timeout.Stop() defer timeout.Stop()
subscribed.Done() subscribed.Done()
@ -57,18 +60,23 @@ func TestFeedOf(t *testing.T) {
} }
const n = 1000 const n = 1000
done.Add(n) done.Add(n)
subscribed.Add(n) subscribed.Add(n)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
go subscriber(i) go subscriber(i)
} }
subscribed.Wait() subscribed.Wait()
if nsent := feed.Send(1); nsent != n { if nsent := feed.Send(1); nsent != n {
t.Errorf("first send delivered %d times, want %d", nsent, n) t.Errorf("first send delivered %d times, want %d", nsent, n)
} }
if nsent := feed.Send(2); nsent != 0 { if nsent := feed.Send(2); nsent != 0 {
t.Errorf("second send delivered %d times, want 0", nsent) t.Errorf("second send delivered %d times, want 0", nsent)
} }
done.Wait() done.Wait()
} }
@ -83,10 +91,12 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) {
sub2 = feed.Subscribe(ch) sub2 = feed.Subscribe(ch)
_ = feed.Subscribe(ch) _ = feed.Subscribe(ch)
) )
expectSends := func(value, n int) { expectSends := func(value, n int) {
if nsent := feed.Send(value); nsent != n { if nsent := feed.Send(value); nsent != n {
t.Errorf("send delivered %d times, want %d", nsent, n) t.Errorf("send delivered %d times, want %d", nsent, n)
} }
done.Done() done.Done()
} }
expectRecv := func(wantValue, n int) { expectRecv := func(wantValue, n int) {
@ -98,6 +108,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) {
} }
done.Add(1) done.Add(1)
go expectSends(1, 3) go expectSends(1, 3)
expectRecv(1, 3) expectRecv(1, 3)
done.Wait() done.Wait()
@ -105,6 +116,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) {
sub1.Unsubscribe() sub1.Unsubscribe()
done.Add(1) done.Add(1)
go expectSends(2, 2) go expectSends(2, 2)
expectRecv(2, 2) expectRecv(2, 2)
done.Wait() done.Wait()
@ -112,6 +124,7 @@ func TestFeedOfSubscribeSameChannel(t *testing.T) {
sub2.Unsubscribe() sub2.Unsubscribe()
done.Add(1) done.Add(1)
go expectSends(3, 1) go expectSends(3, 1)
expectRecv(3, 1) expectRecv(3, 1)
done.Wait() done.Wait()
@ -127,10 +140,12 @@ func TestFeedOfSubscribeBlockedPost(t *testing.T) {
ch2 = make(chan int) ch2 = make(chan int)
wg sync.WaitGroup wg sync.WaitGroup
) )
defer wg.Wait() defer wg.Wait()
feed.Subscribe(ch1) feed.Subscribe(ch1)
wg.Add(nsends) wg.Add(nsends)
for i := 0; i < nsends; i++ { for i := 0; i < nsends; i++ {
go func() { go func() {
feed.Send(99) feed.Send(99)
@ -164,12 +179,14 @@ func TestFeedOfUnsubscribeBlockedPost(t *testing.T) {
bsub = feed.Subscribe(bchan) bsub = feed.Subscribe(bchan)
wg sync.WaitGroup wg sync.WaitGroup
) )
for i := range chans { for i := range chans {
chans[i] = make(chan int, nsends) chans[i] = make(chan int, nsends)
} }
// Queue up some Sends. None of these can make progress while bchan isn't read. // Queue up some Sends. None of these can make progress while bchan isn't read.
wg.Add(nsends) wg.Add(nsends)
for i := 0; i < nsends; i++ { for i := 0; i < nsends; i++ {
go func() { go func() {
feed.Send(99) feed.Send(99)
@ -202,9 +219,11 @@ func TestFeedOfUnsubscribeSentChan(t *testing.T) {
sub2 = feed.Subscribe(ch2) sub2 = feed.Subscribe(ch2)
wg sync.WaitGroup wg sync.WaitGroup
) )
defer sub2.Unsubscribe() defer sub2.Unsubscribe()
wg.Add(1) wg.Add(1)
go func() { go func() {
feed.Send(0) feed.Send(0)
wg.Done() 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 // Send again. This should send to ch2 only, so the wait group will unblock
// as soon as a value is received on ch2. // as soon as a value is received on ch2.
wg.Add(1) wg.Add(1)
go func() { go func() {
feed.Send(0) feed.Send(0)
wg.Done() wg.Done()
@ -241,9 +261,11 @@ func TestFeedOfUnsubscribeFromInbox(t *testing.T) {
sub2 = feed.Subscribe(ch1) sub2 = feed.Subscribe(ch1)
sub3 = feed.Subscribe(ch2) sub3 = feed.Subscribe(ch2)
) )
if len(feed.inbox) != 3 { if len(feed.inbox) != 3 {
t.Errorf("inbox length != 3 after subscribe") t.Errorf("inbox length != 3 after subscribe")
} }
if len(feed.sendCases) != 1 { if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe") t.Errorf("sendCases is non-empty after unsubscribe")
} }
@ -251,9 +273,11 @@ func TestFeedOfUnsubscribeFromInbox(t *testing.T) {
sub1.Unsubscribe() sub1.Unsubscribe()
sub2.Unsubscribe() sub2.Unsubscribe()
sub3.Unsubscribe() sub3.Unsubscribe()
if len(feed.inbox) != 0 { if len(feed.inbox) != 0 {
t.Errorf("inbox is non-empty after unsubscribe") t.Errorf("inbox is non-empty after unsubscribe")
} }
if len(feed.sendCases) != 1 { if len(feed.sendCases) != 1 {
t.Errorf("sendCases is non-empty after unsubscribe") t.Errorf("sendCases is non-empty after unsubscribe")
} }
@ -265,21 +289,26 @@ func BenchmarkFeedOfSend1000(b *testing.B) {
feed FeedOf[int] feed FeedOf[int]
nsubs = 1000 nsubs = 1000
) )
subscriber := func(ch <-chan int) { subscriber := func(ch <-chan int) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
<-ch <-ch
} }
done.Done() done.Done()
} }
done.Add(nsubs) done.Add(nsubs)
for i := 0; i < nsubs; i++ { for i := 0; i < nsubs; i++ {
ch := make(chan int, 200) ch := make(chan int, 200)
feed.Subscribe(ch) feed.Subscribe(ch)
go subscriber(ch) go subscriber(ch)
} }
// The actual benchmark. // The actual benchmark.
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
if feed.Send(i) != nsubs { if feed.Send(i) != nsubs {
panic("wrong number of sends") panic("wrong number of sends")

View file

@ -85,6 +85,7 @@ func (g *GoToolchain) goTool(command string, args ...string) *exec.Cmd {
if g.Root == "" { if g.Root == "" {
g.Root = runtime.GOROOT() g.Root = runtime.GOROOT()
} }
tool := exec.Command(filepath.Join(g.Root, "bin", "go"), command) // nolint: gosec tool := exec.Command(filepath.Join(g.Root, "bin", "go"), command) // nolint: gosec
tool.Args = append(tool.Args, args...) tool.Args = append(tool.Args, args...)
tool.Env = append(tool.Env, "GOROOT="+g.Root) tool.Env = append(tool.Env, "GOROOT="+g.Root)

View file

@ -52,15 +52,19 @@ func MustRun(cmd *exec.Cmd) {
func printArgs(args []string) string { func printArgs(args []string) string {
var s strings.Builder var s strings.Builder
for i, arg := range args { for i, arg := range args {
if i > 0 { if i > 0 {
s.WriteByte(' ') s.WriteByte(' ')
} }
if strings.IndexByte(arg, ' ') >= 0 { if strings.IndexByte(arg, ' ') >= 0 {
arg = strconv.QuoteToASCII(arg) arg = strconv.QuoteToASCII(arg)
} }
s.WriteString(arg) s.WriteString(arg)
} }
return s.String() return s.String()
} }
@ -191,6 +195,7 @@ func UploadSFTP(identityFile, host, dir string, files []string) error {
// package paths. // package paths.
func FindMainPackages(dir string) []string { func FindMainPackages(dir string) []string {
var commands []string var commands []string
cmds, err := os.ReadDir(dir) cmds, err := os.ReadDir(dir)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View file

@ -3,8 +3,6 @@ package server
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"io" "io"
"math/big" "math/big"
"net" "net"

View file

@ -25,15 +25,16 @@ import (
"path/filepath" "path/filepath"
"runtime" "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/fjl/memsize/memsizeui"
"github.com/mattn/go-colorable" "github.com/mattn/go-colorable"
"github.com/mattn/go-isatty" "github.com/mattn/go-isatty"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"gopkg.in/natefinch/lumberjack.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 var Memsize memsizeui.Handler

View file

@ -26,8 +26,9 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/ethereum/go-ethereum/common/math"
"github.com/urfave/cli/v2" "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 // DirectoryString is custom type which is registered in the flags library which cli uses for

View file

@ -22,7 +22,6 @@ import (
"github.com/ethereum/go-ethereum/internal/version" "github.com/ethereum/go-ethereum/internal/version"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/urfave/cli/v2"
) )
// NewApp creates an app with sane defaults. // NewApp creates an app with sane defaults.

View file

@ -49,6 +49,7 @@ func newWithTestJS(t *testing.T, testjs string) *JSRE {
} }
} }
jsre := New(dir, os.Stdout) jsre := New(dir, os.Stdout)
return jsre return jsre
} }

View file

@ -45,8 +45,10 @@ func buildInfoVCS(info *debug.BuildInfo) (s VCSInfo, ok bool) {
} }
} }
} }
if s.Commit != "" && s.Date != "" { if s.Commit != "" && s.Date != "" {
ok = true ok = true
} }
return return
} }

View file

@ -45,11 +45,13 @@ func VCS() (VCSInfo, bool) {
// Use information set by the build script if present. // Use information set by the build script if present.
return VCSInfo{Commit: gitCommit, Date: gitDate}, true return VCSInfo{Commit: gitCommit, Date: gitDate}, true
} }
if buildInfo, ok := debug.ReadBuildInfo(); ok { if buildInfo, ok := debug.ReadBuildInfo(); ok {
if buildInfo.Main.Path == ourPath { if buildInfo.Main.Path == ourPath {
return buildInfoVCS(buildInfo) return buildInfoVCS(buildInfo)
} }
} }
return VCSInfo{}, false return VCSInfo{}, false
} }
@ -57,6 +59,7 @@ func VCS() (VCSInfo, bool) {
// conventions in the Ethereum p2p network. // conventions in the Ethereum p2p network.
func ClientName(clientIdentifier string) string { func ClientName(clientIdentifier string) string {
git, _ := VCS() git, _ := VCS()
return fmt.Sprintf("%s/v%v/%v-%v/%v", return fmt.Sprintf("%s/v%v/%v-%v/%v",
//nolint: staticcheck //nolint: staticcheck
strings.Title(clientIdentifier), 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 // 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, // 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 // 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) { func Info() (version, vcs string) {
version = params.VersionWithMeta version = params.VersionWithMeta
buildInfo, ok := debug.ReadBuildInfo() buildInfo, ok := debug.ReadBuildInfo()
if !ok { if !ok {
return version, "" return version, ""
} }
version = versionInfo(buildInfo) version = versionInfo(buildInfo)
if status, ok := VCS(); ok { if status, ok := VCS(); ok {
modified := "" modified := ""
if status.Dirty { if status.Dirty {
modified = " (dirty)" modified = " (dirty)"
} }
commit := status.Commit commit := status.Commit
if len(commit) > 8 { if len(commit) > 8 {
commit = commit[:8] commit = commit[:8]
} }
vcs = commit + "-" + status.Date + modified vcs = commit + "-" + status.Date + modified
} }
return version, vcs return version, vcs
} }
@ -111,7 +120,9 @@ func versionInfo(info *debug.BuildInfo) string {
// These can be empty when invoked with "go run". // These can be empty when invoked with "go run".
version = fmt.Sprintf("%s@%s ", info.Main.Path, info.Main.Version) version = fmt.Sprintf("%s@%s ", info.Main.Path, info.Main.Version)
} }
mod := findModule(info, ourPath) mod := findModule(info, ourPath)
if mod == nil { if mod == nil {
// If our module path wasn't imported, it's unclear which // If our module path wasn't imported, it's unclear which
// version of our code they are running. Fallback to hardcoded // 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. // If our package was replaced by something else, also note that.
version += fmt.Sprintf(" (replaced by %s@%s)", mod.Replace.Path, mod.Replace.Version) version += fmt.Sprintf(" (replaced by %s@%s)", mod.Replace.Path, mod.Replace.Version)
} }
return version return version
} }
@ -133,10 +145,12 @@ func findModule(info *debug.BuildInfo, path string) *debug.Module {
if info.Path == ourPath { if info.Path == ourPath {
return &info.Main return &info.Main
} }
for _, mod := range info.Deps { for _, mod := range info.Deps {
if mod.Path == path { if mod.Path == path {
return mod return mod
} }
} }
return nil return nil
} }

View file

@ -19,7 +19,6 @@ package les
import ( import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/eth/downloader/whitelist"
"strings" "strings"
"time" "time"

View file

@ -354,6 +354,7 @@ func formatLogfmtValue(value interface{}, term bool) string {
if v == nil { if v == nil {
return "<nil>" return "<nil>"
} }
return formatLogfmtUint256(v) return formatLogfmtUint256(v)
} }
if term { if term {
@ -484,12 +485,14 @@ func formatLogfmtUint256(n *uint256.Int) string {
if n.IsUint64() { if n.IsUint64() {
return FormatLogfmtUint64(n.Uint64()) return FormatLogfmtUint64(n.Uint64())
} }
var ( var (
text = n.Dec() text = n.Dec()
buf = make([]byte, len(text)+len(text)/3) buf = make([]byte, len(text)+len(text)/3)
comma = 0 comma = 0
i = len(buf) - 1 i = len(buf) - 1
) )
for j := len(text) - 1; j >= 0; j, i = j-1, i-1 { for j := len(text) - 1; j >= 0; j, i = j-1, i-1 {
c := text[j] c := text[j]
@ -499,13 +502,16 @@ func formatLogfmtUint256(n *uint256.Int) string {
case comma == 3: case comma == 3:
buf[i] = ',' buf[i] = ','
i-- i--
comma = 0 comma = 0
fallthrough fallthrough
default: default:
buf[i] = c buf[i] = c
comma++ comma++
} }
} }
return string(buf[i+1:]) return string(buf[i+1:])
} }
@ -531,6 +537,7 @@ func escapeString(s string) string {
// for spaces and linebreaks to occur without needing quoting. // for spaces and linebreaks to occur without needing quoting.
func escapeMessage(s string) string { func escapeMessage(s string) string {
needsQuoting := false needsQuoting := false
for _, r := range s { for _, r := range s {
// Allow CR/LF/TAB. This is to make multi-line messages work. // Allow CR/LF/TAB. This is to make multi-line messages work.
if r == '\r' || r == '\n' || r == '\t' { if r == '\r' || r == '\n' || r == '\t' {
@ -543,8 +550,10 @@ func escapeMessage(s string) string {
break break
} }
} }
if !needsQuoting { if !needsQuoting {
return s return s
} }
return strconv.Quote(s) return strconv.Quote(s)
} }

View file

@ -96,6 +96,7 @@ func TestPrettyUint256(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
v := new(uint256.Int) v := new(uint256.Int)
v.SetFromDecimal(tt.int) v.SetFromDecimal(tt.int)
if have := formatLogfmtUint256(v); have != tt.s { if have := formatLogfmtUint256(v); have != tt.s {
t.Errorf("invalid output %s, want %s", have, tt.s) t.Errorf("invalid output %s, want %s", have, tt.s)
} }
@ -156,8 +157,10 @@ func TestSanitation(t *testing.T) {
logger = New() logger = New()
out = new(strings.Builder) out = new(strings.Builder)
) )
logger.SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(out, TerminalFormat(false)))) logger.SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(out, TerminalFormat(false))))
logger.Info(tt.msg, tt.msg, tt.msg) logger.Info(tt.msg, tt.msg, tt.msg)
if have := out.String()[24:]; tt.want != have { if have := out.String()[24:]; tt.want != have {
t.Fatalf("test %d: want / have: \n%v\n%v", i, tt.want, have) t.Fatalf("test %d: want / have: \n%v\n%v", i, tt.want, have)
} }

View file

@ -38,6 +38,7 @@ func NewCounter() Counter {
if !Enabled { if !Enabled {
return NilCounter{} return NilCounter{}
} }
return &StandardCounter{} return &StandardCounter{}
} }

View file

@ -20,6 +20,7 @@ func GetOrRegisterCounterFloat64(name string, r Registry) CounterFloat64 {
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
return r.GetOrRegister(name, NewCounterFloat64).(CounterFloat64) return r.GetOrRegister(name, NewCounterFloat64).(CounterFloat64)
} }
@ -31,6 +32,7 @@ func GetOrRegisterCounterFloat64Forced(name string, r Registry) CounterFloat64 {
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
return r.GetOrRegister(name, NewCounterFloat64Forced).(CounterFloat64) return r.GetOrRegister(name, NewCounterFloat64Forced).(CounterFloat64)
} }
@ -39,6 +41,7 @@ func NewCounterFloat64() CounterFloat64 {
if !Enabled { if !Enabled {
return NilCounterFloat64{} return NilCounterFloat64{}
} }
return &StandardCounterFloat64{} return &StandardCounterFloat64{}
} }
@ -51,10 +54,12 @@ func NewCounterFloat64Forced() CounterFloat64 {
// NewRegisteredCounterFloat64 constructs and registers a new StandardCounterFloat64. // NewRegisteredCounterFloat64 constructs and registers a new StandardCounterFloat64.
func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 { func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 {
c := NewCounterFloat64() c := NewCounterFloat64()
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
r.Register(name, c) r.Register(name, c)
return c return c
} }
@ -64,10 +69,12 @@ func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 {
// allow for garbage collection. // allow for garbage collection.
func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 { func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 {
c := NewCounterFloat64Forced() c := NewCounterFloat64Forced()
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
r.Register(name, c) r.Register(name, c)
return c return c
} }
@ -148,6 +155,7 @@ func atomicAddFloat(fbits *atomic.Uint64, v float64) {
for { for {
loadedBits := fbits.Load() loadedBits := fbits.Load()
newBits := math.Float64bits(math.Float64frombits(loadedBits) + v) newBits := math.Float64bits(math.Float64frombits(loadedBits) + v)
if fbits.CompareAndSwap(loadedBits, newBits) { if fbits.CompareAndSwap(loadedBits, newBits) {
break break
} }

View file

@ -7,7 +7,9 @@ import (
func BenchmarkCounterFloat64(b *testing.B) { func BenchmarkCounterFloat64(b *testing.B) {
c := NewCounterFloat64() c := NewCounterFloat64()
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
c.Inc(1.0) c.Inc(1.0)
} }
@ -15,10 +17,14 @@ func BenchmarkCounterFloat64(b *testing.B) {
func BenchmarkCounterFloat64Parallel(b *testing.B) { func BenchmarkCounterFloat64Parallel(b *testing.B) {
c := NewCounterFloat64() c := NewCounterFloat64()
b.ResetTimer() b.ResetTimer()
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
c.Inc(1.0) c.Inc(1.0)
@ -27,6 +33,7 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) {
}() }()
} }
wg.Wait() wg.Wait()
if have, want := c.Count(), 10.0*float64(b.N); have != want { if have, want := c.Count(), 10.0*float64(b.N); have != want {
b.Fatalf("have %f want %f", have, want) b.Fatalf("have %f want %f", have, want)
} }
@ -34,9 +41,11 @@ func BenchmarkCounterFloat64Parallel(b *testing.B) {
func TestCounterFloat64Clear(t *testing.T) { func TestCounterFloat64Clear(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
c.Clear() c.Clear()
if count := c.Count(); count != 0 { if count := c.Count(); count != 0 {
t.Errorf("c.Count(): 0 != %v\n", count) t.Errorf("c.Count(): 0 != %v\n", count)
} }
@ -44,8 +53,10 @@ func TestCounterFloat64Clear(t *testing.T) {
func TestCounterFloat64Dec1(t *testing.T) { func TestCounterFloat64Dec1(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Dec(1.0) c.Dec(1.0)
if count := c.Count(); count != -1.0 { if count := c.Count(); count != -1.0 {
t.Errorf("c.Count(): -1.0 != %v\n", count) t.Errorf("c.Count(): -1.0 != %v\n", count)
} }
@ -53,8 +64,10 @@ func TestCounterFloat64Dec1(t *testing.T) {
func TestCounterFloat64Dec2(t *testing.T) { func TestCounterFloat64Dec2(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Dec(2.0) c.Dec(2.0)
if count := c.Count(); count != -2.0 { if count := c.Count(); count != -2.0 {
t.Errorf("c.Count(): -2.0 != %v\n", count) t.Errorf("c.Count(): -2.0 != %v\n", count)
} }
@ -62,6 +75,7 @@ func TestCounterFloat64Dec2(t *testing.T) {
func TestCounterFloat64Inc1(t *testing.T) { func TestCounterFloat64Inc1(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
if count := c.Count(); count != 1.0 { if count := c.Count(); count != 1.0 {
@ -71,8 +85,10 @@ func TestCounterFloat64Inc1(t *testing.T) {
func TestCounterFloat64Inc2(t *testing.T) { func TestCounterFloat64Inc2(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(2.0) c.Inc(2.0)
if count := c.Count(); count != 2.0 { if count := c.Count(); count != 2.0 {
t.Errorf("c.Count(): 2.0 != %v\n", count) t.Errorf("c.Count(): 2.0 != %v\n", count)
} }
@ -80,10 +96,12 @@ func TestCounterFloat64Inc2(t *testing.T) {
func TestCounterFloat64Snapshot(t *testing.T) { func TestCounterFloat64Snapshot(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
c.Inc(1.0) c.Inc(1.0)
snapshot := c.Snapshot() snapshot := c.Snapshot()
c.Inc(1.0) c.Inc(1.0)
if count := snapshot.Count(); count != 1.0 { if count := snapshot.Count(); count != 1.0 {
t.Errorf("c.Count(): 1.0 != %v\n", count) t.Errorf("c.Count(): 1.0 != %v\n", count)
} }
@ -91,7 +109,9 @@ func TestCounterFloat64Snapshot(t *testing.T) {
func TestCounterFloat64Zero(t *testing.T) { func TestCounterFloat64Zero(t *testing.T) {
t.Parallel() t.Parallel()
c := NewCounterFloat64() c := NewCounterFloat64()
if count := c.Count(); count != 0 { if count := c.Count(); count != 0 {
t.Errorf("c.Count(): 0 != %v\n", count) t.Errorf("c.Count(): 0 != %v\n", count)
} }
@ -99,6 +119,7 @@ func TestCounterFloat64Zero(t *testing.T) {
func TestGetOrRegisterCounterFloat64(t *testing.T) { func TestGetOrRegisterCounterFloat64(t *testing.T) {
t.Parallel() t.Parallel()
r := NewRegistry() r := NewRegistry()
NewRegisteredCounterFloat64("foo", r).Inc(47.0) NewRegisteredCounterFloat64("foo", r).Inc(47.0)
if c := GetOrRegisterCounterFloat64("foo", r); c.Count() != 47.0 { if c := GetOrRegisterCounterFloat64("foo", r); c.Count() != 47.0 {

View file

@ -32,5 +32,6 @@ func getProcessCPUTime() float64 {
log.Warn("Failed to retrieve CPU time", "err", err) log.Warn("Failed to retrieve CPU time", "err", err)
return 0 return 0
} }
return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1000000 //nolint:unconvert return float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1000000 //nolint:unconvert
} }

View file

@ -25,6 +25,7 @@ func NewGauge() Gauge {
if !Enabled { if !Enabled {
return NilGauge{} return NilGauge{}
} }
return &StandardGauge{} return &StandardGauge{}
} }

View file

@ -26,6 +26,7 @@ func NewGaugeFloat64() GaugeFloat64 {
if !Enabled { if !Enabled {
return NilGaugeFloat64{} return NilGaugeFloat64{}
} }
return &StandardGaugeFloat64{} return &StandardGaugeFloat64{}
} }

View file

@ -15,9 +15,12 @@ func BenchmarkGaugeFloat64(b *testing.B) {
func BenchmarkGaugeFloat64Parallel(b *testing.B) { func BenchmarkGaugeFloat64Parallel(b *testing.B) {
c := NewGaugeFloat64() c := NewGaugeFloat64()
var wg sync.WaitGroup var wg sync.WaitGroup
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
wg.Add(1) wg.Add(1)
go func() { go func() {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
c.Update(float64(i)) c.Update(float64(i))
@ -26,6 +29,7 @@ func BenchmarkGaugeFloat64Parallel(b *testing.B) {
}() }()
} }
wg.Wait() wg.Wait()
if have, want := c.Value(), float64(b.N-1); have != want { if have, want := c.Value(), float64(b.N-1); have != want {
b.Fatalf("have %f want %f", have, want) b.Fatalf("have %f want %f", have, want)
} }

View file

@ -13,30 +13,35 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": metric.Count(), "value": metric.Count(),
} }
return measurement, fields return measurement, fields
case metrics.CounterFloat64: case metrics.CounterFloat64:
measurement := fmt.Sprintf("%s%s.count", namespace, name) measurement := fmt.Sprintf("%s%s.count", namespace, name)
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": metric.Count(), "value": metric.Count(),
} }
return measurement, fields return measurement, fields
case metrics.Gauge: case metrics.Gauge:
measurement := fmt.Sprintf("%s%s.gauge", namespace, name) measurement := fmt.Sprintf("%s%s.gauge", namespace, name)
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": metric.Snapshot().Value(), "value": metric.Snapshot().Value(),
} }
return measurement, fields return measurement, fields
case metrics.GaugeFloat64: case metrics.GaugeFloat64:
measurement := fmt.Sprintf("%s%s.gauge", namespace, name) measurement := fmt.Sprintf("%s%s.gauge", namespace, name)
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": metric.Snapshot().Value(), "value": metric.Snapshot().Value(),
} }
return measurement, fields return measurement, fields
case metrics.Histogram: case metrics.Histogram:
ms := metric.Snapshot() ms := metric.Snapshot()
if ms.Count() <= 0 { if ms.Count() <= 0 {
break break
} }
ps := ms.Percentiles([]float64{0.25, 0.5, 0.75, 0.95, 0.99, 0.999, 0.9999}) 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) measurement := fmt.Sprintf("%s%s.histogram", namespace, name)
fields := map[string]interface{}{ fields := map[string]interface{}{
@ -54,6 +59,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf
"p999": ps[5], "p999": ps[5],
"p9999": ps[6], "p9999": ps[6],
} }
return measurement, fields return measurement, fields
case metrics.Meter: case metrics.Meter:
ms := metric.Snapshot() ms := metric.Snapshot()
@ -65,6 +71,7 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf
"m15": ms.Rate15(), "m15": ms.Rate15(),
"mean": ms.RateMean(), "mean": ms.RateMean(),
} }
return measurement, fields return measurement, fields
case metrics.Timer: case metrics.Timer:
ms := metric.Snapshot() ms := metric.Snapshot()
@ -89,12 +96,14 @@ func readMeter(namespace, name string, i interface{}) (string, map[string]interf
"m15": ms.Rate15(), "m15": ms.Rate15(),
"meanrate": ms.RateMean(), "meanrate": ms.RateMean(),
} }
return measurement, fields return measurement, fields
case metrics.ResettingTimer: case metrics.ResettingTimer:
t := metric.Snapshot() t := metric.Snapshot()
if len(t.Values()) == 0 { if len(t.Values()) == 0 {
break break
} }
ps := t.Percentiles([]float64{50, 95, 99}) ps := t.Percentiles([]float64{50, 95, 99})
val := t.Values() val := t.Values()
measurement := fmt.Sprintf("%s%s.span", namespace, name) 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], "p95": ps[1],
"p99": ps[2], "p99": ps[2],
} }
return measurement, fields return measurement, fields
} }
return "", nil return "", nil
} }

Some files were not shown because too many files have changed in this diff Show more