dev: fix: solve more lint issues

This commit is contained in:
marcello33 2023-06-15 14:54:08 +02:00
parent d9a82cd3cd
commit 131d7b221f
127 changed files with 460 additions and 37 deletions

View file

@ -246,7 +246,9 @@ func UnpackRevert(data []byte) (string, error) {
if !bytes.Equal(data[:4], revertSelector) { if !bytes.Equal(data[:4], revertSelector) {
return "", errors.New("invalid data for unpacking") return "", errors.New("invalid data for unpacking")
} }
typ, err := NewType("string", "", nil) typ, err := NewType("string", "", nil)
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -102,6 +102,7 @@ func parseCompositeType(unescapedSelector string) ([]interface{}, string, error)
if len(rest) == 0 || rest[0] != ')' { if len(rest) == 0 || rest[0] != ')' {
return nil, "", fmt.Errorf("expected ')', got '%s'", rest) return nil, "", fmt.Errorf("expected ')', got '%s'", rest)
} }
if len(rest) >= 3 && rest[1] == '[' && rest[2] == ']' { if len(rest) >= 3 && rest[1] == '[' && rest[2] == ']' {
return append(result, "[]"), rest[3:], nil return append(result, "[]"), rest[3:], nil
} }
@ -131,6 +132,7 @@ func assembleArgs(args []interface{}) ([]ArgumentMarshaling, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to assemble components: %v", err) return nil, fmt.Errorf("failed to assemble components: %v", err)
} }
// nolint:goconst
tupleType := "tuple" tupleType := "tuple"
if len(subArgs) != 0 && subArgs[len(subArgs)-1].Type == "[]" { if len(subArgs) != 0 && subArgs[len(subArgs)-1].Type == "[]" {
subArgs = subArgs[:len(subArgs)-1] subArgs = subArgs[:len(subArgs)-1]

View file

@ -174,15 +174,20 @@ func NewType(t string, internalType string, components []ArgumentMarshaling) (ty
if err != nil { if err != nil {
return Type{}, err return Type{}, err
} }
name := ToCamelCase(c.Name) name := ToCamelCase(c.Name)
if name == "" { if name == "" {
return Type{}, errors.New("abi: purely anonymous or underscored field is not supported") return Type{}, errors.New("abi: purely anonymous or underscored field is not supported")
} }
fieldName := ResolveNameConflict(name, func(s string) bool { return used[s] }) fieldName := ResolveNameConflict(name, func(s string) bool { return used[s] })
if err != nil { if err != nil {
return Type{}, err return Type{}, err
} }
used[fieldName] = true used[fieldName] = true
if !isValidFieldName(fieldName) { if !isValidFieldName(fieldName) {
return Type{}, fmt.Errorf("field %d has invalid name", idx) return Type{}, fmt.Errorf("field %d has invalid name", idx)
} }

View file

@ -34,6 +34,7 @@ var (
) )
// ReadInteger reads the integer based on its kind and returns the appropriate value. // ReadInteger reads the integer based on its kind and returns the appropriate value.
// nolint:gocognit
func ReadInteger(typ Type, b []byte) (interface{}, error) { func ReadInteger(typ Type, b []byte) (interface{}, error) {
ret := new(big.Int).SetBytes(b) ret := new(big.Int).SetBytes(b)
@ -44,21 +45,25 @@ func ReadInteger(typ Type, b []byte) (interface{}, error) {
if !isu64 || u64 > math.MaxUint8 { if !isu64 || u64 > math.MaxUint8 {
return nil, errBadUint8 return nil, errBadUint8
} }
return byte(u64), nil return byte(u64), nil
case 16: case 16:
if !isu64 || u64 > math.MaxUint16 { if !isu64 || u64 > math.MaxUint16 {
return nil, errBadUint16 return nil, errBadUint16
} }
return uint16(u64), nil return uint16(u64), nil
case 32: case 32:
if !isu64 || u64 > math.MaxUint32 { if !isu64 || u64 > math.MaxUint32 {
return nil, errBadUint32 return nil, errBadUint32
} }
return uint32(u64), nil return uint32(u64), nil
case 64: case 64:
if !isu64 { if !isu64 {
return nil, errBadUint64 return nil, errBadUint64
} }
return u64, nil return u64, nil
default: default:
// the only case left for unsigned integer is uint256. // the only case left for unsigned integer is uint256.
@ -74,27 +79,32 @@ func ReadInteger(typ Type, b []byte) (interface{}, error) {
ret.Add(ret, common.Big1) ret.Add(ret, common.Big1)
ret.Neg(ret) ret.Neg(ret)
} }
i64, isi64 := ret.Int64(), ret.IsInt64() i64, isi64 := ret.Int64(), ret.IsInt64()
switch typ.Size { switch typ.Size {
case 8: case 8:
if !isi64 || i64 < math.MinInt8 || i64 > math.MaxInt8 { if !isi64 || i64 < math.MinInt8 || i64 > math.MaxInt8 {
return nil, errBadInt8 return nil, errBadInt8
} }
return int8(i64), nil return int8(i64), nil
case 16: case 16:
if !isi64 || i64 < math.MinInt16 || i64 > math.MaxInt16 { if !isi64 || i64 < math.MinInt16 || i64 > math.MaxInt16 {
return nil, errBadInt16 return nil, errBadInt16
} }
return int16(i64), nil return int16(i64), nil
case 32: case 32:
if !isi64 || i64 < math.MinInt32 || i64 > math.MaxInt32 { if !isi64 || i64 < math.MinInt32 || i64 > math.MaxInt32 {
return nil, errBadInt32 return nil, errBadInt32
} }
return int32(i64), nil return int32(i64), nil
case 64: case 64:
if !isi64 { if !isi64 {
return nil, errBadInt64 return nil, errBadInt64
} }
return i64, nil return i64, nil
default: default:
// the only case left for integer is int256 // the only case left for integer is int256

View file

@ -430,6 +430,7 @@ func TestMultiReturnWithStringArray(t *testing.T) {
} }
buff := new(bytes.Buffer) buff := new(bytes.Buffer)
buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000005c1b78ea0000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000001a055690d9db80000000000000000000000000000ab1257528b3782fb40d7ed5f72e624b744dffb2f00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000008457468657265756d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001048656c6c6f2c20457468657265756d2100000000000000000000000000000000")) buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000005c1b78ea0000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000001a055690d9db80000000000000000000000000000ab1257528b3782fb40d7ed5f72e624b744dffb2f00000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000008457468657265756d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001048656c6c6f2c20457468657265756d2100000000000000000000000000000000"))
temp, _ := new(big.Int).SetString("30000000000000000000", 10) temp, _ := new(big.Int).SetString("30000000000000000000", 10)
ret1, ret1Exp := new([3]*big.Int), [3]*big.Int{big.NewInt(1545304298), big.NewInt(6), temp} ret1, ret1Exp := new([3]*big.Int), [3]*big.Int{big.NewInt(1545304298), big.NewInt(6), temp}
ret2, ret2Exp := new(common.Address), common.HexToAddress("ab1257528b3782fb40d7ed5f72e624b744dffb2f") ret2, ret2Exp := new(common.Address), common.HexToAddress("ab1257528b3782fb40d7ed5f72e624b744dffb2f")
@ -949,10 +950,13 @@ func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
t.Parallel() t.Parallel()
var encodeABI Arguments var encodeABI Arguments
uint256Ty, err := NewType("uint256", "", nil) uint256Ty, err := NewType("uint256", "", nil)
if err != nil { if err != nil {
panic(err) panic(err)
} }
encodeABI = Arguments{ encodeABI = Arguments{
{Type: uint256Ty}, {Type: uint256Ty},
} }
@ -961,6 +965,7 @@ func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
if !ok { if !ok {
panic("bug") panic("bug")
} }
maxU64Plus1 := new(big.Int).Add(maxU64, big.NewInt(1)) maxU64Plus1 := new(big.Int).Add(maxU64, big.NewInt(1))
cases := []struct { cases := []struct {
decodeType string decodeType string
@ -1083,25 +1088,32 @@ func TestPackAndUnpackIncompatibleNumber(t *testing.T) {
expectValue: int64(math.MaxInt64), expectValue: int64(math.MaxInt64),
}, },
} }
for i, testCase := range cases { for i, testCase := range cases {
packed, err := encodeABI.Pack(testCase.inputValue) packed, err := encodeABI.Pack(testCase.inputValue)
if err != nil { if err != nil {
panic(err) panic(err)
} }
ty, err := NewType(testCase.decodeType, "", nil) ty, err := NewType(testCase.decodeType, "", nil)
if err != nil { if err != nil {
panic(err) panic(err)
} }
decodeABI := Arguments{ decodeABI := Arguments{
{Type: ty}, {Type: ty},
} }
decoded, err := decodeABI.Unpack(packed) decoded, err := decodeABI.Unpack(packed)
if err != testCase.err { if err != testCase.err {
t.Fatalf("Expected error %v, actual error %v. case %d", testCase.err, err, i) t.Fatalf("Expected error %v, actual error %v. case %d", testCase.err, err, i)
} }
if err != nil { if err != nil {
continue continue
} }
if !reflect.DeepEqual(decoded[0], testCase.expectValue) { if !reflect.DeepEqual(decoded[0], testCase.expectValue) {
t.Fatalf("Expected value %v, actual value %v", testCase.expectValue, decoded[0]) t.Fatalf("Expected value %v, actual value %v", testCase.expectValue, decoded[0])
} }

View file

@ -32,9 +32,11 @@ import "fmt"
func ResolveNameConflict(rawName string, used func(string) bool) string { func ResolveNameConflict(rawName string, used func(string) bool) string {
name := rawName name := rawName
ok := used(name) ok := used(name)
for idx := 0; ok; idx++ { for idx := 0; ok; idx++ {
name = fmt.Sprintf("%s%d", rawName, idx) name = fmt.Sprintf("%s%d", rawName, idx)
ok = used(name) ok = used(name)
} }
return name return name
} }

View file

@ -22,7 +22,6 @@ package keystore
import ( import (
"time" "time"
"github.com/ethereum/go-ethereum/log"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"

View file

@ -196,9 +196,11 @@ func (w *trezorDriver) trezorDerive(derivationPath []uint32) (common.Address, er
if _, err := w.trezorExchange(&trezor.EthereumGetAddress{AddressN: derivationPath}, address); err != nil { if _, err := w.trezorExchange(&trezor.EthereumGetAddress{AddressN: derivationPath}, address); err != nil {
return common.Address{}, err return common.Address{}, err
} }
if addr := address.GetAddressBin(); len(addr) > 0 { // Older firmwares use binary formats if addr := address.GetAddressBin(); len(addr) > 0 { // Older firmwares use binary formats
return common.BytesToAddress(addr), nil return common.BytesToAddress(addr), nil
} }
if addr := address.GetAddressHex(); len(addr) > 0 { // Newer firmwares use hexadecimal formats if addr := address.GetAddressHex(); len(addr) > 0 { // Newer firmwares use hexadecimal formats
return common.HexToAddress(addr), nil return common.HexToAddress(addr), nil
} }

View file

@ -24,6 +24,8 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/common/compiler" "github.com/ethereum/go-ethereum/common/compiler"

View file

@ -25,6 +25,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"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"

View file

@ -22,6 +22,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"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"

View file

@ -19,7 +19,6 @@ package main
import ( import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"

View file

@ -23,6 +23,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test" "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/v5test" "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v5test"
"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"

View file

@ -21,6 +21,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/urfave/cli/v2"
"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"

View file

@ -25,6 +25,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/credentials"

View file

@ -24,6 +24,8 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/console/prompt" "github.com/ethereum/go-ethereum/console/prompt"

View file

@ -27,6 +27,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/urfave/cli/v2"
"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"

View file

@ -96,6 +96,7 @@ func (c *Chain) Head() *types.Block {
return c.blocks[c.Len()-1] return c.blocks[c.Len()-1]
} }
// nolint:typecheck
func (c *Chain) GetHeaders(req *GetBlockHeaders) ([]*types.Header, error) { func (c *Chain) GetHeaders(req *GetBlockHeaders) ([]*types.Header, error) {
if req.Amount < 1 { if req.Amount < 1 {
return nil, fmt.Errorf("no block headers requested") return nil, fmt.Errorf("no block headers requested")

View file

@ -571,6 +571,7 @@ func (s *Suite) maliciousStatus(conn *Conn) error {
} }
} }
// nolint:typecheck
func (s *Suite) hashAnnounce() error { func (s *Suite) hashAnnounce() error {
// create connections // create connections
sendConn, recvConn, err := s.createSendAndRecvConns() sendConn, recvConn, err := s.createSendAndRecvConns()

View file

@ -136,6 +136,7 @@ func (s *Suite) TestGetBlockHeaders(t *utesting.T) {
// TestSimultaneousRequests sends two simultaneous `GetBlockHeader` requests from // TestSimultaneousRequests sends two simultaneous `GetBlockHeader` requests from
// the same connection with different request IDs and checks to make sure the node // the same connection with different request IDs and checks to make sure the node
// responds with the correct headers per request. // responds with the correct headers per request.
// nolint:typecheck
func (s *Suite) TestSimultaneousRequests(t *utesting.T) { func (s *Suite) TestSimultaneousRequests(t *utesting.T) {
// create a connection // create a connection
conn, err := s.dial() conn, err := s.dial()
@ -214,6 +215,7 @@ func (s *Suite) TestSimultaneousRequests(t *utesting.T) {
// TestSameRequestID sends two requests with the same request ID to a // TestSameRequestID sends two requests with the same request ID to a
// single node. // single node.
// nolint:typecheck
func (s *Suite) TestSameRequestID(t *utesting.T) { func (s *Suite) TestSameRequestID(t *utesting.T) {
conn, err := s.dial() conn, err := s.dial()
if err != nil { if err != nil {
@ -462,6 +464,7 @@ func (s *Suite) TestMaliciousTx(t *utesting.T) {
// TestLargeTxRequest tests whether a node can fulfill a large GetPooledTransactions // TestLargeTxRequest tests whether a node can fulfill a large GetPooledTransactions
// request. // request.
// nolint:typecheck
func (s *Suite) TestLargeTxRequest(t *utesting.T) { func (s *Suite) TestLargeTxRequest(t *utesting.T) {
// send the next block to ensure the node is no longer syncing and // send the next block to ensure the node is no longer syncing and
// is able to accept txs // is able to accept txs

View file

@ -55,6 +55,7 @@ func (s *Suite) sendSuccessfulTxs(t *utesting.T) error {
return nil return nil
} }
// nolint:typecheck
func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction) error { func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction) error {
sendConn, recvConn, err := s.createSendAndRecvConns() sendConn, recvConn, err := s.createSendAndRecvConns()
if err != nil { if err != nil {
@ -269,6 +270,7 @@ func sendMultipleSuccessfulTxs(t *utesting.T, s *Suite, txs []*types.Transaction
// checkMaliciousTxPropagation checks whether the given malicious transactions were // checkMaliciousTxPropagation checks whether the given malicious transactions were
// propagated by the node. // propagated by the node.
// nolint:typecheck
func checkMaliciousTxPropagation(s *Suite, txs []*types.Transaction, conn *Conn) error { func checkMaliciousTxPropagation(s *Suite, txs []*types.Transaction, conn *Conn) error {
switch msg := conn.readAndServe(s.chain, time.Second*8).(type) { switch msg := conn.readAndServe(s.chain, time.Second*8).(type) {
case *Transactions: case *Transactions:

View file

@ -176,6 +176,7 @@ func (tc *conn) findnode(c net.PacketConn, dists []uint) ([]*enode.Node, error)
if resp.RespCount == 0 || resp.RespCount > 6 { if resp.RespCount == 0 || resp.RespCount > 6 {
return nil, fmt.Errorf("invalid NODES response count %d (not in (0,7))", resp.RespCount) return nil, fmt.Errorf("invalid NODES response count %d (not in (0,7))", resp.RespCount)
} }
total = resp.RespCount total = resp.RespCount
n = int(total) - 1 n = int(total) - 1
first = false first = false

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/urfave/cli/v2"
"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"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"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"

View file

@ -25,6 +25,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/core/forkid" "github.com/ethereum/go-ethereum/core/forkid"
"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"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"net" "net"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/devp2p/internal/ethtest" "github.com/ethereum/go-ethereum/cmd/devp2p/internal/ethtest"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"

View file

@ -19,6 +19,8 @@ package main
import ( import (
"os" "os"
"github.com/urfave/cli/v2"
"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"

View file

@ -21,6 +21,8 @@ import (
"os" "os"
"strings" "strings"
"github.com/urfave/cli/v2"
"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"
) )

View file

@ -21,6 +21,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"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"

View file

@ -20,7 +20,6 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/ethereum/go-ethereum/internal/flags"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/internal/flags" "github.com/ethereum/go-ethereum/internal/flags"

View file

@ -21,6 +21,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"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"

View file

@ -22,7 +22,6 @@ import (
"os" "os"
"strings" "strings"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"

View file

@ -22,7 +22,6 @@ import (
"os" "os"
"strings" "strings"
"github.com/ethereum/go-ethereum/core/asm"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/core/asm" "github.com/ethereum/go-ethereum/core/asm"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/urfave/cli/v2"
"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"
) )

View file

@ -22,6 +22,8 @@ import (
"math/big" "math/big"
"os" "os"
"github.com/urfave/cli/v2"
"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"
) )

View file

@ -28,6 +28,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/evm/internal/compiler" "github.com/ethereum/go-ethereum/cmd/evm/internal/compiler"
"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"

View file

@ -22,6 +22,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"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"

View file

@ -26,6 +26,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"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/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"

View file

@ -22,9 +22,12 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/urfave/cli/v2"
"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/ethereum/go-ethereum/node"
) )
var ( var (

View file

@ -23,6 +23,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"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"

View file

@ -23,6 +23,8 @@ import (
"os" "os"
"time" "time"
"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"

View file

@ -26,7 +26,6 @@ import (
"regexp" "regexp"
"strings" "strings"
"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"

View file

@ -44,6 +44,8 @@ import (
"strings" "strings"
"text/tabwriter" "text/tabwriter"
"github.com/urfave/cli/v2"
"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/p2p" "github.com/ethereum/go-ethereum/p2p"

View file

@ -83,6 +83,7 @@ func main() {
if err != nil { if err != nil {
die(err) die(err)
} }
fmt.Printf("%#x\n", data) fmt.Printf("%#x\n", data)
return return
} else { } else {

View file

@ -43,6 +43,7 @@ func TestRoundtrip(t *testing.T) {
t.Errorf("test %d: error %v", i, err) t.Errorf("test %d: error %v", i, err)
continue continue
} }
have := fmt.Sprintf("%#x", rlpBytes) have := fmt.Sprintf("%#x", rlpBytes)
if have != want { if have != want {
t.Errorf("test %d: have\n%v\nwant:\n%v\n", i, have, want) t.Errorf("test %d: have\n%v\nwant:\n%v\n", i, have, want)

View file

@ -4,6 +4,9 @@ import (
"encoding/json" "encoding/json"
"os" "os"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"

View file

@ -34,6 +34,10 @@ import (
"strings" "strings"
"time" "time"
pcsclite "github.com/gballet/go-libpcsclite"
gopsutil "github.com/shirou/gopsutil/mem"
"github.com/urfave/cli/v2"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@ -74,6 +78,7 @@ 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"
"github.com/ethereum/go-ethereum/trie"
) )
// These are all the command line flags we support. // These are all the command line flags we support.

View file

@ -20,7 +20,6 @@ import (
"container/heap" "container/heap"
"time" "time"
"github.com/ethereum/go-ethereum/common/mclock"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/common/mclock"

View file

@ -179,6 +179,7 @@ func TestMixedcaseAddressMarshal(t *testing.T) {
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 {

View file

@ -102,6 +102,7 @@ func errOut(n int, err error) chan error {
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
errs <- err errs <- err
} }
return errs return errs
} }
@ -116,7 +117,9 @@ func (beacon *Beacon) splitHeaders(chain consensus.ChainHeaderReader, headers []
if ttd == nil { if ttd == nil {
return headers, nil, nil return headers, nil, nil
} }
ptd := chain.GetTd(headers[0].ParentHash, headers[0].Number.Uint64()-1) ptd := chain.GetTd(headers[0].ParentHash, headers[0].Number.Uint64()-1)
if ptd == nil { if ptd == nil {
return nil, nil, consensus.ErrUnknownAncestor return nil, nil, consensus.ErrUnknownAncestor
} }
@ -130,19 +133,23 @@ func (beacon *Beacon) splitHeaders(chain consensus.ChainHeaderReader, headers []
td = new(big.Int).Set(ptd) td = new(big.Int).Set(ptd)
tdPassed bool tdPassed bool
) )
for i, header := range headers { for i, header := range headers {
if tdPassed { if tdPassed {
preHeaders = headers[:i] preHeaders = headers[:i]
postHeaders = headers[i:] postHeaders = headers[i:]
break break
} }
td = td.Add(td, header.Difficulty) td = td.Add(td, header.Difficulty)
if td.Cmp(ttd) >= 0 { if td.Cmp(ttd) >= 0 {
// This is the last PoW header, it still belongs to // This is the last PoW header, it still belongs to
// the preHeaders, so we cannot split+break yet. // the preHeaders, so we cannot split+break yet.
tdPassed = true tdPassed = true
} }
} }
return preHeaders, postHeaders, nil return preHeaders, postHeaders, nil
} }
@ -155,6 +162,7 @@ func (beacon *Beacon) VerifyHeaders(chain consensus.ChainHeaderReader, headers [
if err != nil { if err != nil {
return make(chan struct{}), errOut(len(headers), err) return make(chan struct{}), errOut(len(headers), err)
} }
if len(postHeaders) == 0 { if len(postHeaders) == 0 {
return beacon.ethone.VerifyHeaders(chain, headers, seals) return beacon.ethone.VerifyHeaders(chain, headers, seals)
} }
@ -267,6 +275,7 @@ func (beacon *Beacon) verifyHeader(chain consensus.ChainHeaderReader, header, pa
if shanghai && header.WithdrawalsHash == nil { if shanghai && header.WithdrawalsHash == nil {
return errors.New("missing withdrawalsHash") return errors.New("missing withdrawalsHash")
} }
if !shanghai && header.WithdrawalsHash != nil { if !shanghai && header.WithdrawalsHash != nil {
return fmt.Errorf("invalid withdrawalsHash: have %x, expected nil", header.WithdrawalsHash) return fmt.Errorf("invalid withdrawalsHash: have %x, expected nil", header.WithdrawalsHash)
} }
@ -275,9 +284,11 @@ func (beacon *Beacon) verifyHeader(chain consensus.ChainHeaderReader, header, pa
if cancun && header.ExcessDataGas == nil { if cancun && header.ExcessDataGas == nil {
return errors.New("missing excessDataGas") return errors.New("missing excessDataGas")
} }
if !cancun && header.ExcessDataGas != nil { if !cancun && header.ExcessDataGas != nil {
return fmt.Errorf("invalid excessDataGas: have %d, expected nil", header.ExcessDataGas) return fmt.Errorf("invalid excessDataGas: have %d, expected nil", header.ExcessDataGas)
} }
return nil return nil
} }
@ -455,6 +466,7 @@ func IsTTDReached(chain consensus.ChainHeaderReader, parentHash common.Hash, par
if chain.Config().TerminalTotalDifficulty == nil { if chain.Config().TerminalTotalDifficulty == nil {
return false, nil return false, nil
} }
td := chain.GetTd(parentHash, parentNumber) td := chain.GetTd(parentHash, parentNumber)
if td == nil { if td == nil {
return false, consensus.ErrUnknownAncestor return false, consensus.ErrUnknownAncestor

View file

@ -37,7 +37,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/trie" "github.com/ethereum/go-ethereum/trie"
"golang.org/x/crypto/sha3"
) )
// Ethash proof-of-work protocol constants. // Ethash proof-of-work protocol constants.
@ -317,6 +316,7 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainHeaderReader, header, pa
if chain.Config().IsShanghai(header.Time) { if chain.Config().IsShanghai(header.Time) {
return fmt.Errorf("ethash does not support shanghai fork") return fmt.Errorf("ethash does not support shanghai fork")
} }
if chain.Config().IsCancun(header.Time) { if chain.Config().IsCancun(header.Time) {
return fmt.Errorf("ethash does not support cancun fork") return fmt.Errorf("ethash does not support cancun fork")
} }
@ -646,6 +646,7 @@ func (ethash *Ethash) SealHash(header *types.Header) (hash common.Hash) {
if header.BaseFee != nil { if header.BaseFee != nil {
enc = append(enc, header.BaseFee) enc = append(enc, header.BaseFee)
} }
if header.WithdrawalsHash != nil { if header.WithdrawalsHash != nil {
panic("withdrawal hash set on ethash") panic("withdrawal hash set on ethash")
} }

View file

@ -103,6 +103,7 @@ func TestDifficultyCalculators(t *testing.T) {
for i := 0; i < 5000; i++ { for i := 0; i < 5000; i++ {
// 1 to 300 seconds diff // 1 to 300 seconds diff
var timeDelta = uint64(1 + rand.Uint32()%3000) var timeDelta = uint64(1 + rand.Uint32()%3000)
diffBig := new(big.Int).SetBytes(randSlice(2, 10)) diffBig := new(big.Int).SetBytes(randSlice(2, 10))
if diffBig.Cmp(params.MinimumDifficulty) < 0 { if diffBig.Cmp(params.MinimumDifficulty) < 0 {
diffBig.Set(params.MinimumDifficulty) diffBig.Set(params.MinimumDifficulty)

View file

@ -193,6 +193,7 @@ func newlru[T cacheOrDataset](maxItems int, newLru func(epoch uint64) T) *lru[T]
default: default:
panic("unknown type") panic("unknown type")
} }
return &lru[T]{ return &lru[T]{
what: what, what: what,
new: newLru, new: newLru,
@ -610,6 +611,7 @@ func (ethash *Ethash) dataset(block uint64, async bool) *dataset {
if async && !current.generated() { if async && !current.generated() {
go func() { go func() {
current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
if future != nil { if future != nil {
future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest) future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.DatasetsLockMmap, ethash.config.PowMode == ModeTest)
} }

View file

@ -33,6 +33,7 @@ func CalcBlobFee(excessDataGas *big.Int) *big.Int {
if excessDataGas == nil { if excessDataGas == nil {
return big.NewInt(params.BlobTxMinDataGasprice) return big.NewInt(params.BlobTxMinDataGasprice)
} }
return fakeExponential(minDataGasPrice, excessDataGas, dataGaspriceUpdateFraction) return fakeExponential(minDataGasPrice, excessDataGas, dataGaspriceUpdateFraction)
} }
@ -43,6 +44,7 @@ func fakeExponential(factor, numerator, denominator *big.Int) *big.Int {
output = new(big.Int) output = new(big.Int)
accum = new(big.Int).Mul(factor, denominator) accum = new(big.Int).Mul(factor, denominator)
) )
for i := 1; accum.Sign() > 0; i++ { for i := 1; accum.Sign() > 0; i++ {
output.Add(output, accum) output.Add(output, accum)
@ -50,5 +52,6 @@ func fakeExponential(factor, numerator, denominator *big.Int) *big.Int {
accum.Div(accum, denominator) accum.Div(accum, denominator)
accum.Div(accum, big.NewInt(int64(i))) accum.Div(accum, big.NewInt(int64(i)))
} }
return output.Div(output, denominator) return output.Div(output, denominator)
} }

View file

@ -37,9 +37,11 @@ func TestCalcBlobFee(t *testing.T) {
{10 * 1024 * 1024, 111}, {10 * 1024 * 1024, 111},
} }
have := CalcBlobFee(nil) have := CalcBlobFee(nil)
if have.Int64() != params.BlobTxMinDataGasprice { if have.Int64() != params.BlobTxMinDataGasprice {
t.Errorf("nil test: blobfee mismatch: have %v, want %v", have, params.BlobTxMinDataGasprice) t.Errorf("nil test: blobfee mismatch: have %v, want %v", have, params.BlobTxMinDataGasprice)
} }
for i, tt := range tests { for i, tt := range tests {
have := CalcBlobFee(big.NewInt(tt.excessDataGas)) have := CalcBlobFee(big.NewInt(tt.excessDataGas))
if have.Int64() != tt.blobfee { if have.Int64() != tt.blobfee {
@ -78,10 +80,13 @@ func TestFakeExponential(t *testing.T) {
f, n, d := big.NewInt(tt.factor), big.NewInt(tt.numerator), big.NewInt(tt.denominator) f, n, d := big.NewInt(tt.factor), big.NewInt(tt.numerator), big.NewInt(tt.denominator)
original := fmt.Sprintf("%d %d %d", f, n, d) original := fmt.Sprintf("%d %d %d", f, n, d)
have := fakeExponential(f, n, d) have := fakeExponential(f, n, d)
if have.Int64() != tt.want { if have.Int64() != tt.want {
t.Errorf("test %d: fake exponential mismatch: have %v want %v", i, have, tt.want) t.Errorf("test %d: fake exponential mismatch: have %v want %v", i, have, tt.want)
} }
later := fmt.Sprintf("%d %d %d", f, n, d) later := fmt.Sprintf("%d %d %d", f, n, d)
if original != later { if original != later {
t.Errorf("test %d: fake exponential modified arguments: have\n%v\nwant\n%v", i, later, original) t.Errorf("test %d: fake exponential modified arguments: have\n%v\nwant\n%v", i, later, original)
} }

View file

@ -114,6 +114,7 @@ func (c *Compiler) Compile() (string, []error) {
bin.WriteString(fmt.Sprintf("%x", v)) bin.WriteString(fmt.Sprintf("%x", v))
} }
} }
return bin.String(), errors return bin.String(), errors
} }

View file

@ -57,6 +57,7 @@ import (
"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/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie" "github.com/ethereum/go-ethereum/trie"
) )

View file

@ -79,7 +79,7 @@ func BenchmarkGenerator(b *testing.B) {
} }
}) })
for i := 0; i < types.BloomBitLength; i++ { for i := 0; i < types.BloomBitLength; i++ {
crand.Read(input[i][:]) _, _ = crand.Read(input[i][:])
} }
b.Run("random", func(b *testing.B) { b.Run("random", func(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()

View file

@ -211,6 +211,7 @@ func testMatcher(t *testing.T, filter [][]bloomIndexes, start, blocks uint64, in
if retrievals != 0 && requested.Load() != retrievals { if retrievals != 0 && requested.Load() != retrievals {
t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, have #%v, want #%v", filter, blocks, intermittent, requested.Load(), retrievals) t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, have #%v, want #%v", filter, blocks, intermittent, requested.Load(), retrievals)
} }
return requested.Load() return requested.Load()
} }
@ -238,6 +239,7 @@ func startRetrievers(session *MatcherSession, quit chan struct{}, retrievals *at
for i, section := range task.Sections { for i, section := range task.Sections {
if rand.Int()%4 != 0 { // Handle occasional missing deliveries if rand.Int()%4 != 0 { // Handle occasional missing deliveries
task.Bitsets[i] = generateBitset(task.Bit, section) task.Bitsets[i] = generateBitset(task.Bit, section)
retrievals.Add(1) retrievals.Add(1)
} }
} }

View file

@ -9,6 +9,7 @@ import (
"github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie"
) )
// chainValidatorFake is a mock for the chain validator service // chainValidatorFake is a mock for the chain validator service

View file

@ -85,16 +85,20 @@ func NewID(config *params.ChainConfig, genesis common.Hash, head, time uint64) I
hash = checksumUpdate(hash, fork) hash = checksumUpdate(hash, fork)
continue continue
} }
return ID{Hash: checksumToBytes(hash), Next: fork} return ID{Hash: checksumToBytes(hash), Next: fork}
} }
for _, fork := range forksByTime { for _, fork := range forksByTime {
if fork <= time { if fork <= time {
// Fork already passed, checksum the previous hash and fork timestamp // Fork already passed, checksum the previous hash and fork timestamp
hash = checksumUpdate(hash, fork) hash = checksumUpdate(hash, fork)
continue continue
} }
return ID{Hash: checksumToBytes(hash), Next: fork} return ID{Hash: checksumToBytes(hash), Next: fork}
} }
return ID{Hash: checksumToBytes(hash), Next: 0} return ID{Hash: checksumToBytes(hash), Next: 0}
} }
@ -132,6 +136,7 @@ func NewStaticFilter(config *params.ChainConfig, genesis common.Hash) Filter {
// newFilter is the internal version of NewFilter, taking closures as its arguments // newFilter is the internal version of NewFilter, taking closures as its arguments
// instead of a chain. The reason is to allow testing it without having to simulate // instead of a chain. The reason is to allow testing it without having to simulate
// an entire blockchain. // an entire blockchain.
// nolint:gocognit
func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() (uint64, uint64)) Filter { func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() (uint64, uint64)) Filter {
// Calculate the all the valid fork hash and fork next combos // Calculate the all the valid fork hash and fork next combos
var ( var (
@ -148,6 +153,7 @@ func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() (u
// Add two sentries to simplify the fork checks and don't require special // Add two sentries to simplify the fork checks and don't require special
// casing the last one. // casing the last one.
forks = append(forks, math.MaxUint64) // Last fork will never be passed forks = append(forks, math.MaxUint64) // Last fork will never be passed
if len(forksByTime) == 0 { if len(forksByTime) == 0 {
// In purely block based forks, avoid the sentry spilling into timestapt territory // In purely block based forks, avoid the sentry spilling into timestapt territory
forksByBlock = append(forksByBlock, math.MaxUint64) // Last fork will never be passed forksByBlock = append(forksByBlock, math.MaxUint64) // Last fork will never be passed
@ -245,6 +251,7 @@ func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) {
kind := reflect.TypeOf(params.ChainConfig{}) kind := reflect.TypeOf(params.ChainConfig{})
conf := reflect.ValueOf(config).Elem() conf := reflect.ValueOf(config).Elem()
x := uint64(0) x := uint64(0)
var ( var (
forksByBlock []uint64 forksByBlock []uint64
forksByTime []uint64 forksByTime []uint64
@ -264,6 +271,7 @@ func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) {
forksByTime = append(forksByTime, *rule) forksByTime = append(forksByTime, *rule)
} }
} }
if field.Type == reflect.TypeOf(new(big.Int)) { if field.Type == reflect.TypeOf(new(big.Int)) {
if rule := conf.Field(i).Interface().(*big.Int); rule != nil { if rule := conf.Field(i).Interface().(*big.Int); rule != nil {
forksByBlock = append(forksByBlock, rule.Uint64()) forksByBlock = append(forksByBlock, rule.Uint64())
@ -280,6 +288,7 @@ func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) {
i-- i--
} }
} }
for i := 1; i < len(forksByTime); i++ { for i := 1; i < len(forksByTime); i++ {
if forksByTime[i] == forksByTime[i-1] { if forksByTime[i] == forksByTime[i-1] {
forksByTime = append(forksByTime[:i], forksByTime[i+1:]...) forksByTime = append(forksByTime[:i], forksByTime[i+1:]...)
@ -290,8 +299,10 @@ func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) {
if len(forksByBlock) > 0 && forksByBlock[0] == 0 { if len(forksByBlock) > 0 && forksByBlock[0] == 0 {
forksByBlock = forksByBlock[1:] forksByBlock = forksByBlock[1:]
} }
if len(forksByTime) > 0 && forksByTime[0] == 0 { if len(forksByTime) > 0 && forksByTime[0] == 0 {
forksByTime = forksByTime[1:] forksByTime = forksByTime[1:]
} }
return forksByBlock, forksByTime return forksByBlock, forksByTime
} }

View file

@ -26,6 +26,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/gofrs/flock"
"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"

View file

@ -45,12 +45,15 @@ func TestNodeIteratorCoverage(t *testing.T) {
seenNodes = make(map[common.Hash]struct{}) seenNodes = make(map[common.Hash]struct{})
seenCodes = make(map[common.Hash]struct{}) seenCodes = make(map[common.Hash]struct{})
) )
it := db.NewIterator(nil, nil) it := db.NewIterator(nil, nil)
for it.Next() { for it.Next() {
ok, hash := isTrieNode(sdb.TrieDB().Scheme(), it.Key(), it.Value()) ok, hash := isTrieNode(sdb.TrieDB().Scheme(), it.Key(), it.Value())
if !ok { if !ok {
continue continue
} }
seenNodes[hash] = struct{}{} seenNodes[hash] = struct{}{}
} }
it.Release() it.Release()
@ -62,19 +65,22 @@ func TestNodeIteratorCoverage(t *testing.T) {
if !ok { if !ok {
continue continue
} }
if _, ok := hashes[common.BytesToHash(hash)]; !ok { if _, ok := hashes[common.BytesToHash(hash)]; !ok {
t.Errorf("state entry not reported %x", it.Key()) t.Errorf("state entry not reported %x", it.Key())
} }
seenCodes[common.BytesToHash(hash)] = struct{}{} seenCodes[common.BytesToHash(hash)] = struct{}{}
} }
it.Release() it.Release()
// Cross check the iterated hashes and the database/nodepool content // Cross-check the iterated hashes and the database/nodepool content
for hash := range hashes { for hash := range hashes {
_, ok := seenNodes[hash] _, ok := seenNodes[hash]
if !ok { if !ok {
_, ok = seenCodes[hash] _, ok = seenCodes[hash]
} }
if !ok { if !ok {
t.Errorf("failed to retrieve reported node %x", hash) t.Errorf("failed to retrieve reported node %x", hash)
} }
@ -89,5 +95,6 @@ func isTrieNode(scheme string, key, val []byte) (bool, common.Hash) {
return true, common.BytesToHash(key) return true, common.BytesToHash(key)
} }
} }
return false, common.Hash{} return false, common.Hash{}
} }

View file

@ -833,6 +833,7 @@ func (s *StateDB) SetTransientState(addr common.Address, key, value common.Hash)
if prev == value { if prev == value {
return return
} }
s.journal.append(transientStorageChange{ s.journal.append(transientStorageChange{
account: &addr, account: &addr,
key: key, key: key,
@ -1044,10 +1045,13 @@ func (s *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.
if so == nil { if so == nil {
return nil return nil
} }
tr, err := so.getTrie(s.db) tr, err := so.getTrie(s.db)
if err != nil { if err != nil {
return err return err
} }
it := trie.NewIterator(tr.NodeIterator(nil)) it := trie.NewIterator(tr.NodeIterator(nil))
for it.Next() { for it.Next() {
@ -1337,6 +1341,7 @@ func (s *StateDB) clearJournalAndRefund() {
s.journal = newJournal() s.journal = newJournal()
s.refund = 0 s.refund = 0
} }
s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entries s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entries
} }
@ -1375,6 +1380,7 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
if err := nodes.Merge(set); err != nil { if err := nodes.Merge(set); err != nil {
return common.Hash{}, err return common.Hash{}, err
} }
updates, deleted := set.Size() updates, deleted := set.Size()
storageTrieNodesUpdated += updates storageTrieNodesUpdated += updates
storageTrieNodesDeleted += deleted storageTrieNodesDeleted += deleted
@ -1400,12 +1406,14 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
if metrics.EnabledExpensive { if metrics.EnabledExpensive {
start = time.Now() start = time.Now()
} }
root, set := s.trie.Commit(true) root, set := s.trie.Commit(true)
// Merge the dirty nodes of account trie into global set // Merge the dirty nodes of account trie into global set
if set != nil { if set != nil {
if err := nodes.Merge(set); err != nil { if err := nodes.Merge(set); err != nil {
return common.Hash{}, err return common.Hash{}, err
} }
accountTrieNodesUpdated, accountTrieNodesDeleted = set.Size() accountTrieNodesUpdated, accountTrieNodesDeleted = set.Size()
} }
if metrics.EnabledExpensive { if metrics.EnabledExpensive {
@ -1438,31 +1446,42 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err) log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err)
} }
} }
if metrics.EnabledExpensive { if metrics.EnabledExpensive {
s.SnapshotCommits += time.Since(start) s.SnapshotCommits += time.Since(start)
} }
s.snap, s.snapAccounts, s.snapStorage = nil, nil, nil s.snap, s.snapAccounts, s.snapStorage = nil, nil, nil
} }
if len(s.stateObjectsDestruct) > 0 { if len(s.stateObjectsDestruct) > 0 {
s.stateObjectsDestruct = make(map[common.Address]struct{}) s.stateObjectsDestruct = make(map[common.Address]struct{})
} }
if root == (common.Hash{}) { if root == (common.Hash{}) {
root = types.EmptyRootHash root = types.EmptyRootHash
} }
origin := s.originalRoot origin := s.originalRoot
if origin == (common.Hash{}) { if origin == (common.Hash{}) {
origin = types.EmptyRootHash origin = types.EmptyRootHash
} }
if root != origin { if root != origin {
start := time.Now() start := time.Now()
if err := s.db.TrieDB().Update(nodes); err != nil { if err := s.db.TrieDB().Update(nodes); err != nil {
return common.Hash{}, err return common.Hash{}, err
} }
s.originalRoot = root s.originalRoot = root
if metrics.EnabledExpensive { if metrics.EnabledExpensive {
s.TrieDBCommits += time.Since(start) s.TrieDBCommits += time.Since(start)
} }
} }
return root, nil return root, nil
} }
@ -1486,15 +1505,19 @@ func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, d
s.accessList = al s.accessList = al
al.AddAddress(sender) al.AddAddress(sender)
if dst != nil { if dst != nil {
al.AddAddress(*dst)
// If it's a create-tx, the destination will be added inside evm.create // If it's a create-tx, the destination will be added inside evm.create
al.AddAddress(*dst)
} }
for _, addr := range precompiles { for _, addr := range precompiles {
al.AddAddress(addr) al.AddAddress(addr)
} }
for _, el := range list { for _, el := range list {
al.AddAddress(el.Address) al.AddAddress(el.Address)
for _, key := range el.StorageKeys { for _, key := range el.StorageKeys {
al.AddSlot(el.Address, key) al.AddSlot(el.Address, key)
} }
@ -1546,6 +1569,7 @@ func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addre
// convertAccountSet converts a provided account set from address keyed to hash keyed. // convertAccountSet converts a provided account set from address keyed to hash keyed.
func (s *StateDB) convertAccountSet(set map[common.Address]struct{}) map[common.Hash]struct{} { func (s *StateDB) convertAccountSet(set map[common.Address]struct{}) map[common.Hash]struct{} {
ret := make(map[common.Hash]struct{}) ret := make(map[common.Hash]struct{})
for addr := range set { for addr := range set {
obj, exist := s.stateObjects[addr] obj, exist := s.stateObjects[addr]
if !exist { if !exist {
@ -1554,5 +1578,6 @@ func (s *StateDB) convertAccountSet(set map[common.Address]struct{}) map[common.
ret[obj.addrHash] = struct{}{} ret[obj.addrHash] = struct{}{}
} }
} }
return ret return ret
} }

View file

@ -104,11 +104,12 @@ func TestIntermediateLeaks(t *testing.T) {
modify(finalState, common.Address{i}, i, 99) modify(finalState, common.Address{i}, i, 99)
} }
// Commit and cross check the databases. // Commit and cross-check the databases.
transRoot, err := transState.Commit(false) transRoot, err := transState.Commit(false)
if err != nil { if err != nil {
t.Fatalf("failed to commit transition state: %v", err) t.Fatalf("failed to commit transition state: %v", err)
} }
if err = transState.Database().TrieDB().Commit(transRoot, false); err != nil { if err = transState.Database().TrieDB().Commit(transRoot, false); err != nil {
t.Errorf("can not commit trie %v to persistent database", transRoot.Hex()) t.Errorf("can not commit trie %v to persistent database", transRoot.Hex())
} }
@ -117,6 +118,7 @@ func TestIntermediateLeaks(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to commit final state: %v", err) t.Fatalf("failed to commit final state: %v", err)
} }
if err = finalState.Database().TrieDB().Commit(finalRoot, false); err != nil { if err = finalState.Database().TrieDB().Commit(finalRoot, false); err != nil {
t.Errorf("can not commit trie %v to persistent database", finalRoot.Hex()) t.Errorf("can not commit trie %v to persistent database", finalRoot.Hex())
} }
@ -476,6 +478,7 @@ func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error {
return fmt.Errorf("got GetRefund() == %d, want GetRefund() == %d", return fmt.Errorf("got GetRefund() == %d, want GetRefund() == %d",
state.GetRefund(), checkstate.GetRefund()) state.GetRefund(), checkstate.GetRefund())
} }
if !reflect.DeepEqual(state.GetLogs(common.Hash{}, 0, common.Hash{}), checkstate.GetLogs(common.Hash{}, 0, common.Hash{})) { if !reflect.DeepEqual(state.GetLogs(common.Hash{}, 0, common.Hash{}), checkstate.GetLogs(common.Hash{}, 0, common.Hash{})) {
return fmt.Errorf("got GetLogs(common.Hash{}) == %v, want GetLogs(common.Hash{}) == %v", return fmt.Errorf("got GetLogs(common.Hash{}) == %v, want GetLogs(common.Hash{}) == %v",
state.GetLogs(common.Hash{}, 0, common.Hash{}), checkstate.GetLogs(common.Hash{}, 0, common.Hash{})) state.GetLogs(common.Hash{}, 0, common.Hash{}), checkstate.GetLogs(common.Hash{}, 0, common.Hash{}))
@ -1390,20 +1393,26 @@ func TestFlushOrderDataLoss(t *testing.T) {
statedb = NewDatabase(memdb) statedb = NewDatabase(memdb)
state, _ = New(common.Hash{}, statedb, nil) state, _ = New(common.Hash{}, statedb, nil)
) )
for a := byte(0); a < 10; a++ { for a := byte(0); a < 10; a++ {
state.CreateAccount(common.Address{a}) state.CreateAccount(common.Address{a})
for s := byte(0); s < 10; s++ { for s := byte(0); s < 10; s++ {
state.SetState(common.Address{a}, common.Hash{a, s}, common.Hash{a, s}) state.SetState(common.Address{a}, common.Hash{a, s}, common.Hash{a, s})
} }
} }
root, err := state.Commit(false) root, err := state.Commit(false)
if err != nil { if err != nil {
t.Fatalf("failed to commit state trie: %v", err) t.Fatalf("failed to commit state trie: %v", err)
} }
statedb.TrieDB().Reference(root, common.Hash{}) statedb.TrieDB().Reference(root, common.Hash{})
if err := statedb.TrieDB().Cap(1024); err != nil { if err := statedb.TrieDB().Cap(1024); err != nil {
t.Fatalf("failed to cap trie dirty cache: %v", err) t.Fatalf("failed to cap trie dirty cache: %v", err)
} }
if err := statedb.TrieDB().Commit(root, false); err != nil { if err := statedb.TrieDB().Commit(root, false); err != nil {
t.Fatalf("failed to commit state trie: %v", err) t.Fatalf("failed to commit state trie: %v", err)
} }
@ -1412,6 +1421,7 @@ func TestFlushOrderDataLoss(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to reopen state trie: %v", err) t.Fatalf("failed to reopen state trie: %v", err)
} }
for a := byte(0); a < 10; a++ { for a := byte(0); a < 10; a++ {
for s := byte(0); s < 10; s++ { for s := byte(0); s < 10; s++ {
if have := state.GetState(common.Address{a}, common.Hash{a, s}); have != (common.Hash{a, s}) { if have := state.GetState(common.Address{a}, common.Hash{a, s}); have != (common.Hash{a, s}) {
@ -1433,6 +1443,7 @@ func TestStateDBTransientStorage(t *testing.T) {
addr := common.Address{} addr := common.Address{}
state.SetTransientState(addr, key, value) state.SetTransientState(addr, key, value)
if exp, got := 1, state.journal.length(); exp != got { if exp, got := 1, state.journal.length(); exp != got {
t.Fatalf("journal length mismatch: have %d, want %d", got, exp) t.Fatalf("journal length mismatch: have %d, want %d", got, exp)
} }
@ -1444,6 +1455,7 @@ func TestStateDBTransientStorage(t *testing.T) {
// revert the transient state being set and then check that the // revert the transient state being set and then check that the
// value is now the empty hash // value is now the empty hash
state.journal.revert(state, 0) state.journal.revert(state, 0)
if got, exp := state.GetTransientState(addr, key), (common.Hash{}); exp != got { if got, exp := state.GetTransientState(addr, key), (common.Hash{}); exp != got {
t.Fatalf("transient storage mismatch: have %x, want %x", got, exp) t.Fatalf("transient storage mismatch: have %x, want %x", got, exp)
} }
@ -1452,6 +1464,7 @@ func TestStateDBTransientStorage(t *testing.T) {
// the transient state is copied // the transient state is copied
state.SetTransientState(addr, key, value) state.SetTransientState(addr, key, value)
cpy := state.Copy() cpy := state.Copy()
if got := cpy.GetTransientState(addr, key); got != value { if got := cpy.GetTransientState(addr, key); got != value {
t.Fatalf("transient storage mismatch: have %x, want %x", got, value) t.Fatalf("transient storage mismatch: have %x, want %x", got, value)
} }

View file

@ -38,6 +38,7 @@ func NewStateSync(root common.Hash, database ethdb.KeyValueReader, onLeaf func(k
// Register the account callback to connect the state trie and the storage // Register the account callback to connect the state trie and the storage
// trie belongs to the contract. // trie belongs to the contract.
var syncer *trie.Sync var syncer *trie.Sync
onAccount := func(keys [][]byte, path []byte, leaf []byte, parent common.Hash, parentPath []byte) error { onAccount := func(keys [][]byte, path []byte, leaf []byte, parent common.Hash, parentPath []byte) error {
if onLeaf != nil { if onLeaf != nil {
if err := onLeaf(keys, leaf); err != nil { if err := onLeaf(keys, leaf); err != nil {
@ -48,6 +49,7 @@ func NewStateSync(root common.Hash, database ethdb.KeyValueReader, onLeaf func(k
if err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil { if err := rlp.Decode(bytes.NewReader(leaf), &obj); err != nil {
return err return err
} }
syncer.AddSubTrie(obj.Root, path, parent, parentPath, onSlot) syncer.AddSubTrie(obj.Root, path, parent, parentPath, onSlot)
syncer.AddCodeEntry(common.BytesToHash(obj.CodeHash), path, parent, parentPath) syncer.AddCodeEntry(common.BytesToHash(obj.CodeHash), path, parent, parentPath)
return nil return nil

View file

@ -105,11 +105,13 @@ func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
if v, _ := db.Get(root[:]); v == nil { if v, _ := db.Get(root[:]); v == nil {
return nil // Consider a non existent state consistent. return nil // Consider a non existent state consistent.
} }
trie, err := trie.New(trie.StateTrieID(root), trie.NewDatabase(db))
t, err := trie.New(trie.StateTrieID(root), trie.NewDatabase(db))
if err != nil { if err != nil {
return err return err
} }
it := trie.NodeIterator(nil) it := t.NodeIterator(nil)
for it.Next(true) { for it.Next(true) {
} }
return it.Error() return it.Error()
@ -135,6 +137,7 @@ func checkStateConsistency(db ethdb.Database, root common.Hash) error {
func TestEmptyStateSync(t *testing.T) { func TestEmptyStateSync(t *testing.T) {
db := trie.NewDatabase(rawdb.NewMemoryDatabase()) db := trie.NewDatabase(rawdb.NewMemoryDatabase())
sync := NewStateSync(types.EmptyRootHash, rawdb.NewMemoryDatabase(), nil, db.Scheme()) sync := NewStateSync(types.EmptyRootHash, rawdb.NewMemoryDatabase(), nil, db.Scheme())
if paths, nodes, codes := sync.Missing(1); len(paths) != 0 || len(nodes) != 0 || len(codes) != 0 { if paths, nodes, codes := sync.Missing(1); len(paths) != 0 || len(nodes) != 0 || len(codes) != 0 {
t.Errorf("content requested for empty state: %v, %v, %v", nodes, paths, codes) t.Errorf("content requested for empty state: %v, %v, %v", nodes, paths, codes)
} }
@ -175,6 +178,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
if commit { if commit {
srcDb.TrieDB().Commit(srcRoot, false) srcDb.TrieDB().Commit(srcRoot, false)
} }
srcTrie, _ := trie.New(trie.StateTrieID(srcRoot), srcDb.TrieDB()) srcTrie, _ := trie.New(trie.StateTrieID(srcRoot), srcDb.TrieDB())
// Create a destination state and sync with the scheduler // Create a destination state and sync with the scheduler
@ -186,6 +190,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
codeElements []stateElement codeElements []stateElement
) )
paths, nodes, codes := sched.Missing(count) paths, nodes, codes := sched.Missing(count)
for i := 0; i < len(paths); i++ { for i := 0; i < len(paths); i++ {
nodeElements = append(nodeElements, stateElement{ nodeElements = append(nodeElements, stateElement{
path: paths[i], path: paths[i],
@ -193,23 +198,28 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
syncPath: trie.NewSyncPath([]byte(paths[i])), syncPath: trie.NewSyncPath([]byte(paths[i])),
}) })
} }
for i := 0; i < len(codes); i++ { for i := 0; i < len(codes); i++ {
codeElements = append(codeElements, stateElement{ codeElements = append(codeElements, stateElement{
code: codes[i], code: codes[i],
}) })
} }
for len(nodeElements)+len(codeElements) > 0 { for len(nodeElements)+len(codeElements) > 0 {
var ( var (
nodeResults = make([]trie.NodeSyncResult, len(nodeElements)) nodeResults = make([]trie.NodeSyncResult, len(nodeElements))
codeResults = make([]trie.CodeSyncResult, len(codeElements)) codeResults = make([]trie.CodeSyncResult, len(codeElements))
) )
for i, element := range codeElements { for i, element := range codeElements {
data, err := srcDb.ContractCode(common.Hash{}, element.code) data, err := srcDb.ContractCode(common.Hash{}, element.code)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve contract bytecode for hash %x", element.code) t.Fatalf("failed to retrieve contract bytecode for hash %x", element.code)
} }
codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data} codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
} }
for i, node := range nodeElements { for i, node := range nodeElements {
if bypath { if bypath {
if len(node.syncPath) == 1 { if len(node.syncPath) == 1 {
@ -217,6 +227,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[0], err) t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[0], err)
} }
nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data} nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
} else { } else {
var acc types.StateAccount var acc types.StateAccount
@ -242,11 +253,13 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data} nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
} }
} }
for _, result := range codeResults { for _, result := range codeResults {
if err := sched.ProcessCode(result); err != nil { if err := sched.ProcessCode(result); err != nil {
t.Errorf("failed to process result %v", err) t.Errorf("failed to process result %v", err)
} }
} }
for _, result := range nodeResults { for _, result := range nodeResults {
if err := sched.ProcessNode(result); err != nil { if err := sched.ProcessNode(result); err != nil {
t.Errorf("failed to process result %v", err) t.Errorf("failed to process result %v", err)
@ -260,6 +273,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
paths, nodes, codes = sched.Missing(count) paths, nodes, codes = sched.Missing(count)
nodeElements = nodeElements[:0] nodeElements = nodeElements[:0]
for i := 0; i < len(paths); i++ { for i := 0; i < len(paths); i++ {
nodeElements = append(nodeElements, stateElement{ nodeElements = append(nodeElements, stateElement{
path: paths[i], path: paths[i],
@ -267,7 +281,9 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
syncPath: trie.NewSyncPath([]byte(paths[i])), syncPath: trie.NewSyncPath([]byte(paths[i])),
}) })
} }
codeElements = codeElements[:0] codeElements = codeElements[:0]
for i := 0; i < len(codes); i++ { for i := 0; i < len(codes); i++ {
codeElements = append(codeElements, stateElement{ codeElements = append(codeElements, stateElement{
code: codes[i], code: codes[i],
@ -292,7 +308,9 @@ func TestIterativeDelayedStateSync(t *testing.T) {
nodeElements []stateElement nodeElements []stateElement
codeElements []stateElement codeElements []stateElement
) )
paths, nodes, codes := sched.Missing(0) paths, nodes, codes := sched.Missing(0)
for i := 0; i < len(paths); i++ { for i := 0; i < len(paths); i++ {
nodeElements = append(nodeElements, stateElement{ nodeElements = append(nodeElements, stateElement{
path: paths[i], path: paths[i],
@ -300,15 +318,19 @@ func TestIterativeDelayedStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(paths[i])), syncPath: trie.NewSyncPath([]byte(paths[i])),
}) })
} }
for i := 0; i < len(codes); i++ { for i := 0; i < len(codes); i++ {
codeElements = append(codeElements, stateElement{ codeElements = append(codeElements, stateElement{
code: codes[i], code: codes[i],
}) })
} }
for len(nodeElements)+len(codeElements) > 0 { for len(nodeElements)+len(codeElements) > 0 {
// Sync only half of the scheduled nodes // Sync only half of the scheduled nodes
var nodeProcessed int var nodeProcessed int
var codeProcessed int var codeProcessed int
if len(codeElements) > 0 { if len(codeElements) > 0 {
codeResults := make([]trie.CodeSyncResult, len(codeElements)/2+1) codeResults := make([]trie.CodeSyncResult, len(codeElements)/2+1)
for i, element := range codeElements[:len(codeResults)] { for i, element := range codeElements[:len(codeResults)] {
@ -316,15 +338,19 @@ func TestIterativeDelayedStateSync(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to retrieve contract bytecode for %x", element.code) t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
} }
codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data} codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
} }
for _, result := range codeResults { for _, result := range codeResults {
if err := sched.ProcessCode(result); err != nil { if err := sched.ProcessCode(result); err != nil {
t.Fatalf("failed to process result %v", err) t.Fatalf("failed to process result %v", err)
} }
} }
codeProcessed = len(codeResults) codeProcessed = len(codeResults)
} }
if len(nodeElements) > 0 { if len(nodeElements) > 0 {
nodeResults := make([]trie.NodeSyncResult, len(nodeElements)/2+1) nodeResults := make([]trie.NodeSyncResult, len(nodeElements)/2+1)
for i, element := range nodeElements[:len(nodeResults)] { for i, element := range nodeElements[:len(nodeResults)] {
@ -332,13 +358,16 @@ func TestIterativeDelayedStateSync(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to retrieve contract bytecode for %x", element.code) t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
} }
nodeResults[i] = trie.NodeSyncResult{Path: element.path, Data: data} nodeResults[i] = trie.NodeSyncResult{Path: element.path, Data: data}
} }
for _, result := range nodeResults { for _, result := range nodeResults {
if err := sched.ProcessNode(result); err != nil { if err := sched.ProcessNode(result); err != nil {
t.Fatalf("failed to process result %v", err) t.Fatalf("failed to process result %v", err)
} }
} }
nodeProcessed = len(nodeResults) nodeProcessed = len(nodeResults)
} }
batch := dstDb.NewBatch() batch := dstDb.NewBatch()
@ -349,6 +378,7 @@ func TestIterativeDelayedStateSync(t *testing.T) {
paths, nodes, codes = sched.Missing(0) paths, nodes, codes = sched.Missing(0)
nodeElements = nodeElements[nodeProcessed:] nodeElements = nodeElements[nodeProcessed:]
for i := 0; i < len(paths); i++ { for i := 0; i < len(paths); i++ {
nodeElements = append(nodeElements, stateElement{ nodeElements = append(nodeElements, stateElement{
path: paths[i], path: paths[i],
@ -356,7 +386,9 @@ func TestIterativeDelayedStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(paths[i])), syncPath: trie.NewSyncPath([]byte(paths[i])),
}) })
} }
codeElements = codeElements[codeProcessed:] codeElements = codeElements[codeProcessed:]
for i := 0; i < len(codes); i++ { for i := 0; i < len(codes); i++ {
codeElements = append(codeElements, stateElement{ codeElements = append(codeElements, stateElement{
code: codes[i], code: codes[i],
@ -384,6 +416,7 @@ func testIterativeRandomStateSync(t *testing.T, count int) {
nodeQueue := make(map[string]stateElement) nodeQueue := make(map[string]stateElement)
codeQueue := make(map[common.Hash]struct{}) codeQueue := make(map[common.Hash]struct{})
paths, nodes, codes := sched.Missing(count) paths, nodes, codes := sched.Missing(count)
for i, path := range paths { for i, path := range paths {
nodeQueue[path] = stateElement{ nodeQueue[path] = stateElement{
path: path, path: path,
@ -391,35 +424,44 @@ func testIterativeRandomStateSync(t *testing.T, count int) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
for len(nodeQueue)+len(codeQueue) > 0 { for len(nodeQueue)+len(codeQueue) > 0 {
// Fetch all the queued nodes in a random order // Fetch all the queued nodes in a random order
if len(codeQueue) > 0 { if len(codeQueue) > 0 {
results := make([]trie.CodeSyncResult, 0, len(codeQueue)) results := make([]trie.CodeSyncResult, 0, len(codeQueue))
for hash := range codeQueue { for hash := range codeQueue {
data, err := srcDb.ContractCode(common.Hash{}, hash) data, err := srcDb.ContractCode(common.Hash{}, hash)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x", hash) t.Fatalf("failed to retrieve node data for %x", hash)
} }
results = append(results, trie.CodeSyncResult{Hash: hash, Data: data}) results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
} }
for _, result := range results { for _, result := range results {
if err := sched.ProcessCode(result); err != nil { if err := sched.ProcessCode(result); err != nil {
t.Fatalf("failed to process result %v", err) t.Fatalf("failed to process result %v", err)
} }
} }
} }
if len(nodeQueue) > 0 { if len(nodeQueue) > 0 {
results := make([]trie.NodeSyncResult, 0, len(nodeQueue)) results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
for path, element := range nodeQueue { for path, element := range nodeQueue {
data, err := srcDb.TrieDB().Node(element.hash) data, err := srcDb.TrieDB().Node(element.hash)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x %v %v", element.hash, []byte(element.path), element.path) t.Fatalf("failed to retrieve node data for %x %v %v", element.hash, []byte(element.path), element.path)
} }
results = append(results, trie.NodeSyncResult{Path: path, Data: data}) results = append(results, trie.NodeSyncResult{Path: path, Data: data})
} }
for _, result := range results { for _, result := range results {
if err := sched.ProcessNode(result); err != nil { if err := sched.ProcessNode(result); err != nil {
t.Fatalf("failed to process result %v", err) t.Fatalf("failed to process result %v", err)
@ -436,6 +478,7 @@ func testIterativeRandomStateSync(t *testing.T, count int) {
nodeQueue = make(map[string]stateElement) nodeQueue = make(map[string]stateElement)
codeQueue = make(map[common.Hash]struct{}) codeQueue = make(map[common.Hash]struct{})
paths, nodes, codes := sched.Missing(count) paths, nodes, codes := sched.Missing(count)
for i, path := range paths { for i, path := range paths {
nodeQueue[path] = stateElement{ nodeQueue[path] = stateElement{
path: path, path: path,
@ -443,11 +486,12 @@ func testIterativeRandomStateSync(t *testing.T, count int) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
} }
// Cross check that the two states are in sync // Cross-check that the two states are in sync
checkStateAccounts(t, dstDb, srcRoot, srcAccounts) checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
} }
@ -464,6 +508,7 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
nodeQueue := make(map[string]stateElement) nodeQueue := make(map[string]stateElement)
codeQueue := make(map[common.Hash]struct{}) codeQueue := make(map[common.Hash]struct{})
paths, nodes, codes := sched.Missing(0) paths, nodes, codes := sched.Missing(0)
for i, path := range paths { for i, path := range paths {
nodeQueue[path] = stateElement{ nodeQueue[path] = stateElement{
path: path, path: path,
@ -471,13 +516,16 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
for len(nodeQueue)+len(codeQueue) > 0 { for len(nodeQueue)+len(codeQueue) > 0 {
// Sync only half of the scheduled nodes, even those in random order // Sync only half of the scheduled nodes, even those in random order
if len(codeQueue) > 0 { if len(codeQueue) > 0 {
results := make([]trie.CodeSyncResult, 0, len(codeQueue)/2+1) results := make([]trie.CodeSyncResult, 0, len(codeQueue)/2+1)
for hash := range codeQueue { for hash := range codeQueue {
delete(codeQueue, hash) delete(codeQueue, hash)
@ -485,24 +533,29 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x", hash) t.Fatalf("failed to retrieve node data for %x", hash)
} }
results = append(results, trie.CodeSyncResult{Hash: hash, Data: data}) results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
if len(results) >= cap(results) { if len(results) >= cap(results) {
break break
} }
} }
for _, result := range results { for _, result := range results {
if err := sched.ProcessCode(result); err != nil { if err := sched.ProcessCode(result); err != nil {
t.Fatalf("failed to process result %v", err) t.Fatalf("failed to process result %v", err)
} }
} }
} }
if len(nodeQueue) > 0 { if len(nodeQueue) > 0 {
results := make([]trie.NodeSyncResult, 0, len(nodeQueue)/2+1) results := make([]trie.NodeSyncResult, 0, len(nodeQueue)/2+1)
for path, element := range nodeQueue { for path, element := range nodeQueue {
delete(nodeQueue, path) delete(nodeQueue, path)
data, err := srcDb.TrieDB().Node(element.hash) data, err := srcDb.TrieDB().Node(element.hash)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x", element.hash) t.Fatalf("failed to retrieve node data for %x", element.hash)
} }
@ -533,11 +586,12 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
} }
// Cross check that the two states are in sync // Cross-check that the two states are in sync
checkStateAccounts(t, dstDb, srcRoot, srcAccounts) checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
} }
@ -554,8 +608,9 @@ func TestIncompleteStateSync(t *testing.T) {
isCode[crypto.Keccak256Hash(acc.code)] = struct{}{} isCode[crypto.Keccak256Hash(acc.code)] = struct{}{}
} }
} }
isCode[types.EmptyCodeHash] = struct{}{} isCode[types.EmptyCodeHash] = struct{}{}
checkTrieConsistency(db, srcRoot) _ = checkTrieConsistency(db, srcRoot)
// Create a destination state and sync with the scheduler // Create a destination state and sync with the scheduler
dstDb := rawdb.NewMemoryDatabase() dstDb := rawdb.NewMemoryDatabase()
@ -566,9 +621,11 @@ func TestIncompleteStateSync(t *testing.T) {
addedPaths []string addedPaths []string
addedHashes []common.Hash addedHashes []common.Hash
) )
nodeQueue := make(map[string]stateElement) nodeQueue := make(map[string]stateElement)
codeQueue := make(map[common.Hash]struct{}) codeQueue := make(map[common.Hash]struct{})
paths, nodes, codes := sched.Missing(1) paths, nodes, codes := sched.Missing(1)
for i, path := range paths { for i, path := range paths {
nodeQueue[path] = stateElement{ nodeQueue[path] = stateElement{
path: path, path: path,
@ -576,18 +633,22 @@ func TestIncompleteStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
for len(nodeQueue)+len(codeQueue) > 0 { for len(nodeQueue)+len(codeQueue) > 0 {
// Fetch a batch of state nodes // Fetch a batch of state nodes
if len(codeQueue) > 0 { if len(codeQueue) > 0 {
results := make([]trie.CodeSyncResult, 0, len(codeQueue)) results := make([]trie.CodeSyncResult, 0, len(codeQueue))
for hash := range codeQueue { for hash := range codeQueue {
data, err := srcDb.ContractCode(common.Hash{}, hash) data, err := srcDb.ContractCode(common.Hash{}, hash)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x", hash) t.Fatalf("failed to retrieve node data for %x", hash)
} }
results = append(results, trie.CodeSyncResult{Hash: hash, Data: data}) results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
addedCodes = append(addedCodes, hash) addedCodes = append(addedCodes, hash)
} }
@ -598,20 +659,25 @@ func TestIncompleteStateSync(t *testing.T) {
} }
} }
} }
var nodehashes []common.Hash var nodehashes []common.Hash
if len(nodeQueue) > 0 { if len(nodeQueue) > 0 {
results := make([]trie.NodeSyncResult, 0, len(nodeQueue)) results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
for path, element := range nodeQueue { for path, element := range nodeQueue {
data, err := srcDb.TrieDB().Node(element.hash) data, err := srcDb.TrieDB().Node(element.hash)
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x", element.hash) t.Fatalf("failed to retrieve node data for %x", element.hash)
} }
results = append(results, trie.NodeSyncResult{Path: path, Data: data}) results = append(results, trie.NodeSyncResult{Path: path, Data: data})
if element.hash != srcRoot { if element.hash != srcRoot {
addedPaths = append(addedPaths, element.path) addedPaths = append(addedPaths, element.path)
addedHashes = append(addedHashes, element.hash) addedHashes = append(addedHashes, element.hash)
} }
nodehashes = append(nodehashes, element.hash) nodehashes = append(nodehashes, element.hash)
} }
// Process each of the state nodes // Process each of the state nodes
@ -638,6 +704,7 @@ func TestIncompleteStateSync(t *testing.T) {
nodeQueue = make(map[string]stateElement) nodeQueue = make(map[string]stateElement)
codeQueue = make(map[common.Hash]struct{}) codeQueue = make(map[common.Hash]struct{})
paths, nodes, codes := sched.Missing(1) paths, nodes, codes := sched.Missing(1)
for i, path := range paths { for i, path := range paths {
nodeQueue[path] = stateElement{ nodeQueue[path] = stateElement{
path: path, path: path,
@ -645,6 +712,7 @@ func TestIncompleteStateSync(t *testing.T) {
syncPath: trie.NewSyncPath([]byte(path)), syncPath: trie.NewSyncPath([]byte(path)),
} }
} }
for _, hash := range codes { for _, hash := range codes {
codeQueue[hash] = struct{}{} codeQueue[hash] = struct{}{}
} }
@ -653,23 +721,31 @@ func TestIncompleteStateSync(t *testing.T) {
for _, node := range addedCodes { for _, node := range addedCodes {
val := rawdb.ReadCode(dstDb, node) val := rawdb.ReadCode(dstDb, node)
rawdb.DeleteCode(dstDb, node) rawdb.DeleteCode(dstDb, node)
if err := checkStateConsistency(dstDb, srcRoot); err == nil { if err := checkStateConsistency(dstDb, srcRoot); err == nil {
t.Errorf("trie inconsistency not caught, missing: %x", node) t.Errorf("trie inconsistency not caught, missing: %x", node)
} }
rawdb.WriteCode(dstDb, node, val) rawdb.WriteCode(dstDb, node, val)
} }
scheme := srcDb.TrieDB().Scheme() scheme := srcDb.TrieDB().Scheme()
for i, path := range addedPaths { for i, path := range addedPaths {
owner, inner := trie.ResolvePath([]byte(path)) owner, inner := trie.ResolvePath([]byte(path))
hash := addedHashes[i] hash := addedHashes[i]
val := rawdb.ReadTrieNode(dstDb, owner, inner, hash, scheme) val := rawdb.ReadTrieNode(dstDb, owner, inner, hash, scheme)
if val == nil { if val == nil {
t.Error("missing trie node") t.Error("missing trie node")
} }
rawdb.DeleteTrieNode(dstDb, owner, inner, hash, scheme) rawdb.DeleteTrieNode(dstDb, owner, inner, hash, scheme)
if err := checkStateConsistency(dstDb, srcRoot); err == nil { if err := checkStateConsistency(dstDb, srcRoot); err == nil {
t.Errorf("trie inconsistency not caught, missing: %v", path) t.Errorf("trie inconsistency not caught, missing: %v", path)
} }
rawdb.WriteTrieNode(dstDb, owner, inner, hash, val, scheme) rawdb.WriteTrieNode(dstDb, owner, inner, hash, val, scheme)
} }
} }

View file

@ -33,6 +33,7 @@ func (t transientStorage) Set(addr common.Address, key, value common.Hash) {
if _, ok := t[addr]; !ok { if _, ok := t[addr]; !ok {
t[addr] = make(Storage) t[addr] = make(Storage)
} }
t[addr][key] = value t[addr][key] = value
} }
@ -42,6 +43,7 @@ func (t transientStorage) Get(addr common.Address, key common.Hash) common.Hash
if !ok { if !ok {
return common.Hash{} return common.Hash{}
} }
return val[key] return val[key]
} }
@ -51,5 +53,6 @@ func (t transientStorage) Copy() transientStorage {
for key, value := range t { for key, value := range t {
storage[key] = value.Copy() storage[key] = value.Copy()
} }
return storage return storage
} }

View file

@ -300,6 +300,7 @@ func (sf *subfetcher) loop() {
log.Warn("Trie prefetcher failed opening trie", "root", sf.root, "err", err) log.Warn("Trie prefetcher failed opening trie", "root", sf.root, "err", err)
return return
} }
sf.trie = trie sf.trie = trie
} else { } else {
trie, err := sf.db.OpenStorageTrie(sf.state, sf.owner, sf.root) trie, err := sf.db.OpenStorageTrie(sf.state, sf.owner, sf.root)

View file

@ -50,6 +50,7 @@ func TestCopyAndClose(t *testing.T) {
prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()})
prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()})
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
a := prefetcher.trie(common.Hash{}, db.originalRoot) a := prefetcher.trie(common.Hash{}, db.originalRoot)
prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()}) prefetcher.prefetch(common.Hash{}, db.originalRoot, common.Address{}, [][]byte{skey.Bytes()})
b := prefetcher.trie(common.Hash{}, db.originalRoot) b := prefetcher.trie(common.Hash{}, db.originalRoot)

View file

@ -21,6 +21,8 @@ import (
"math/rand" "math/rand"
"testing" "testing"
"github.com/holiman/uint256"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )

View file

@ -24,6 +24,8 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/kylelemons/godebug/diff"
"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"

View file

@ -76,6 +76,7 @@ func codeBitmapInternal(code, bits bitvec) bitvec {
for pc := uint64(0); pc < uint64(len(code)); { for pc := uint64(0); pc < uint64(len(code)); {
op := OpCode(code[pc]) op := OpCode(code[pc])
pc++ pc++
if int8(op) < int8(PUSH1) { // If not PUSH (the int8(op) > int(PUSH32) is always false). if int8(op) < int8(PUSH1) { // If not PUSH (the int8(op) > int(PUSH32) is always false).
continue continue
} }

View file

@ -197,6 +197,8 @@ func opTload(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]by
hash := common.Hash(loc.Bytes32()) hash := common.Hash(loc.Bytes32())
val := interpreter.evm.StateDB.GetTransientState(scope.Contract.Address(), hash) val := interpreter.evm.StateDB.GetTransientState(scope.Contract.Address(), hash)
loc.SetBytes(val.Bytes()) loc.SetBytes(val.Bytes())
// nolint:nilnil
return nil, nil return nil, nil
} }
@ -205,9 +207,12 @@ func opTstore(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]b
if interpreter.readOnly { if interpreter.readOnly {
return nil, ErrWriteProtection return nil, ErrWriteProtection
} }
loc := scope.Stack.pop() loc := scope.Stack.pop()
val := scope.Stack.pop() val := scope.Stack.pop()
interpreter.evm.StateDB.SetTransientState(scope.Contract.Address(), loc.Bytes32(), val.Bytes32()) interpreter.evm.StateDB.SetTransientState(scope.Contract.Address(), loc.Bytes32(), val.Bytes32())
// nolint:nilnil
return nil, nil return nil, nil
} }

View file

@ -307,7 +307,9 @@ func gasCreateEip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
if err != nil { if err != nil {
return 0, err return 0, err
} }
size, overflow := stack.Back(2).Uint64WithOverflow() size, overflow := stack.Back(2).Uint64WithOverflow()
if overflow || size > params.MaxInitCodeSize { if overflow || size > params.MaxInitCodeSize {
return 0, ErrGasUintOverflow return 0, ErrGasUintOverflow
} }
@ -316,6 +318,7 @@ func gasCreateEip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory, m
if gas, overflow = math.SafeAdd(gas, moreGas); overflow { if gas, overflow = math.SafeAdd(gas, moreGas); overflow {
return 0, ErrGasUintOverflow return 0, ErrGasUintOverflow
} }
return gas, nil return gas, nil
} }
func gasCreate2Eip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) { func gasCreate2Eip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
@ -323,7 +326,9 @@ func gasCreate2Eip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory,
if err != nil { if err != nil {
return 0, err return 0, err
} }
size, overflow := stack.Back(2).Uint64WithOverflow() size, overflow := stack.Back(2).Uint64WithOverflow()
if overflow || size > params.MaxInitCodeSize { if overflow || size > params.MaxInitCodeSize {
return 0, ErrGasUintOverflow return 0, ErrGasUintOverflow
} }
@ -332,6 +337,7 @@ func gasCreate2Eip3860(evm *EVM, contract *Contract, stack *Stack, mem *Memory,
if gas, overflow = math.SafeAdd(gas, moreGas); overflow { if gas, overflow = math.SafeAdd(gas, moreGas); overflow {
return 0, ErrGasUintOverflow return 0, ErrGasUintOverflow
} }
return gas, nil return gas, nil
} }

View file

@ -135,39 +135,49 @@ func TestCreateGas(t *testing.T) {
for i, tt := range createGasTests { for i, tt := range createGasTests {
var gasUsed = uint64(0) var gasUsed = uint64(0)
doCheck := func(testGas int) bool { doCheck := func(testGas int) bool {
address := common.BytesToAddress([]byte("contract")) address := common.BytesToAddress([]byte("contract"))
statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
statedb.CreateAccount(address) statedb.CreateAccount(address)
statedb.SetCode(address, hexutil.MustDecode(tt.code)) statedb.SetCode(address, hexutil.MustDecode(tt.code))
statedb.Finalise(true) statedb.Finalise(true)
vmctx := BlockContext{ vmctx := BlockContext{
CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true }, CanTransfer: func(StateDB, common.Address, *big.Int) bool { return true },
Transfer: func(StateDB, common.Address, common.Address, *big.Int) {}, Transfer: func(StateDB, common.Address, common.Address, *big.Int) {},
BlockNumber: big.NewInt(0), BlockNumber: big.NewInt(0),
} }
config := Config{} config := Config{}
if tt.eip3860 { if tt.eip3860 {
config.ExtraEips = []int{3860} config.ExtraEips = []int{3860}
} }
vmenv := NewEVM(vmctx, TxContext{}, statedb, params.AllEthashProtocolChanges, config) vmenv := NewEVM(vmctx, TxContext{}, statedb, params.AllEthashProtocolChanges, config)
var startGas = uint64(testGas) var startGas = uint64(testGas)
ret, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, startGas, new(big.Int), nil) ret, gas, err := vmenv.Call(AccountRef(common.Address{}), address, nil, startGas, new(big.Int), nil)
if err != nil { if err != nil {
return false return false
} }
gasUsed = startGas - gas gasUsed = startGas - gas
if len(ret) != 32 { if len(ret) != 32 {
t.Fatalf("test %d: expected 32 bytes returned, have %d", i, len(ret)) t.Fatalf("test %d: expected 32 bytes returned, have %d", i, len(ret))
} }
if bytes.Equal(ret, make([]byte, 32)) { if bytes.Equal(ret, make([]byte, 32)) {
// Failure // Failure
return false return false
} }
return true return true
} }
minGas := sort.Search(100_000, doCheck) minGas := sort.Search(100_000, doCheck)
if uint64(minGas) != tt.minimumGas { if uint64(minGas) != tt.minimumGas {
t.Fatalf("test %d: min gas error, want %d, have %d", i, tt.minimumGas, minGas) t.Fatalf("test %d: min gas error, want %d, have %d", i, tt.minimumGas, minGas)
} }

View file

@ -822,6 +822,7 @@ func opSelfdestruct(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext
balance := interpreter.evm.StateDB.GetBalance(scope.Contract.Address()) balance := interpreter.evm.StateDB.GetBalance(scope.Contract.Address())
interpreter.evm.StateDB.AddBalance(beneficiary.Bytes20(), balance) interpreter.evm.StateDB.AddBalance(beneficiary.Bytes20(), balance)
interpreter.evm.StateDB.Suicide(scope.Contract.Address()) interpreter.evm.StateDB.Suicide(scope.Contract.Address())
if tracer := interpreter.evm.Config.Tracer; tracer != nil { if tracer := interpreter.evm.Config.Tracer; tracer != nil {
tracer.CaptureEnter(SELFDESTRUCT, scope.Contract.Address(), beneficiary.Bytes20(), []byte{}, 0, balance) tracer.CaptureEnter(SELFDESTRUCT, scope.Contract.Address(), beneficiary.Bytes20(), []byte{}, 0, balance)
tracer.CaptureExit([]byte{}, 0, nil) tracer.CaptureExit([]byte{}, 0, nil)

View file

@ -251,15 +251,19 @@ func TestWriteExpectedValues(t *testing.T) {
interpreter = env.interpreter interpreter = env.interpreter
) )
result := make([]TwoOperandTestcase, len(args)) result := make([]TwoOperandTestcase, len(args))
for i, param := range args { for i, param := range args {
x := new(uint256.Int).SetBytes(common.Hex2Bytes(param.x)) x := new(uint256.Int).SetBytes(common.Hex2Bytes(param.x))
y := new(uint256.Int).SetBytes(common.Hex2Bytes(param.y)) y := new(uint256.Int).SetBytes(common.Hex2Bytes(param.y))
stack.push(x) stack.push(x)
stack.push(y) stack.push(y)
opFn(&pc, interpreter, &ScopeContext{nil, stack, nil})
_, _ = opFn(&pc, interpreter, &ScopeContext{nil, stack, nil})
actual := stack.pop() actual := stack.pop()
result[i] = TwoOperandTestcase{param.x, param.y, fmt.Sprintf("%064x", actual)} result[i] = TwoOperandTestcase{param.x, param.y, fmt.Sprintf("%064x", actual)}
} }
return result return result
} }
@ -268,6 +272,7 @@ func TestWriteExpectedValues(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
_ = os.WriteFile(fmt.Sprintf("testdata/testcases_%v.json", name), data, 0644) _ = os.WriteFile(fmt.Sprintf("testdata/testcases_%v.json", name), data, 0644)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -616,7 +621,9 @@ func TestOpTstore(t *testing.T) {
if stack.len() != 1 { if stack.len() != 1 {
t.Fatal("stack wrong size") t.Fatal("stack wrong size")
} }
val := stack.peek() val := stack.peek()
if !bytes.Equal(val.Bytes(), value) { if !bytes.Equal(val.Bytes(), value) {
t.Fatal("incorrect element read from transient storage") t.Fatal("incorrect element read from transient storage")
} }

View file

@ -130,6 +130,7 @@ func PutCache(ctx context.Context, cache *TxCache) context.Context {
func NewEVMInterpreter(evm *EVM) *EVMInterpreter { func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
// If jump table was not initialised we set the default one. // If jump table was not initialised we set the default one.
var table *JumpTable var table *JumpTable
switch { switch {
// TODO marcello double check // TODO marcello double check
case evm.chainRules.IsShanghai: case evm.chainRules.IsShanghai:
@ -155,11 +156,14 @@ func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
default: default:
table = &frontierInstructionSet table = &frontierInstructionSet
} }
var extraEips []int var extraEips []int
if len(evm.Config.ExtraEips) > 0 { if len(evm.Config.ExtraEips) > 0 {
// Deep-copy jumptable to prevent modification of opcodes in other tables // Deep-copy jumptable to prevent modification of opcodes in other tables
table = copyJumpTable(table) table = copyJumpTable(table)
} }
for _, eip := range evm.Config.ExtraEips { for _, eip := range evm.Config.ExtraEips {
if err := EnableEIP(eip, table); err != nil { if err := EnableEIP(eip, table); err != nil {
// Disable it, so caller can check if it's activated or not // Disable it, so caller can check if it's activated or not
@ -168,7 +172,9 @@ func NewEVMInterpreter(evm *EVM) *EVMInterpreter {
extraEips = append(extraEips, eip) extraEips = append(extraEips, eip)
} }
} }
evm.Config.ExtraEips = extraEips evm.Config.ExtraEips = extraEips
return &EVMInterpreter{evm: evm, table: table} return &EVMInterpreter{evm: evm, table: table}
} }
@ -244,6 +250,7 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool, i
defer func() { defer func() {
returnStack(stack) returnStack(stack)
}() }()
contract.Input = input contract.Input = input
if debug { if debug {
@ -504,6 +511,7 @@ func (in *EVMInterpreter) RunWithDelay(contract *Contract, input []byte, readOnl
// Do tracing before memory expansion // Do tracing before memory expansion
if debug { if debug {
in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) in.evm.Config.Tracer.CaptureState(pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err)
logged = true logged = true
} }
if memorySize > 0 { if memorySize > 0 {

View file

@ -83,6 +83,7 @@ func newShanghaiInstructionSet() JumpTable {
instructionSet := newMergeInstructionSet() instructionSet := newMergeInstructionSet()
enable3855(&instructionSet) // PUSH0 instruction enable3855(&instructionSet) // PUSH0 instruction
enable3860(&instructionSet) // Limit and meter initcode enable3860(&instructionSet) // Limit and meter initcode
return validate(instructionSet) return validate(instructionSet)
} }
@ -1054,11 +1055,13 @@ func newFrontierInstructionSet() JumpTable {
func copyJumpTable(source *JumpTable) *JumpTable { func copyJumpTable(source *JumpTable) *JumpTable {
dest := *source dest := *source
for i, op := range source { for i, op := range source {
if op != nil { if op != nil {
opCopy := *op opCopy := *op
dest[i] = &opCopy dest[i] = &opCopy
} }
} }
return &dest return &dest
} }

View file

@ -51,6 +51,7 @@ func LookupInstructionSet(rules params.Rules) (JumpTable, error) {
case rules.IsHomestead: case rules.IsHomestead:
return newHomesteadInstructionSet(), nil return newHomesteadInstructionSet(), nil
} }
return newFrontierInstructionSet(), nil return newFrontierInstructionSet(), nil
} }

View file

@ -61,6 +61,7 @@ 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"
"github.com/ethereum/go-ethereum/trie"
) )
// Config contains the configuration options of the ETH protocol. // Config contains the configuration options of the ETH protocol.

View file

@ -34,6 +34,7 @@ type ethPeer struct {
} }
// info gathers and returns some `eth` protocol metadata known about a peer. // info gathers and returns some `eth` protocol metadata known about a peer.
// nolint:typecheck
func (p *ethPeer) info() *ethPeerInfo { func (p *ethPeer) info() *ethPeerInfo {
return &ethPeerInfo{ return &ethPeerInfo{
Version: p.Version(), Version: p.Version(),

View file

@ -65,6 +65,7 @@ func newTestBackend(blocks int) *testBackend {
// newTestBackend creates a chain with a number of explicitly defined blocks and // newTestBackend creates a chain with a number of explicitly defined blocks and
// wraps it into a mock backend. // wraps it into a mock backend.
// nolint:typecheck
func newTestBackendWithGenerator(blocks int, shanghai bool, generator func(int, *core.BlockGen)) *testBackend { func newTestBackendWithGenerator(blocks int, shanghai bool, generator func(int, *core.BlockGen)) *testBackend {
var ( var (
// Create a database pre-initialize with a genesis block // Create a database pre-initialize with a genesis block

View file

@ -21,6 +21,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"golang.org/x/crypto/sha3"
gomath "math" gomath "math"
"math/big" "math/big"
"math/rand" "math/rand"
@ -2744,7 +2745,7 @@ func (s *Syncer) OnTrieNodes(peer SyncPeer, id uint64, trienodes [][]byte) error
} }
s.lock.Unlock() s.lock.Unlock()
// Cross reference the requested trienodes with the response to find gaps // Cross-reference the requested trie-nodes with the response to find gaps
// that the serving node is missing // that the serving node is missing
var ( var (
hasher = sha3.NewLegacyKeccak256().(crypto.KeccakState) hasher = sha3.NewLegacyKeccak256().(crypto.KeccakState)
@ -2755,8 +2756,8 @@ func (s *Syncer) OnTrieNodes(peer SyncPeer, id uint64, trienodes [][]byte) error
for i, j := 0, 0; i < len(trienodes); i++ { for i, j := 0, 0; i < len(trienodes); i++ {
// Find the next hash that we've been served, leaving misses with nils // Find the next hash that we've been served, leaving misses with nils
hasher.Reset() hasher.Reset()
hasher.Write(trienodes[i]) _, _ = hasher.Write(trienodes[i])
hasher.Read(hash) _, _ = hasher.Read(hash)
for j < len(req.hashes) && !bytes.Equal(hash, req.hashes[j][:]) { for j < len(req.hashes) && !bytes.Equal(hash, req.hashes[j][:]) {
j++ j++

View file

@ -391,6 +391,7 @@ func TestTraceTransaction(t *testing.T) {
} }
} }
// nolint:typecheck
func TestTraceBlock(t *testing.T) { func TestTraceBlock(t *testing.T) {
t.Parallel() t.Parallel()
@ -552,6 +553,7 @@ func TestIOdump(t *testing.T) {
} }
} }
// nolint:typecheck
func TestTracingWithOverrides(t *testing.T) { func TestTracingWithOverrides(t *testing.T) {
t.Parallel() t.Parallel()
// Initialize test accounts // Initialize test accounts
@ -923,6 +925,7 @@ func newStates(keys []common.Hash, vals []common.Hash) *map[common.Hash]common.H
return &m return &m
} }
// nolint:typecheck
func TestTraceChain(t *testing.T) { func TestTraceChain(t *testing.T) {
t.Parallel() t.Parallel()

View file

@ -240,6 +240,7 @@ func (l *StructLogger) GetResult() (json.RawMessage, error) {
if l.reason != nil { if l.reason != nil {
return nil, l.reason return nil, l.reason
} }
failed := l.err != nil failed := l.err != nil
returnData := common.CopyBytes(l.output) returnData := common.CopyBytes(l.output)
// Return data when successful and revert reason when reverted, otherwise empty. // Return data when successful and revert reason when reverted, otherwise empty.
@ -247,6 +248,7 @@ func (l *StructLogger) GetResult() (json.RawMessage, error) {
if failed && l.err != vm.ErrExecutionReverted { if failed && l.err != vm.ErrExecutionReverted {
returnVal = "" returnVal = ""
} }
return json.Marshal(&ExecutionResult{ return json.Marshal(&ExecutionResult{
Gas: l.usedGas, Gas: l.usedGas,
Failed: failed, Failed: failed,
@ -436,27 +438,34 @@ func formatLogs(logs []StructLog) []StructLogRes {
Error: trace.ErrorString(), Error: trace.ErrorString(),
RefundCounter: trace.RefundCounter, RefundCounter: trace.RefundCounter,
} }
if trace.Stack != nil { if trace.Stack != nil {
stack := make([]string, len(trace.Stack)) stack := make([]string, len(trace.Stack))
for i, stackValue := range trace.Stack { for i, stackValue := range trace.Stack {
stack[i] = stackValue.Hex() stack[i] = stackValue.Hex()
} }
formatted[index].Stack = &stack formatted[index].Stack = &stack
} }
if trace.Memory != nil { if trace.Memory != nil {
memory := make([]string, 0, (len(trace.Memory)+31)/32) memory := make([]string, 0, (len(trace.Memory)+31)/32)
for i := 0; i+32 <= len(trace.Memory); i += 32 { for i := 0; i+32 <= len(trace.Memory); i += 32 {
memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
} }
formatted[index].Memory = &memory formatted[index].Memory = &memory
} }
if trace.Storage != nil { if trace.Storage != nil {
storage := make(map[string]string) storage := make(map[string]string)
for i, storageValue := range trace.Storage { for i, storageValue := range trace.Storage {
storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
} }
formatted[index].Storage = &storage formatted[index].Storage = &storage
} }
} }
return formatted return formatted
} }

View file

@ -51,6 +51,7 @@ type dummyStatedb struct {
func (*dummyStatedb) GetRefund() uint64 { return 1337 } func (*dummyStatedb) GetRefund() uint64 { return 1337 }
func (*dummyStatedb) GetState(_ common.Address, _ common.Hash) common.Hash { return common.Hash{} } func (*dummyStatedb) GetState(_ common.Address, _ common.Hash) common.Hash { return common.Hash{} }
func (*dummyStatedb) SetState(_ common.Address, _ common.Hash, _ common.Hash) {} func (*dummyStatedb) SetState(_ common.Address, _ common.Hash, _ common.Hash) {}
func (*dummyStatedb) AddAddressToAccessList(address common.Address) {}
func TestStoreCapture(t *testing.T) { func TestStoreCapture(t *testing.T) {
var ( var (

View file

@ -79,6 +79,7 @@ func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
return n, blocks return n, blocks
} }
// nolint:typecheck
func generateTestChain() (*core.Genesis, []*types.Block) { func generateTestChain() (*core.Genesis, []*types.Block) {
genesis := &core.Genesis{ genesis := &core.Genesis{
Config: params.AllEthashProtocolChanges, Config: params.AllEthashProtocolChanges,

View file

@ -172,6 +172,7 @@ func TestGraphQLBlockSerialization(t *testing.T) {
} }
} }
// nolint:typecheck
func TestGraphQLBlockSerializationEIP2718(t *testing.T) { func TestGraphQLBlockSerializationEIP2718(t *testing.T) {
// Account for signing txes // Account for signing txes
var ( var (
@ -277,6 +278,7 @@ func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
assert.Equal(t, http.StatusNotFound, resp.StatusCode) assert.Equal(t, http.StatusNotFound, resp.StatusCode)
} }
// nolint:typecheck
func TestGraphQLConcurrentResolvers(t *testing.T) { func TestGraphQLConcurrentResolvers(t *testing.T) {
t.Parallel() t.Parallel()

View file

@ -24,10 +24,12 @@ import (
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"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/consensus/beacon" //nolint:typecheck "github.com/ethereum/go-ethereum/consensus/beacon" //nolint:typecheck
"github.com/ethereum/go-ethereum/consensus/bor" //nolint:typecheck "github.com/ethereum/go-ethereum/consensus/bor" //nolint:typecheck
"github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/consensus/clique"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/ethereum/go-ethereum/eth/tracers" "github.com/ethereum/go-ethereum/eth/tracers"
"github.com/ethereum/go-ethereum/ethstats" "github.com/ethereum/go-ethereum/ethstats"
"github.com/ethereum/go-ethereum/graphql" "github.com/ethereum/go-ethereum/graphql"

View file

@ -20,6 +20,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/urfave/cli/v2"
"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"
) )

View file

@ -37,6 +37,7 @@ func TestUpdateTimer(t *testing.T) {
if updated := timer.Update(func(diff time.Duration) bool { return true }); !updated { if updated := timer.Update(func(diff time.Duration) bool { return true }); !updated {
t.Fatalf("Doesn't update the clock when reaching the threshold") t.Fatalf("Doesn't update the clock when reaching the threshold")
} }
if updated := timer.UpdateAt(sim.Now().Add(time.Second), func(diff time.Duration) bool { return true }); !updated { if updated := timer.UpdateAt(sim.Now().Add(time.Second), func(diff time.Duration) bool { return true }); !updated {
t.Fatalf("Doesn't update the clock when reaching the threshold") t.Fatalf("Doesn't update the clock when reaching the threshold")
} }

View file

@ -58,6 +58,7 @@ func NewRegisteredCounterFloat64(name string, r Registry) CounterFloat64 {
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
_ = r.Register(name, c) _ = r.Register(name, c)
return c return c
@ -73,6 +74,7 @@ func NewRegisteredCounterFloat64Forced(name string, r Registry) CounterFloat64 {
if nil == r { if nil == r {
r = DefaultRegistry r = DefaultRegistry
} }
_ = r.Register(name, c) _ = r.Register(name, c)
return c return c

View file

@ -5,7 +5,7 @@ import (
"crypto/rand" "crypto/rand"
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts" // nolint:typecheck
"github.com/ethereum/go-ethereum/consensus/bor" "github.com/ethereum/go-ethereum/consensus/bor"
"github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/consensus/clique"
"github.com/ethereum/go-ethereum/consensus/ethash" "github.com/ethereum/go-ethereum/consensus/ethash"

View file

@ -29,6 +29,8 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/gofrs/flock"
"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/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
@ -336,7 +338,7 @@ func (n *Node) openDataDir() error {
func (n *Node) closeDataDir() { func (n *Node) closeDataDir() {
// Release instance directory lock. // Release instance directory lock.
if n.dirLock != nil && n.dirLock.Locked() { if n.dirLock != nil && n.dirLock.Locked() {
n.dirLock.Unlock() _ = n.dirLock.Unlock()
n.dirLock = nil n.dirLock = nil
} }
} }

View file

@ -347,6 +347,7 @@ func (d *dialScheduler) rearmHistoryTimer() {
if len(d.history) == 0 { if len(d.history) == 0 {
return return
} }
d.historyTimer.Schedule(d.history.nextExpiry()) d.historyTimer.Schedule(d.history.nextExpiry())
} }

View file

@ -142,6 +142,7 @@ func (it *lookup) slowdown() {
func (it *lookup) query(n *node, reply chan<- []*node) { func (it *lookup) query(n *node, reply chan<- []*node) {
fails := it.tab.db.FindFails(n.ID(), n.IP()) fails := it.tab.db.FindFails(n.ID(), n.IP())
r, err := it.queryfunc(n) r, err := it.queryfunc(n)
if errors.Is(err, errClosed) { if errors.Is(err, errClosed) {
// Avoid recording failures on shutdown. // Avoid recording failures on shutdown.
reply <- nil reply <- nil

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