diff --git a/.golangci.yml b/.golangci.yml index 9b5a80b54c..72955396a8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,7 +1,6 @@ # This file configures github.com/golangci/golangci-lint. run: - go: '1.20' timeout: 20m tests: true # default is true. Enables skipping of directories: @@ -9,180 +8,60 @@ run: skip-dirs-use-default: true skip-files: - core/genesis_alloc.go - - gen_.*.go - - .*_gen.go linters: + disable-all: true enable: - goconst - goimports + - gosimple + - govet + - ineffassign - misspell - unconvert - - bodyclose - - containedctx - - contextcheck - - decorder + - typecheck + - unused + - staticcheck + - bidichk - durationcheck - - errchkjson - - errname - - exhaustive - exportloopref - - gocognit - - gofmt - # - gomnd - # - gomoddirectives - - gosec - - makezero - - nestif - - nilerr - - nilnil - - noctx - #- nosprintfhostport # TODO: do we use IPv6? - - paralleltest - - prealloc - - predeclared - #- promlinter - #- revive - # - tagliatelle - - tenv - - thelper - - tparallel - - unconvert - - unparam - # - wsl - - asasalint - #- errorlint causes stack overflow. TODO: recheck after each golangci update + - whitespace + + # - structcheck # lots of false positives + # - errcheck #lot of false positives + # - contextcheck + # - errchkjson # lots of false positives + # - errorlint # this check crashes + # - exhaustive # silly check + # - makezero # false positives + # - nilerr # several intentional linters-settings: gofmt: simplify: true - auto-fix: false - goconst: min-len: 3 # minimum length of string constant - min-occurrences: 2 # minimum number of occurrences - numbers: true - - goimports: - local-prefixes: github.com/ethereum/go-ethereum - - nestif: - min-complexity: 5 - - prealloc: - for-loops: true - - gocritic: - # Which checks should be enabled; can't be combined with 'disabled-checks'; - # See https://go-critic.github.io/overview#checks-overview - # To check which checks are enabled run `GL_DEBUG=gocritic ./build/bin/golangci-lint run` - # By default list of stable checks is used. - enabled-checks: - - badLock - - filepathJoin - - sortSlice - - sprintfQuotedString - - syncMapLoadAndDelete - - weakCond - - boolExprSimplify - - httpNoBody - - ioutilDeprecated - - nestingReduce - - preferFilepathJoin - - redundantSprint - - stringConcatSimplify - - timeExprSimplify - - typeAssertChain - - yodaStyleExpr - - truncateCmp - - equalFold - - preferDecodeRune - - preferFprint - - preferStringWriter - - preferWriteByte - - sliceClear - #- ruleguard - - # Which checks should be disabled; can't be combined with 'enabled-checks'; default is empty - disabled-checks: - - regexpMust - - exitAfterDefer - - dupBranchBody - - singleCaseSwitch - - unlambda - - captLocal - - commentFormatting - - ifElseChain - - importShadow - - builtinShadow - - # Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks. - # Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags". - enabled-tags: - - performance - - diagnostic - - opinionated - - style - disabled-tags: - - experimental - govet: - disable: - - deepequalerrors - - fieldalignment - - shadow - - unsafeptr - check-shadowing: true - enable-all: true - settings: - printf: - # Run `go tool vet help printf` to see available settings for `printf` analyzer. - funcs: - - (github.com/ethereum/go-ethereum/log.Logger).Trace - - (github.com/ethereum/go-ethereum/log.Logger).Debug - - (github.com/ethereum/go-ethereum/log.Logger).Info - - (github.com/ethereum/go-ethereum/log.Logger).Warn - - (github.com/ethereum/go-ethereum/log.Logger).Error - - (github.com/ethereum/go-ethereum/log.Logger).Crit + min-occurrences: 6 # minimum number of occurrences issues: exclude-rules: - path: crypto/bn256/cloudflare/optate.go linters: - deadcode - - path: crypto/bn256/cloudflare - linters: - - deadcode - - path: p2p/discv5/ - linters: - - deadcode - - path: core/vm/instructions_test.go - linters: - - goconst - - path: cmd/faucet/ - linters: - - deadcode - # Exclude some linters from running on tests files. - - path: test\.go - linters: - - gosec - - unused - - deadcode - - gocritic - - path: cmd/devp2p - linters: - - gosec - - unused - - deadcode - - gocritic - - path: metrics/sample\.go - linters: - - gosec - - gocritic - - path: p2p/simulations - linters: - - gosec - - gocritic - max-issues-per-linter: 0 - max-same-issues: 0 - #new: true - new-from-rev: origin/master + - staticcheck + - path: internal/build/pgp.go + text: 'SA1019: "golang.org/x/crypto/openpgp" is deprecated: this package is unmaintained except for security fixes.' + - path: core/vm/contracts.go + text: 'SA1019: "golang.org/x/crypto/ripemd160" is deprecated: RIPEMD-160 is a legacy hash and should not be used for new applications.' + - path: accounts/usbwallet/trezor.go + text: 'SA1019: "github.com/golang/protobuf/proto" is deprecated: Use the "google.golang.org/protobuf/proto" package instead.' + - path: accounts/usbwallet/trezor/ + text: 'SA1019: "github.com/golang/protobuf/proto" is deprecated: Use the "google.golang.org/protobuf/proto" package instead.' + exclude: + - 'SA1019: event.TypeMux is deprecated: use Feed' + - 'SA1019: strings.Title is deprecated' + - 'SA1019: strings.Title has been deprecated since Go 1.18 and an alternative has been available since Go 1.0: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.' + - 'SA1029: should not use built-in type string as key for value' + - 'SA1019: "io/ioutil" has been deprecated since Go 1.19: As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details' + - 'SA1019: grpc.WithInsecure is deprecated: use WithTransportCredentials and insecure.NewCredentials() instead. Will be supported throughout 1.x' + - "SA1019: rand.Read has been deprecated since Go 1.20 because it shouldn't be used: For almost all use cases, crypto/rand.Read is more appropriate" diff --git a/cmd/geth/config.go b/cmd/geth/config.go index aae5258d28..321d0d388c 100644 --- a/cmd/geth/config.go +++ b/cmd/geth/config.go @@ -205,11 +205,9 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) { // dumpConfig is the dumpconfig command. func dumpConfig(ctx *cli.Context) error { _, cfg := makeConfigNode(ctx) - comment := "" if cfg.Eth.Genesis != nil { cfg.Eth.Genesis = nil - comment += "# Note: this config doesn't contain the genesis block.\n\n" } if err := toml.NewEncoder(os.Stdout).Encode(&cfg); err != nil { @@ -277,21 +275,6 @@ func applyMetricConfig(ctx *cli.Context, cfg *gethConfig) { } } -func deprecated(field string) bool { - switch field { - case "ethconfig.Config.EVMInterpreter": - return true - case "ethconfig.Config.EWASMInterpreter": - return true - case "ethconfig.Config.TrieCleanCacheJournal": - return true - case "ethconfig.Config.TrieCleanCacheRejournal": - return true - default: - return false - } -} - func setAccountManagerBackends(conf *node.Config, am *accounts.Manager, keydir string) error { scryptN := keystore.StandardScryptN scryptP := keystore.StandardScryptP diff --git a/cmd/geth/main.go b/cmd/geth/main.go index f7d5181593..f45b61a53b 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -276,7 +276,6 @@ func main() { // prepare manipulates memory cache allowance and setups metric system. // This function should be called before launching devp2p stack. func prepare(ctx *cli.Context) { - const light = "light" // If we're running a known preset, log it for convenience. diff --git a/cmd/utils/bor_flags.go b/cmd/utils/bor_flags.go index 8c0d35f2ef..76d965746c 100644 --- a/cmd/utils/bor_flags.go +++ b/cmd/utils/bor_flags.go @@ -1,15 +1,12 @@ package utils import ( - "encoding/json" "os" "github.com/urfave/cli/v2" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth/ethconfig" - "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/node" ) @@ -67,24 +64,6 @@ var ( } ) -func getGenesis(genesisPath string) (*core.Genesis, error) { - log.Info("Reading genesis at ", "file", genesisPath) - - file, err := os.Open(genesisPath) - if err != nil { - return nil, err - } - - defer file.Close() - - genesis := new(core.Genesis) - if err := json.NewDecoder(file).Decode(genesis); err != nil { - return nil, err - } - - return genesis, nil -} - // SetBorConfig sets bor config func SetBorConfig(ctx *cli.Context, cfg *eth.Config) { cfg.HeimdallURL = ctx.String(HeimdallURLFlag.Name) diff --git a/consensus/bor/statefull/processor.go b/consensus/bor/statefull/processor.go index 039f3daae0..b4579cb413 100644 --- a/consensus/bor/statefull/processor.go +++ b/consensus/bor/statefull/processor.go @@ -104,7 +104,7 @@ func ApplyMessage( return gasUsed, nil } -func ApplyBorMessage(vmenv vm.EVM, msg Callmsg) (*core.ExecutionResult, error) { +func ApplyBorMessage(vmenv *vm.EVM, msg Callmsg) (*core.ExecutionResult, error) { initialGas := msg.Gas() // Apply the transaction to the current state (included in the env) diff --git a/core/blockchain_bor_test.go b/core/blockchain_bor_test.go index 6719f4f149..93412076b8 100644 --- a/core/blockchain_bor_test.go +++ b/core/blockchain_bor_test.go @@ -117,7 +117,7 @@ func TestChain2HeadEvent(t *testing.T) { }}) // reorg event - //In this event the channel recieves an array of Blocks in NewChain and OldChain + //In this event the channel receives an array of Blocks in NewChain and OldChain readEvent(&eventTest{ Type: Chain2HeadReorgEvent, Added: []common.Hash{ diff --git a/core/blockstm/executor_test.go b/core/blockstm/executor_test.go index 8a16e0652f..eb06776a7d 100644 --- a/core/blockstm/executor_test.go +++ b/core/blockstm/executor_test.go @@ -471,7 +471,7 @@ func runParallelGetMetadata(t *testing.T, tasks []ExecTask, validation PropertyC func TestLessConflicts(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{10, 50, 100, 200, 300} numReads := []int{20, 100, 200} @@ -495,7 +495,7 @@ func TestLessConflicts(t *testing.T) { func TestLessConflictsWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{300} numReads := []int{100, 200} @@ -541,7 +541,7 @@ func TestLessConflictsWithMetadata(t *testing.T) { func TestZeroTx(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{0} numReads := []int{20} @@ -562,7 +562,7 @@ func TestZeroTx(t *testing.T) { func TestAlternatingTx(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{200} numReads := []int{20} @@ -583,7 +583,7 @@ func TestAlternatingTx(t *testing.T) { func TestAlternatingTxWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{200} numReads := []int{20} @@ -626,7 +626,7 @@ func TestAlternatingTxWithMetadata(t *testing.T) { func TestMoreConflicts(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{10, 50, 100, 200, 300} numReads := []int{20, 100, 200} @@ -650,7 +650,7 @@ func TestMoreConflicts(t *testing.T) { func TestMoreConflictsWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{300} numReads := []int{100, 200} @@ -696,7 +696,7 @@ func TestMoreConflictsWithMetadata(t *testing.T) { func TestRandomTx(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{10, 50, 100, 200, 300} numReads := []int{20, 100, 200} @@ -718,7 +718,7 @@ func TestRandomTx(t *testing.T) { func TestRandomTxWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{300} numReads := []int{100, 200} @@ -762,7 +762,7 @@ func TestRandomTxWithMetadata(t *testing.T) { func TestTxWithLongTailRead(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{10, 50, 100, 200, 300} numReads := []int{20, 100, 200} @@ -789,7 +789,7 @@ func TestTxWithLongTailRead(t *testing.T) { func TestTxWithLongTailReadWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{300} numReads := []int{100, 200} @@ -838,7 +838,7 @@ func TestTxWithLongTailReadWithMetadata(t *testing.T) { func TestDexScenario(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{10, 50, 100, 200, 300} numReads := []int{20, 100, 200} @@ -873,7 +873,7 @@ func TestDexScenario(t *testing.T) { func TestDexScenarioWithMetadata(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) totalTxs := []int{300} numReads := []int{100, 200} @@ -930,7 +930,7 @@ func TestDexScenarioWithMetadata(t *testing.T) { func TestBreakFromCircularDependency(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) tasks := make([]ExecTask, 5) @@ -956,7 +956,7 @@ func TestBreakFromCircularDependency(t *testing.T) { func TestBreakFromPartialCircularDependency(t *testing.T) { t.Parallel() - rand.Seed(0) + rand.New(rand.NewSource(0)) tasks := make([]ExecTask, 5) diff --git a/core/blockstm/mvhashmap.go b/core/blockstm/mvhashmap.go index 3739609304..59085138cf 100644 --- a/core/blockstm/mvhashmap.go +++ b/core/blockstm/mvhashmap.go @@ -115,7 +115,6 @@ func (mv *MVHashMap) Write(k Key, v Version, data interface{}) { rw: sync.RWMutex{}, tm: treemap.NewWithIntComparator(), } - cells = n val, _ := mv.m.LoadOrStore(kenc, n) cells = val.(*TxnIndexCells) diff --git a/core/bor_blockchain.go b/core/bor_blockchain.go index d6a0226b02..1a5ce39e62 100644 --- a/core/bor_blockchain.go +++ b/core/bor_blockchain.go @@ -18,7 +18,7 @@ func (bc *BlockChain) GetBorReceiptByHash(hash common.Hash) *types.Receipt { return nil } - // read bor reciept by hash and number + // read bor receipt by hash and number receipt := rawdb.ReadBorReceipt(bc.db, hash, *number, bc.chainConfig) if receipt == nil { return nil diff --git a/core/rawdb/bor_receipt.go b/core/rawdb/bor_receipt.go index f3242b51ce..456000f821 100644 --- a/core/rawdb/bor_receipt.go +++ b/core/rawdb/bor_receipt.go @@ -61,7 +61,7 @@ func ReadBorReceiptRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.Raw func ReadRawBorReceipt(db ethdb.Reader, hash common.Hash, number uint64) *types.Receipt { // Retrieve the flattened receipt slice data := ReadBorReceiptRLP(db, hash, number) - if data == nil || len(data) == 0 { + if len(data) == 0 { return nil } diff --git a/core/rawdb/database.go b/core/rawdb/database.go index d5c4e0f395..3aaa6fcf3e 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -424,11 +424,6 @@ func openKeyValueDatabase(o OpenOptions) (ethdb.Database, error) { log.Info("Defaulting to leveldb as the backing database") return NewLevelDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly, o.ExtraDBConfig) } - - // Use leveldb, either as default (no explicit choice), or pre-existing, or chosen explicitly - log.Info("Using leveldb as the backing database") - - return NewLevelDBDatabase(o.Directory, o.Cache, o.Handles, o.Namespace, o.ReadOnly, o.ExtraDBConfig) } // Open opens both a disk-based key-value database such as leveldb or pebble, but also diff --git a/core/rawdb/freezer_table.go b/core/rawdb/freezer_table.go index 181ad6812b..0d3def83ae 100644 --- a/core/rawdb/freezer_table.go +++ b/core/rawdb/freezer_table.go @@ -1039,15 +1039,15 @@ func (t *freezerTable) dumpIndex(w io.Writer, start, stop int64) { // Bor related changes // -// Fill adds empty data till given number (convenience method for backward compatibilty) +// Fill adds empty data till given number (convenience method for backward compatibility) func (t *freezerTable) Fill(number uint64) error { if t.items.Load() < number { b := t.newBatch() - log.Info("Filling all data into freezer for backward compatablity", "name", t.name, "items", t.items, "number", number) + log.Info("Filling all data into freezer for backward compatibility", "name", t.name, "items", &t.items, "number", number) for t.items.Load() < number { if err := b.Append(t.items.Load(), nil); err != nil { - log.Error("Failed to fill data into freezer", "name", t.name, "items", t.items, "number", number, "err", err) + log.Error("Failed to fill data into freezer", "name", t.name, "items", &t.items, "number", number, "err", err) return err } } diff --git a/core/txpool/legacypool/legacypool_test.go b/core/txpool/legacypool/legacypool_test.go index bd155fdd67..27cd244294 100644 --- a/core/txpool/legacypool/legacypool_test.go +++ b/core/txpool/legacypool/legacypool_test.go @@ -24,7 +24,6 @@ import ( "math/big" "math/rand" "os" - "strings" "sync" "sync/atomic" "testing" @@ -32,12 +31,8 @@ import ( "github.com/holiman/uint256" "github.com/maticnetwork/crand" - "gonum.org/v1/gonum/floats" - "gonum.org/v1/gonum/stat" - "pgregory.net/rapid" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/debug" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" @@ -59,7 +54,7 @@ var ( ) const ( - txPoolGasLimit = 10_000_000 +// txPoolGasLimit = 10_000_000 ) func init() { @@ -3274,131 +3269,131 @@ func newTxs(pool *LegacyPool) *types.Transaction { return tx } -type acc struct { - nonce uint64 - key *ecdsa.PrivateKey - account common.Address -} +// type acc struct { +// nonce uint64 +// key *ecdsa.PrivateKey +// account common.Address +// } -type testTx struct { - tx *types.Transaction - idx int - isLocal bool -} +// type testTx struct { +// tx *types.Transaction +// idx int +// isLocal bool +// } -const localIdx = 0 +// const localIdx = 0 -func getTransactionGen(t *rapid.T, keys []*acc, nonces []uint64, localKey *acc, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax uint64) *testTx { - idx := rapid.IntRange(0, len(keys)-1).Draw(t, "accIdx").(int) +// func getTransactionGen(t *rapid.T, keys []*acc, nonces []uint64, localKey *acc, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax uint64) *testTx { +// idx := rapid.IntRange(0, len(keys)-1).Draw(t, "accIdx").(int) - var ( - isLocal bool - key *ecdsa.PrivateKey - ) +// var ( +// isLocal bool +// key *ecdsa.PrivateKey +// ) - if idx == localIdx { - isLocal = true - key = localKey.key - } else { - key = keys[idx].key - } +// if idx == localIdx { +// isLocal = true +// key = localKey.key +// } else { +// key = keys[idx].key +// } - nonces[idx]++ +// nonces[idx]++ - gasPriceUint := rapid.Uint64Range(gasPriceMin, gasPriceMax).Draw(t, "gasPrice").(uint64) - gasPrice := big.NewInt(0).SetUint64(gasPriceUint) - gasLimit := rapid.Uint64Range(gasLimitMin, gasLimitMax).Draw(t, "gasLimit").(uint64) +// gasPriceUint := rapid.Uint64Range(gasPriceMin, gasPriceMax).Draw(t, "gasPrice").(uint64) +// gasPrice := big.NewInt(0).SetUint64(gasPriceUint) +// gasLimit := rapid.Uint64Range(gasLimitMin, gasLimitMax).Draw(t, "gasLimit").(uint64) - return &testTx{ - tx: pricedTransaction(nonces[idx]-1, gasLimit, gasPrice, key), - idx: idx, - isLocal: isLocal, - } -} +// return &testTx{ +// tx: pricedTransaction(nonces[idx]-1, gasLimit, gasPrice, key), +// idx: idx, +// isLocal: isLocal, +// } +// } -type transactionBatches struct { - txs []*testTx - totalTxs int -} +// type transactionBatches struct { +// txs []*testTx +// totalTxs int +// } -func transactionsGen(keys []*acc, nonces []uint64, localKey *acc, minTxs int, maxTxs int, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax uint64, caseParams *strings.Builder) func(t *rapid.T) *transactionBatches { - return func(t *rapid.T) *transactionBatches { - totalTxs := rapid.IntRange(minTxs, maxTxs).Draw(t, "totalTxs").(int) - txs := make([]*testTx, totalTxs) +// func transactionsGen(keys []*acc, nonces []uint64, localKey *acc, minTxs int, maxTxs int, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax uint64, caseParams *strings.Builder) func(t *rapid.T) *transactionBatches { +// return func(t *rapid.T) *transactionBatches { +// totalTxs := rapid.IntRange(minTxs, maxTxs).Draw(t, "totalTxs").(int) +// txs := make([]*testTx, totalTxs) - gasValues := make([]float64, totalTxs) +// gasValues := make([]float64, totalTxs) - fmt.Fprintf(caseParams, " totalTxs = %d;", totalTxs) +// fmt.Fprintf(caseParams, " totalTxs = %d;", totalTxs) - keys = keys[:len(nonces)] +// keys = keys[:len(nonces)] - for i := 0; i < totalTxs; i++ { - txs[i] = getTransactionGen(t, keys, nonces, localKey, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax) +// for i := 0; i < totalTxs; i++ { +// txs[i] = getTransactionGen(t, keys, nonces, localKey, gasPriceMin, gasPriceMax, gasLimitMin, gasLimitMax) - gasValues[i] = float64(txs[i].tx.Gas()) - } +// gasValues[i] = float64(txs[i].tx.Gas()) +// } - mean, stddev := stat.MeanStdDev(gasValues, nil) - fmt.Fprintf(caseParams, " gasValues mean %d, stdev %d, %d-%d);", int64(mean), int64(stddev), int64(floats.Min(gasValues)), int64(floats.Max(gasValues))) +// mean, stddev := stat.MeanStdDev(gasValues, nil) +// fmt.Fprintf(caseParams, " gasValues mean %d, stdev %d, %d-%d);", int64(mean), int64(stddev), int64(floats.Min(gasValues)), int64(floats.Max(gasValues))) - return &transactionBatches{txs, totalTxs} - } -} +// return &transactionBatches{txs, totalTxs} +// } +// } -type txPoolRapidConfig struct { - gasLimit uint64 - avgBlockTxs uint64 +// type txPoolRapidConfig struct { +// gasLimit uint64 +// avgBlockTxs uint64 - minTxs int - maxTxs int +// minTxs int +// maxTxs int - minAccs int - maxAccs int +// minAccs int +// maxAccs int - // less tweakable, more like constants - gasPriceMin uint64 - gasPriceMax uint64 +// // less tweakable, more like constants +// gasPriceMin uint64 +// gasPriceMax uint64 - gasLimitMin uint64 - gasLimitMax uint64 +// gasLimitMin uint64 +// gasLimitMax uint64 - balance int64 +// balance int64 - blockTime time.Duration - maxEmptyBlocks int - maxStuckBlocks int -} +// blockTime time.Duration +// maxEmptyBlocks int +// maxStuckBlocks int +// } -func defaultTxPoolRapidConfig() txPoolRapidConfig { - gasLimit := uint64(30_000_000) - avgBlockTxs := gasLimit/params.TxGas + 1 - maxTxs := int(25 * avgBlockTxs) +// func defaultTxPoolRapidConfig() txPoolRapidConfig { +// gasLimit := uint64(30_000_000) +// avgBlockTxs := gasLimit/params.TxGas + 1 +// maxTxs := int(25 * avgBlockTxs) - return txPoolRapidConfig{ - gasLimit: gasLimit, +// return txPoolRapidConfig{ +// gasLimit: gasLimit, - avgBlockTxs: avgBlockTxs, +// avgBlockTxs: avgBlockTxs, - minTxs: 1, - maxTxs: maxTxs, +// minTxs: 1, +// maxTxs: maxTxs, - minAccs: 1, - maxAccs: maxTxs, +// minAccs: 1, +// maxAccs: maxTxs, - // less tweakable, more like constants - gasPriceMin: 1, - gasPriceMax: 1_000, +// // less tweakable, more like constants +// gasPriceMin: 1, +// gasPriceMax: 1_000, - gasLimitMin: params.TxGas, - gasLimitMax: gasLimit / 2, +// gasLimitMin: params.TxGas, +// gasLimitMax: gasLimit / 2, - balance: 0xffffffffffffff, +// balance: 0xffffffffffffff, - blockTime: 2 * time.Second, - maxEmptyBlocks: 10, - maxStuckBlocks: 10, - } -} +// blockTime: 2 * time.Second, +// maxEmptyBlocks: 10, +// maxStuckBlocks: 10, +// } +// } // TODO - Fix Later // TestSmallTxPool is not something to run in parallel as far it uses all CPUs @@ -4558,163 +4553,163 @@ func BenchmarkBigs(b *testing.B) { // common.NowMilliseconds(), time.Duration(mean), time.Duration(stddev), time.Duration(floats.Min(pendingDurationsFloat)), time.Duration(floats.Max(pendingDurationsFloat))) // } -func addTransactionsBatches(tb testing.TB, batches []types.Transactions, fn func(types.Transactions) error, done chan struct{}, timeoutDuration time.Duration, tickerDuration time.Duration, name string, thread int) { - tb.Helper() +// func addTransactionsBatches(tb testing.TB, batches []types.Transactions, fn func(types.Transactions) error, done chan struct{}, timeoutDuration time.Duration, tickerDuration time.Duration, name string, thread int) { +// tb.Helper() - tb.Logf("[%s] starting %s", common.NowMilliseconds(), name) +// tb.Logf("[%s] starting %s", common.NowMilliseconds(), name) - defer func() { - tb.Logf("[%s] stop %s", common.NowMilliseconds(), name) - }() +// defer func() { +// tb.Logf("[%s] stop %s", common.NowMilliseconds(), name) +// }() - for _, batch := range batches { - batch := batch +// for _, batch := range batches { +// batch := batch - select { - case <-done: - return - default: - } +// select { +// case <-done: +// return +// default: +// } - runWithTimeout(tb, func(_ chan struct{}) { - err := fn(batch) - if err != nil { - tb.Logf("[%s] %s error: %s", common.NowMilliseconds(), name, err) - } - }, done, name, timeoutDuration, 0, thread) +// runWithTimeout(tb, func(_ chan struct{}) { +// err := fn(batch) +// if err != nil { +// tb.Logf("[%s] %s error: %s", common.NowMilliseconds(), name, err) +// } +// }, done, name, timeoutDuration, 0, thread) - time.Sleep(tickerDuration) - } -} +// time.Sleep(tickerDuration) +// } +// } -func addTransactions(tb testing.TB, batches []types.Transactions, fn func(*types.Transaction) error, done chan struct{}, timeoutDuration time.Duration, tickerDuration time.Duration, name string, thread int) { - tb.Helper() +// func addTransactions(tb testing.TB, batches []types.Transactions, fn func(*types.Transaction) error, done chan struct{}, timeoutDuration time.Duration, tickerDuration time.Duration, name string, thread int) { +// tb.Helper() - tb.Logf("[%s] starting %s", common.NowMilliseconds(), name) +// tb.Logf("[%s] starting %s", common.NowMilliseconds(), name) - defer func() { - tb.Logf("[%s] stop %s", common.NowMilliseconds(), name) - }() +// defer func() { +// tb.Logf("[%s] stop %s", common.NowMilliseconds(), name) +// }() - for _, batch := range batches { - for _, tx := range batch { - tx := tx +// for _, batch := range batches { +// for _, tx := range batch { +// tx := tx - select { - case <-done: - return - default: - } +// select { +// case <-done: +// return +// default: +// } - runWithTimeout(tb, func(_ chan struct{}) { - err := fn(tx) - if err != nil { - tb.Logf("%s error: %s", name, err) - } - }, done, name, timeoutDuration, 0, thread) +// runWithTimeout(tb, func(_ chan struct{}) { +// err := fn(tx) +// if err != nil { +// tb.Logf("%s error: %s", name, err) +// } +// }, done, name, timeoutDuration, 0, thread) - time.Sleep(tickerDuration) - } +// time.Sleep(tickerDuration) +// } - time.Sleep(tickerDuration) - } -} +// time.Sleep(tickerDuration) +// } +// } -func getFnForBatches(fn func([]*types.Transaction) []error) func(types.Transactions) error { - return func(batch types.Transactions) error { - errs := fn(batch) - if len(errs) != 0 { - return errs[0] - } +// func getFnForBatches(fn func([]*types.Transaction) []error) func(types.Transactions) error { +// return func(batch types.Transactions) error { +// errs := fn(batch) +// if len(errs) != 0 { +// return errs[0] +// } - return nil - } -} +// return nil +// } +// } //nolint:unparam -func runWithTicker(tb testing.TB, fn func(c chan struct{}), done chan struct{}, name string, tickerDuration, timeoutDuration time.Duration, thread int) { - tb.Helper() +// func runWithTicker(tb testing.TB, fn func(c chan struct{}), done chan struct{}, name string, tickerDuration, timeoutDuration time.Duration, thread int) { +// tb.Helper() - select { - case <-done: - tb.Logf("[%s] Short path. finishing outer runWithTicker for %q, thread %d", common.NowMilliseconds(), name, thread) +// select { +// case <-done: +// tb.Logf("[%s] Short path. finishing outer runWithTicker for %q, thread %d", common.NowMilliseconds(), name, thread) - return - default: - } +// return +// default: +// } - defer func() { - tb.Logf("[%s] finishing outer runWithTicker for %q, thread %d", common.NowMilliseconds(), name, thread) - }() +// defer func() { +// tb.Logf("[%s] finishing outer runWithTicker for %q, thread %d", common.NowMilliseconds(), name, thread) +// }() - localTicker := time.NewTicker(tickerDuration) - defer localTicker.Stop() +// localTicker := time.NewTicker(tickerDuration) +// defer localTicker.Stop() - n := 0 +// n := 0 - for range localTicker.C { - select { - case <-done: - return - default: - } +// for range localTicker.C { +// select { +// case <-done: +// return +// default: +// } - runWithTimeout(tb, fn, done, name, timeoutDuration, n, thread) +// runWithTimeout(tb, fn, done, name, timeoutDuration, n, thread) - n++ - } -} +// n++ +// } +// } -func runWithTimeout(tb testing.TB, fn func(chan struct{}), outerDone chan struct{}, name string, timeoutDuration time.Duration, n, thread int) { - tb.Helper() +// func runWithTimeout(tb testing.TB, fn func(chan struct{}), outerDone chan struct{}, name string, timeoutDuration time.Duration, n, thread int) { +// tb.Helper() - select { - case <-outerDone: - tb.Logf("[%s] Short path. exiting inner runWithTimeout by outer exit event for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) +// select { +// case <-outerDone: +// tb.Logf("[%s] Short path. exiting inner runWithTimeout by outer exit event for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) - return - default: - } +// return +// default: +// } - timeout := time.NewTimer(timeoutDuration) - defer timeout.Stop() +// timeout := time.NewTimer(timeoutDuration) +// defer timeout.Stop() - doneCh := make(chan struct{}) +// doneCh := make(chan struct{}) - isError := new(int32) - *isError = 0 +// isError := new(int32) +// *isError = 0 - go func() { - defer close(doneCh) +// go func() { +// defer close(doneCh) - select { - case <-outerDone: - return - default: - fn(doneCh) - } - }() +// select { +// case <-outerDone: +// return +// default: +// fn(doneCh) +// } +// }() - const isDebug = false +// const isDebug = false - var stack string +// var stack string - select { - case <-outerDone: - tb.Logf("[%s] exiting inner runWithTimeout by outer exit event for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) - case <-doneCh: - // only for debug - //tb.Logf("[%s] exiting inner runWithTimeout by successful call for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) - case <-timeout.C: - atomic.StoreInt32(isError, 1) - - if isDebug { - stack = string(debug.Stack(true)) - } +// select { +// case <-outerDone: +// tb.Logf("[%s] exiting inner runWithTimeout by outer exit event for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) +// case <-doneCh: +// // only for debug +// //tb.Logf("[%s] exiting inner runWithTimeout by successful call for %q, thread %d, iteration %d", common.NowMilliseconds(), name, thread, n) +// case <-timeout.C: +// atomic.StoreInt32(isError, 1) + +// if isDebug { +// stack = string(debug.Stack(true)) +// } - tb.Errorf("[%s] %s timeouted, thread %d, iteration %d. Stack %s", common.NowMilliseconds(), name, thread, n, stack) - } -} +// tb.Errorf("[%s] %s timeouted, thread %d, iteration %d. Stack %s", common.NowMilliseconds(), name, thread, n, stack) +// } +// } // Benchmarks the speed of batch transaction insertion in case of multiple accounts. func BenchmarkMultiAccountBatchInsert(b *testing.B) { diff --git a/core/types/transaction.go b/core/types/transaction.go index 7af38f7b19..6f2fa21aa5 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -588,116 +588,3 @@ func (s *TxByPriceAndTime) Pop() interface{} { return x } - -// TransactionsByPriceAndNonce represents a set of transactions that can return -// transactions in a profit-maximizing sorted order, while supporting removing -// entire batches of transactions for non-executable accounts. -type TransactionsByPriceAndNonce struct { - txs map[common.Address]Transactions // Per account nonce-sorted list of transactions - heads TxByPriceAndTime // Next transaction for each unique account (price heap) - signer Signer // Signer for the set of transactions - baseFee *uint256.Int // Current base fee -} - -// NewTransactionsByPriceAndNonce creates a transaction set that can retrieve -// price sorted transactions in a nonce-honouring way. -// -// Note, the input map is reowned so the caller should not interact any more with -// if after providing it to the constructor. -/* -func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions, baseFee *big.Int) *TransactionsByPriceAndNonce { - // Initialize a price and received time based heap with the head transactions - heads := make(TxByPriceAndTime, 0, len(txs)) - for from, accTxs := range txs { - if len(accTxs) == 0 { - continue - } - - acc, _ := Sender(signer, accTxs[0]) - wrapped, err := NewTxWithMinerFee(accTxs[0], baseFee) - // Remove transaction if sender doesn't match from, or if wrapping fails. - if acc != from || err != nil { - delete(txs, from) - continue - } - heads = append(heads, wrapped) - txs[from] = accTxs[1:] - } - heap.Init(&heads) - - // Assemble and return the transaction set - return &TransactionsByPriceAndNonce{ - txs: txs, - heads: heads, - signer: signer, - baseFee: baseFee, - } -}*/ - -// func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions, baseFee *uint256.Int) *TransactionsByPriceAndNonce { -// // Initialize a price and received time based heap with the head transactions -// heads := make(TxByPriceAndTime, 0, len(txs)) - -// for from, accTxs := range txs { -// if len(accTxs) == 0 { -// continue -// } - -// acc, _ := Sender(signer, accTxs[0]) -// wrapped, err := NewTxWithMinerFee(accTxs[0], baseFee) - -// // Remove transaction if sender doesn't match from, or if wrapping fails. -// if acc != from || err != nil { -// delete(txs, from) -// continue -// } - -// heads = append(heads, wrapped) -// txs[from] = accTxs[1:] -// } - -// heap.Init(&heads) - -// // Assemble and return the transaction set -// return &TransactionsByPriceAndNonce{ -// txs: txs, -// heads: heads, -// signer: signer, -// baseFee: baseFee, -// } -// } - -// // Peek returns the next transaction by price. -// func (t *TransactionsByPriceAndNonce) Peek() *Transaction { -// if len(t.heads) == 0 { -// return nil -// } - -// return t.heads[0].tx -// } - -// // Shift replaces the current best head with the next one from the same account. -// func (t *TransactionsByPriceAndNonce) Shift() { -// acc, _ := Sender(t.signer, t.heads[0].tx) -// if txs, ok := t.txs[acc]; ok && len(txs) > 0 { -// if wrapped, err := NewTxWithMinerFee(txs[0], t.baseFee); err == nil { -// t.heads[0], t.txs[acc] = wrapped, txs[1:] -// heap.Fix(&t.heads, 0) - -// return -// } -// } - -// heap.Pop(&t.heads) -// } - -// func (t *TransactionsByPriceAndNonce) GetTxs() int { -// return len(t.txs) -// } - -// // Pop removes the best transaction, *not* replacing it with the next one from -// // the same account. This should be used when a transaction cannot be executed -// // and hence all subsequent ones should be discarded from the same account. -// func (t *TransactionsByPriceAndNonce) Pop() { -// heap.Pop(&t.heads) -// } diff --git a/eth/backend.go b/eth/backend.go index 0373538f2e..0d7ba78a09 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -146,11 +146,6 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { if err := pruner.RecoverPruning(stack.ResolvePath(""), chainDb); err != nil { log.Error("Failed to recover state", "error", err) } - // Transfer mining-related config to the ethash config. - chainConfig, err := core.LoadChainConfig(chainDb, config.Genesis) - if err != nil { - return nil, err - } // START: Bor changes eth := &Ethereum{ diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index 7b35bfb6eb..f6369f8f4b 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -894,7 +894,6 @@ func (d *Downloader) getFetchHeadersByNumber(p *peerConnection) func(number uint // In the rare scenario when we ended up on a long reorganisation (i.e. none of // the head links match), we do a binary search to find the common ancestor. func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header) (uint64, error) { - // Check the validity of peer from which the chain is to be downloaded if d.ChainValidator != nil { if _, err := d.IsValidPeer(d.getFetchHeadersByNumber(p)); err != nil { diff --git a/eth/downloader/downloader_test.go b/eth/downloader/downloader_test.go index 503e8dd93d..ca6202ac66 100644 --- a/eth/downloader/downloader_test.go +++ b/eth/downloader/downloader_test.go @@ -99,10 +99,6 @@ func newTesterWithNotification(t *testing.T, success func()) *downloadTester { return tester } -func (dl *downloadTester) setWhitelist(w ethereum.ChainValidator) { - dl.downloader.ChainValidator = w -} - // terminate aborts any operations on the embedded downloader and releases all // held resources. func (dl *downloadTester) terminate() { diff --git a/eth/filters/test_backend.go b/eth/filters/test_backend.go index 453d9b06a4..4118979b3c 100644 --- a/eth/filters/test_backend.go +++ b/eth/filters/test_backend.go @@ -96,7 +96,6 @@ func (b *TestBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*type } func (b *TestBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) { - if number := rawdb.ReadHeaderNumber(b.DB, hash); number != nil { block := rawdb.ReadBlock(b.DB, hash, *number) return rawdb.ReadReceipts(b.DB, hash, *number, block.Time(), params.TestChainConfig), nil diff --git a/eth/handler_bor_test.go b/eth/handler_bor_test.go index ac04ad26f8..7ceab1fc64 100644 --- a/eth/handler_bor_test.go +++ b/eth/handler_bor_test.go @@ -146,12 +146,6 @@ func fetchMilestoneTest(t *testing.T, heimdall *mockHeimdall, bor *bor.Bor, hand require.Equal(t, milestones[len(milestones)-1].Hash, hash) } -func getMockFetchCheckpointFn(number int64, err error) func(ctx context.Context) (int64, error) { - return func(_ context.Context) (int64, error) { - return number, err - } -} - func createMockCheckpoints(count int) []*checkpoint.Checkpoint { var ( checkpoints []*checkpoint.Checkpoint = make([]*checkpoint.Checkpoint, count) diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 7e215330c7..d309fe7cf7 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -24,7 +24,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "math/big" "os" "path/filepath" @@ -888,7 +887,7 @@ txloop: if *config.BorTraceEnabled { callmsg := prepareCallMessage(*msg) // nolint : contextcheck - if _, err := statefull.ApplyBorMessage(*vmenv, callmsg); err != nil { + if _, err := statefull.ApplyBorMessage(vmenv, callmsg); err != nil { failed = err break txloop } @@ -957,7 +956,7 @@ txloop: } // make sure that the file exists and write IOdump - err = ioutil.WriteFile(filepath.Join(path, "data.csv"), []byte(fmt.Sprint(IOdump)), 0600) + err = os.WriteFile(filepath.Join(path, "data.csv"), []byte(fmt.Sprint(IOdump)), 0600) if err != nil { return nil, err } @@ -1095,7 +1094,7 @@ func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block if stateSyncPresent && i == len(txs)-1 { if *config.BorTraceEnabled { callmsg := prepareCallMessage(*msg) - _, err = statefull.ApplyBorMessage(*vmenv, callmsg) + _, err = statefull.ApplyBorMessage(vmenv, callmsg) if writer != nil { writer.Flush() @@ -1340,7 +1339,7 @@ func (api *API) traceTx(ctx context.Context, message *core.Message, txctx *Conte if *config.BorTx { callmsg := prepareCallMessage(*message) // nolint : contextcheck - if _, err := statefull.ApplyBorMessage(*vmenv, callmsg); err != nil { + if _, err := statefull.ApplyBorMessage(vmenv, callmsg); err != nil { return nil, fmt.Errorf("tracing failed: %w", err) } } else { diff --git a/eth/tracers/api_bor.go b/eth/tracers/api_bor.go index 65db8a1db2..565148c384 100644 --- a/eth/tracers/api_bor.go +++ b/eth/tracers/api_bor.go @@ -92,7 +92,7 @@ func (api *API) traceBorBlock(ctx context.Context, block *types.Block, config *T if borTx { callmsg := prepareCallMessage(*message) - execRes, err = statefull.ApplyBorMessage(*vmenv, callmsg) + execRes, err = statefull.ApplyBorMessage(vmenv, callmsg) } else { execRes, err = core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.GasLimit), nil) } diff --git a/ethclient/ethclient_test.go b/ethclient/ethclient_test.go index df8a6275f8..93f95c3595 100644 --- a/ethclient/ethclient_test.go +++ b/ethclient/ethclient_test.go @@ -17,22 +17,13 @@ package ethclient import ( - "bytes" - "context" "errors" "math/big" "reflect" "testing" - "time" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/consensus/ethash" - "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/params" - "github.com/ethereum/go-ethereum/rpc" ) // Verify that Client implements the ethereum interfaces. @@ -177,35 +168,35 @@ func TestToFilterArg(t *testing.T) { } } -var ( - testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - testAddr = crypto.PubkeyToAddress(testKey.PublicKey) - testBalance = big.NewInt(2e15) -) - -var genesis = &core.Genesis{ - Config: params.AllEthashProtocolChanges, - Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}}, - ExtraData: []byte("test genesis"), - Timestamp: 9000, - BaseFee: big.NewInt(params.InitialBaseFee), -} +// var ( +// testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") +// testAddr = crypto.PubkeyToAddress(testKey.PublicKey) +// testBalance = big.NewInt(2e15) +// ) + +// var genesis = &core.Genesis{ +// Config: params.AllEthashProtocolChanges, +// Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}}, +// ExtraData: []byte("test genesis"), +// Timestamp: 9000, +// BaseFee: big.NewInt(params.InitialBaseFee), +// } -var testTx1 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{ - Nonce: 0, - Value: big.NewInt(12), - GasPrice: big.NewInt(params.InitialBaseFee), - Gas: params.TxGas, - To: &common.Address{2}, -}) - -var testTx2 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{ - Nonce: 1, - Value: big.NewInt(8), - GasPrice: big.NewInt(params.InitialBaseFee), - Gas: params.TxGas, - To: &common.Address{2}, -}) +// var testTx1 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{ +// Nonce: 0, +// Value: big.NewInt(12), +// GasPrice: big.NewInt(params.InitialBaseFee), +// Gas: params.TxGas, +// To: &common.Address{2}, +// }) + +// var testTx2 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), &types.LegacyTx{ +// Nonce: 1, +// Value: big.NewInt(8), +// GasPrice: big.NewInt(params.InitialBaseFee), +// Gas: params.TxGas, +// To: &common.Address{2}, +// }) // func newTestBackend(t *testing.T) (*node.Node, []*types.Block) { // // Generate test chain. @@ -232,21 +223,21 @@ var testTx2 = types.MustSignNewTx(testKey, types.LatestSigner(genesis.Config), & // return n, blocks // } -func generateTestChain() []*types.Block { - generate := func(i int, g *core.BlockGen) { - g.OffsetTime(5) - g.SetExtra([]byte("test")) +// func generateTestChain() []*types.Block { +// generate := func(i int, g *core.BlockGen) { +// g.OffsetTime(5) +// g.SetExtra([]byte("test")) - if i == 1 { - // Test transactions are included in block #2. - g.AddTx(testTx1) - g.AddTx(testTx2) - } - } - _, blocks, _ := core.GenerateChainWithGenesis(genesis, ethash.NewFaker(), 2, generate) +// if i == 1 { +// // Test transactions are included in block #2. +// g.AddTx(testTx1) +// g.AddTx(testTx2) +// } +// } +// _, blocks, _ := core.GenerateChainWithGenesis(genesis, ethash.NewFaker(), 2, generate) - return append([]*types.Block{genesis.ToBlock()}, blocks...) -} +// return append([]*types.Block{genesis.ToBlock()}, blocks...) +// } func TestEthClient(t *testing.T) { t.Skip("bor due to burn contract") @@ -296,457 +287,457 @@ func TestEthClient(t *testing.T) { // } } -func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) { - tests := map[string]struct { - block *big.Int - want *types.Header - wantErr error - }{ - "genesis": { - block: big.NewInt(0), - want: chain[0].Header(), - }, - "first_block": { - block: big.NewInt(1), - want: chain[1].Header(), - }, - "future_block": { - block: big.NewInt(1000000000), - want: nil, - wantErr: ethereum.NotFound, - }, - } - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - ec := NewClient(client) - - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - - got, err := ec.HeaderByNumber(ctx, tt.block) - if !errors.Is(err, tt.wantErr) { - t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr) - } - - if got != nil && got.Number != nil && got.Number.Sign() == 0 { - got.Number = big.NewInt(0) // hack to make DeepEqual work - } - - if !reflect.DeepEqual(got, tt.want) { - t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want) - } - }) - } -} - -func testBalanceAt(t *testing.T, client *rpc.Client) { - tests := map[string]struct { - account common.Address - block *big.Int - want *big.Int - wantErr error - }{ - "valid_account_genesis": { - account: testAddr, - block: big.NewInt(0), - want: testBalance, - }, - "valid_account": { - account: testAddr, - block: big.NewInt(1), - want: testBalance, - }, - "non_existent_account": { - account: common.Address{1}, - block: big.NewInt(1), - want: big.NewInt(0), - }, - "future_block": { - account: testAddr, - block: big.NewInt(1000000000), - want: big.NewInt(0), - wantErr: errors.New("header not found"), - }, - } - for name, tt := range tests { - t.Run(name, func(t *testing.T) { - ec := NewClient(client) +// func testHeader(t *testing.T, chain []*types.Block, client *rpc.Client) { +// tests := map[string]struct { +// block *big.Int +// want *types.Header +// wantErr error +// }{ +// "genesis": { +// block: big.NewInt(0), +// want: chain[0].Header(), +// }, +// "first_block": { +// block: big.NewInt(1), +// want: chain[1].Header(), +// }, +// "future_block": { +// block: big.NewInt(1000000000), +// want: nil, +// wantErr: ethereum.NotFound, +// }, +// } +// for name, tt := range tests { +// t.Run(name, func(t *testing.T) { +// ec := NewClient(client) + +// ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) +// defer cancel() + +// got, err := ec.HeaderByNumber(ctx, tt.block) +// if !errors.Is(err, tt.wantErr) { +// t.Fatalf("HeaderByNumber(%v) error = %q, want %q", tt.block, err, tt.wantErr) +// } + +// if got != nil && got.Number != nil && got.Number.Sign() == 0 { +// got.Number = big.NewInt(0) // hack to make DeepEqual work +// } + +// if !reflect.DeepEqual(got, tt.want) { +// t.Fatalf("HeaderByNumber(%v)\n = %v\nwant %v", tt.block, got, tt.want) +// } +// }) +// } +// } - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() +// func testBalanceAt(t *testing.T, client *rpc.Client) { +// tests := map[string]struct { +// account common.Address +// block *big.Int +// want *big.Int +// wantErr error +// }{ +// "valid_account_genesis": { +// account: testAddr, +// block: big.NewInt(0), +// want: testBalance, +// }, +// "valid_account": { +// account: testAddr, +// block: big.NewInt(1), +// want: testBalance, +// }, +// "non_existent_account": { +// account: common.Address{1}, +// block: big.NewInt(1), +// want: big.NewInt(0), +// }, +// "future_block": { +// account: testAddr, +// block: big.NewInt(1000000000), +// want: big.NewInt(0), +// wantErr: errors.New("header not found"), +// }, +// } +// for name, tt := range tests { +// t.Run(name, func(t *testing.T) { +// ec := NewClient(client) + +// ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) +// defer cancel() + +// got, err := ec.BalanceAt(ctx, tt.account, tt.block) +// if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) { +// t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr) +// } + +// if got.Cmp(tt.want) != 0 { +// t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want) +// } +// }) +// } +// } - got, err := ec.BalanceAt(ctx, tt.account, tt.block) - if tt.wantErr != nil && (err == nil || err.Error() != tt.wantErr.Error()) { - t.Fatalf("BalanceAt(%x, %v) error = %q, want %q", tt.account, tt.block, err, tt.wantErr) - } +// func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) - if got.Cmp(tt.want) != 0 { - t.Fatalf("BalanceAt(%x, %v) = %v, want %v", tt.account, tt.block, got, tt.want) - } - }) - } -} - -func testTransactionInBlockInterrupted(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // Get current block by number. +// block, err := ec.BlockByNumber(context.Background(), nil) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // Get current block by number. - block, err := ec.BlockByNumber(context.Background(), nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// // Test tx in block interrupted. +// ctx, cancel := context.WithCancel(context.Background()) +// cancel() - // Test tx in block interrupted. - ctx, cancel := context.WithCancel(context.Background()) - cancel() +// tx, err := ec.TransactionInBlock(ctx, block.Hash(), 0) +// if tx != nil { +// t.Fatal("transaction should be nil") +// } - tx, err := ec.TransactionInBlock(ctx, block.Hash(), 0) - if tx != nil { - t.Fatal("transaction should be nil") - } +// if err == nil || err == ethereum.NotFound { +// t.Fatal("error should not be nil/notfound") +// } - if err == nil || err == ethereum.NotFound { - t.Fatal("error should not be nil/notfound") - } +// // Test tx in block not found. +// if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 20); err != ethereum.NotFound { +// t.Fatal("error should be ethereum.NotFound") +// } +// } - // Test tx in block not found. - if _, err := ec.TransactionInBlock(context.Background(), block.Hash(), 20); err != ethereum.NotFound { - t.Fatal("error should be ethereum.NotFound") - } -} +// func testChainID(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testChainID(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// id, err := ec.ChainID(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - id, err := ec.ChainID(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 { +// t.Fatalf("ChainID returned wrong number: %+v", id) +// } +// } - if id == nil || id.Cmp(params.AllEthashProtocolChanges.ChainID) != 0 { - t.Fatalf("ChainID returned wrong number: %+v", id) - } -} +// func testGetBlock(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testGetBlock(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // Get current block number +// blockNumber, err := ec.BlockNumber(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // Get current block number - blockNumber, err := ec.BlockNumber(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if blockNumber != 2 { +// t.Fatalf("BlockNumber returned wrong number: %d", blockNumber) +// } +// // Get current block by number +// block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if blockNumber != 2 { - t.Fatalf("BlockNumber returned wrong number: %d", blockNumber) - } - // Get current block by number - block, err := ec.BlockByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if block.NumberU64() != blockNumber { +// t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64()) +// } +// // Get current block by hash +// blockH, err := ec.BlockByHash(context.Background(), block.Hash()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if block.NumberU64() != blockNumber { - t.Fatalf("BlockByNumber returned wrong block: want %d got %d", blockNumber, block.NumberU64()) - } - // Get current block by hash - blockH, err := ec.BlockByHash(context.Background(), block.Hash()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if block.Hash() != blockH.Hash() { +// t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex()) +// } +// // Get header by number +// header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if block.Hash() != blockH.Hash() { - t.Fatalf("BlockByHash returned wrong block: want %v got %v", block.Hash().Hex(), blockH.Hash().Hex()) - } - // Get header by number - header, err := ec.HeaderByNumber(context.Background(), new(big.Int).SetUint64(blockNumber)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if block.Header().Hash() != header.Hash() { +// t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex()) +// } +// // Get header by hash +// headerH, err := ec.HeaderByHash(context.Background(), block.Hash()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if block.Header().Hash() != header.Hash() { - t.Fatalf("HeaderByNumber returned wrong header: want %v got %v", block.Header().Hash().Hex(), header.Hash().Hex()) - } - // Get header by hash - headerH, err := ec.HeaderByHash(context.Background(), block.Hash()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if block.Header().Hash() != headerH.Hash() { +// t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex()) +// } +// } - if block.Header().Hash() != headerH.Hash() { - t.Fatalf("HeaderByHash returned wrong header: want %v got %v", block.Header().Hash().Hex(), headerH.Hash().Hex()) - } -} +// func testStatusFunctions(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testStatusFunctions(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // Sync progress +// progress, err := ec.SyncProgress(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // Sync progress - progress, err := ec.SyncProgress(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if progress != nil { +// t.Fatalf("unexpected progress: %v", progress) +// } - if progress != nil { - t.Fatalf("unexpected progress: %v", progress) - } +// // NetworkID +// networkID, err := ec.NetworkID(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // NetworkID - networkID, err := ec.NetworkID(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if networkID.Cmp(big.NewInt(0)) != 0 { +// t.Fatalf("unexpected networkID: %v", networkID) +// } - if networkID.Cmp(big.NewInt(0)) != 0 { - t.Fatalf("unexpected networkID: %v", networkID) - } +// // SuggestGasPrice +// gasPrice, err := ec.SuggestGasPrice(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // SuggestGasPrice - gasPrice, err := ec.SuggestGasPrice(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if gasPrice.Cmp(big.NewInt(1000000000)) != 0 { +// t.Fatalf("unexpected gas price: %v", gasPrice) +// } - if gasPrice.Cmp(big.NewInt(1000000000)) != 0 { - t.Fatalf("unexpected gas price: %v", gasPrice) - } +// // SuggestGasTipCap +// gasTipCap, err := ec.SuggestGasTipCap(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // SuggestGasTipCap - gasTipCap, err := ec.SuggestGasTipCap(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if gasTipCap.Cmp(big.NewInt(234375000)) != 0 { +// t.Fatalf("unexpected gas tip cap: %v", gasTipCap) +// } - if gasTipCap.Cmp(big.NewInt(234375000)) != 0 { - t.Fatalf("unexpected gas tip cap: %v", gasTipCap) - } +// // FeeHistory +// history, err := ec.FeeHistory(context.Background(), 1, big.NewInt(2), []float64{95, 99}) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // FeeHistory - history, err := ec.FeeHistory(context.Background(), 1, big.NewInt(2), []float64{95, 99}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// want := ðereum.FeeHistory{ +// OldestBlock: big.NewInt(2), +// Reward: [][]*big.Int{ +// { +// big.NewInt(234375000), +// big.NewInt(234375000), +// }, +// }, +// BaseFee: []*big.Int{ +// big.NewInt(765625000), +// big.NewInt(671627818), +// }, +// GasUsedRatio: []float64{0.008912678667376286}, +// } +// if !reflect.DeepEqual(history, want) { +// t.Fatalf("FeeHistory result doesn't match expected: (got: %v, want: %v)", history, want) +// } +// } - want := ðereum.FeeHistory{ - OldestBlock: big.NewInt(2), - Reward: [][]*big.Int{ - { - big.NewInt(234375000), - big.NewInt(234375000), - }, - }, - BaseFee: []*big.Int{ - big.NewInt(765625000), - big.NewInt(671627818), - }, - GasUsedRatio: []float64{0.008912678667376286}, - } - if !reflect.DeepEqual(history, want) { - t.Fatalf("FeeHistory result doesn't match expected: (got: %v, want: %v)", history, want) - } -} +// func testCallContractAtHash(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testCallContractAtHash(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // EstimateGas +// msg := ethereum.CallMsg{ +// From: testAddr, +// To: &common.Address{}, +// Gas: 21000, +// Value: big.NewInt(1), +// } - // EstimateGas - msg := ethereum.CallMsg{ - From: testAddr, - To: &common.Address{}, - Gas: 21000, - Value: big.NewInt(1), - } +// gas, err := ec.EstimateGas(context.Background(), msg) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - gas, err := ec.EstimateGas(context.Background(), msg) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if gas != 21000 { +// t.Fatalf("unexpected gas price: %v", gas) +// } - if gas != 21000 { - t.Fatalf("unexpected gas price: %v", gas) - } +// block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1)) +// if err != nil { +// t.Fatalf("BlockByNumber error: %v", err) +// } +// // CallContract +// if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil { +// t.Fatalf("unexpected error: %v", err) +// } +// } - block, err := ec.HeaderByNumber(context.Background(), big.NewInt(1)) - if err != nil { - t.Fatalf("BlockByNumber error: %v", err) - } - // CallContract - if _, err := ec.CallContractAtHash(context.Background(), msg, block.Hash()); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} +// func testCallContract(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testCallContract(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // EstimateGas +// msg := ethereum.CallMsg{ +// From: testAddr, +// To: &common.Address{}, +// Gas: 21000, +// Value: big.NewInt(1), +// } - // EstimateGas - msg := ethereum.CallMsg{ - From: testAddr, - To: &common.Address{}, - Gas: 21000, - Value: big.NewInt(1), - } +// gas, err := ec.EstimateGas(context.Background(), msg) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - gas, err := ec.EstimateGas(context.Background(), msg) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if gas != 21000 { +// t.Fatalf("unexpected gas price: %v", gas) +// } +// // CallContract +// if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil { +// t.Fatalf("unexpected error: %v", err) +// } +// // PendingCallContract +// if _, err := ec.PendingCallContract(context.Background(), msg); err != nil { +// t.Fatalf("unexpected error: %v", err) +// } +// } - if gas != 21000 { - t.Fatalf("unexpected gas price: %v", gas) - } - // CallContract - if _, err := ec.CallContract(context.Background(), msg, big.NewInt(1)); err != nil { - t.Fatalf("unexpected error: %v", err) - } - // PendingCallContract - if _, err := ec.PendingCallContract(context.Background(), msg); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} +// func testAtFunctions(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) -func testAtFunctions(t *testing.T, client *rpc.Client) { - ec := NewClient(client) +// // send a transaction for some interesting pending status +// sendTransaction(ec) +// time.Sleep(100 * time.Millisecond) - // send a transaction for some interesting pending status - sendTransaction(ec) - time.Sleep(100 * time.Millisecond) +// // Check pending transaction count +// pending, err := ec.PendingTransactionCount(context.Background()) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - // Check pending transaction count - pending, err := ec.PendingTransactionCount(context.Background()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if pending != 1 { +// t.Fatalf("unexpected pending, wanted 1 got: %v", pending) +// } +// // Query balance +// balance, err := ec.BalanceAt(context.Background(), testAddr, nil) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if pending != 1 { - t.Fatalf("unexpected pending, wanted 1 got: %v", pending) - } - // Query balance - balance, err := ec.BalanceAt(context.Background(), testAddr, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - penBalance, err := ec.PendingBalanceAt(context.Background(), testAddr) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if balance.Cmp(penBalance) == 0 { +// t.Fatalf("unexpected balance: %v %v", balance, penBalance) +// } +// // NonceAt +// nonce, err := ec.NonceAt(context.Background(), testAddr, nil) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if balance.Cmp(penBalance) == 0 { - t.Fatalf("unexpected balance: %v %v", balance, penBalance) - } - // NonceAt - nonce, err := ec.NonceAt(context.Background(), testAddr, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// penNonce, err := ec.PendingNonceAt(context.Background(), testAddr) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - penNonce, err := ec.PendingNonceAt(context.Background(), testAddr) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if penNonce != nonce+1 { +// t.Fatalf("unexpected nonce: %v %v", nonce, penNonce) +// } +// // StorageAt +// storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if penNonce != nonce+1 { - t.Fatalf("unexpected nonce: %v %v", nonce, penNonce) - } - // StorageAt - storage, err := ec.StorageAt(context.Background(), testAddr, common.Hash{}, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{}) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - penStorage, err := ec.PendingStorageAt(context.Background(), testAddr, common.Hash{}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if !bytes.Equal(storage, penStorage) { +// t.Fatalf("unexpected storage: %v %v", storage, penStorage) +// } +// // CodeAt +// code, err := ec.CodeAt(context.Background(), testAddr, nil) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - if !bytes.Equal(storage, penStorage) { - t.Fatalf("unexpected storage: %v %v", storage, penStorage) - } - // CodeAt - code, err := ec.CodeAt(context.Background(), testAddr, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// penCode, err := ec.PendingCodeAt(context.Background(), testAddr) +// if err != nil { +// t.Fatalf("unexpected error: %v", err) +// } - penCode, err := ec.PendingCodeAt(context.Background(), testAddr) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } +// if !bytes.Equal(code, penCode) { +// t.Fatalf("unexpected code: %v %v", code, penCode) +// } +// } - if !bytes.Equal(code, penCode) { - t.Fatalf("unexpected code: %v %v", code, penCode) - } -} +// func testTransactionSender(t *testing.T, client *rpc.Client) { +// ec := NewClient(client) +// ctx := context.Background() -func testTransactionSender(t *testing.T, client *rpc.Client) { - ec := NewClient(client) - ctx := context.Background() +// // Retrieve testTx1 via RPC. +// block2, err := ec.HeaderByNumber(ctx, big.NewInt(2)) +// if err != nil { +// t.Fatal("can't get block 1:", err) +// } - // Retrieve testTx1 via RPC. - block2, err := ec.HeaderByNumber(ctx, big.NewInt(2)) - if err != nil { - t.Fatal("can't get block 1:", err) - } +// tx1, err := ec.TransactionInBlock(ctx, block2.Hash(), 0) +// if err != nil { +// t.Fatal("can't get tx:", err) +// } - tx1, err := ec.TransactionInBlock(ctx, block2.Hash(), 0) - if err != nil { - t.Fatal("can't get tx:", err) - } +// if tx1.Hash() != testTx1.Hash() { +// t.Fatalf("wrong tx hash %v, want %v", tx1.Hash(), testTx1.Hash()) +// } - if tx1.Hash() != testTx1.Hash() { - t.Fatalf("wrong tx hash %v, want %v", tx1.Hash(), testTx1.Hash()) - } +// // The sender address is cached in tx1, so no additional RPC should be required in +// // TransactionSender. Ensure the server is not asked by canceling the context here. +// canceledCtx, cancel := context.WithCancel(context.Background()) +// cancel() - // The sender address is cached in tx1, so no additional RPC should be required in - // TransactionSender. Ensure the server is not asked by canceling the context here. - canceledCtx, cancel := context.WithCancel(context.Background()) - cancel() +// sender1, err := ec.TransactionSender(canceledCtx, tx1, block2.Hash(), 0) +// if err != nil { +// t.Fatal(err) +// } - sender1, err := ec.TransactionSender(canceledCtx, tx1, block2.Hash(), 0) - if err != nil { - t.Fatal(err) - } +// if sender1 != testAddr { +// t.Fatal("wrong sender:", sender1) +// } - if sender1 != testAddr { - t.Fatal("wrong sender:", sender1) - } +// // Now try to get the sender of testTx2, which was not fetched through RPC. +// // TransactionSender should query the server here. +// sender2, err := ec.TransactionSender(ctx, testTx2, block2.Hash(), 1) +// if err != nil { +// t.Fatal(err) +// } - // Now try to get the sender of testTx2, which was not fetched through RPC. - // TransactionSender should query the server here. - sender2, err := ec.TransactionSender(ctx, testTx2, block2.Hash(), 1) - if err != nil { - t.Fatal(err) - } +// if sender2 != testAddr { +// t.Fatal("wrong sender:", sender2) +// } +// } - if sender2 != testAddr { - t.Fatal("wrong sender:", sender2) - } -} +// func sendTransaction(ec *Client) error { +// chainID, err := ec.ChainID(context.Background()) +// if err != nil { +// return err +// } -func sendTransaction(ec *Client) error { - chainID, err := ec.ChainID(context.Background()) - if err != nil { - return err - } +// nonce, err := ec.PendingNonceAt(context.Background(), testAddr) +// if err != nil { +// return err +// } - nonce, err := ec.PendingNonceAt(context.Background(), testAddr) - if err != nil { - return err - } +// signer := types.LatestSignerForChainID(chainID) - signer := types.LatestSignerForChainID(chainID) - - tx, err := types.SignNewTx(testKey, signer, &types.LegacyTx{ - Nonce: nonce, - To: &common.Address{2}, - Value: big.NewInt(1), - Gas: 22000, - GasPrice: big.NewInt(params.InitialBaseFee), - }) - if err != nil { - return err - } +// tx, err := types.SignNewTx(testKey, signer, &types.LegacyTx{ +// Nonce: nonce, +// To: &common.Address{2}, +// Value: big.NewInt(1), +// Gas: 22000, +// GasPrice: big.NewInt(params.InitialBaseFee), +// }) +// if err != nil { +// return err +// } - return ec.SendTransaction(context.Background(), tx) -} +// return ec.SendTransaction(context.Background(), tx) +// } diff --git a/ethdb/database.go b/ethdb/database.go index 10c248eba1..095af6bf79 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -180,6 +180,7 @@ type AncientStore interface { // Database contains all the methods required by the high level database to not // only access the key-value data store but also the chain freezer. +// //go:generate mockgen -destination=../eth/filters/IDatabase.go -package=filters . Database type Database interface { Reader diff --git a/internal/cli/command.go b/internal/cli/command.go index 95f7776df6..9039d7d222 100644 --- a/internal/cli/command.go +++ b/internal/cli/command.go @@ -13,6 +13,7 @@ import ( "github.com/mitchellh/cli" "github.com/ryanuber/columnize" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" ) const ( @@ -222,7 +223,7 @@ func (m *Meta2) NewFlagSet(n string) *flagset.Flagset { } func (m *Meta2) Conn() (*grpc.ClientConn, error) { - conn, err := grpc.Dial(m.addr, grpc.WithInsecure()) + conn, err := grpc.Dial(m.addr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return nil, fmt.Errorf("failed to connect to server: %v", err) } diff --git a/internal/cli/debug.go b/internal/cli/debug.go index 9b3d224699..baa29c8721 100644 --- a/internal/cli/debug.go +++ b/internal/cli/debug.go @@ -5,7 +5,6 @@ import ( "compress/gzip" "fmt" "io" - "io/ioutil" "os" "os/signal" "path/filepath" @@ -61,8 +60,8 @@ func (d *DebugCommand) MarkDown() string { func (c *DebugCommand) Help() string { return `Usage: bor debug - This command takes a debug dump of the running client. - + This command takes a debug dump of the running client. + Get the pprof traces: $ bor debug pprof @@ -107,7 +106,7 @@ func (d *debugEnv) init() error { } } else { // Generate temp directory - tmp, err = ioutil.TempDir(os.TempDir(), d.name) + tmp, err = os.MkdirTemp(os.TempDir(), d.name) if err != nil { return fmt.Errorf("error creating tmp directory: %s", err.Error()) } @@ -188,7 +187,7 @@ func (d *debugEnv) writeJSON(name string, msg protoreflect.ProtoMessage) error { return err } - if err := ioutil.WriteFile(filepath.Join(d.dst, name), data, 0600); err != nil { + if err := os.WriteFile(filepath.Join(d.dst, name), data, 0600); err != nil { return fmt.Errorf("failed to write status: %v", err) } diff --git a/internal/cli/server/config.go b/internal/cli/server/config.go index 5a33ff3d75..607bcb8978 100644 --- a/internal/cli/server/config.go +++ b/internal/cli/server/config.go @@ -3,7 +3,6 @@ package server import ( "crypto/ecdsa" "fmt" - "io/ioutil" "math" "math/big" "os" @@ -1093,7 +1092,7 @@ func (c *Config) buildEth(stack *node.Node, accountManager *accounts.Manager) (* mem.Total = 2 * 1024 * 1024 * 1024 } - allowance := uint64(mem.Total / 1024 / 1024 / 3) + allowance := mem.Total / 1024 / 1024 / 3 if cache > allowance { log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) cache = allowance @@ -1525,7 +1524,7 @@ func Hostname() string { } func MakePasswordListFromFile(path string) ([]string, error) { - text, err := ioutil.ReadFile(path) + text, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("failed to read password file: %v", err) } diff --git a/internal/cli/server/server_test.go b/internal/cli/server/server_test.go index ab14c31a5d..6c52ae8a14 100644 --- a/internal/cli/server/server_test.go +++ b/internal/cli/server/server_test.go @@ -1,35 +1,12 @@ package server import ( - "fmt" - "net" - "sync/atomic" "testing" "time" - "github.com/ethereum/go-ethereum/log" - "github.com/stretchr/testify/assert" ) -var initialPort uint64 = 61000 - -// nextPort gives the next available port starting from 60000 -func nextPort() uint64 { - log.Info("Checking for new port", "current", initialPort) - port := atomic.AddUint64(&initialPort, 1) - addr := fmt.Sprintf("localhost:%d", port) - - lis, err := net.Listen("tcp", addr) - if err == nil { - lis.Close() - - return port - } else { - return nextPort() - } -} - func TestServer_DeveloperMode(t *testing.T) { t.Parallel() @@ -49,7 +26,7 @@ func TestServer_DeveloperMode(t *testing.T) { // record the initial block number blockNumber := server.backend.BlockChain().CurrentBlock().Number.Int64() - var i int64 = 0 + var i int64 for i = 0; i < 3; i++ { // We expect the node to mine blocks every `config.Developer.Period` time period time.Sleep(time.Duration(config.Developer.Period) * time.Second) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index d0de59c873..28649316e3 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1811,17 +1811,6 @@ func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.By return blob } -// newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation. -func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash, config *params.ChainConfig, db ethdb.Database) *RPCTransaction { - for idx, tx := range b.Transactions() { - if tx.Hash() == hash { - return newRPCTransactionFromBlockIndex(b, uint64(idx), config, db) - } - } - - return nil -} - // accessListResult returns an optional accesslist // It's the result of the `debug_createAccessList` RPC call. // It contains an error if the transaction itself failed. diff --git a/miner/miner_test.go b/miner/miner_test.go index ef68bb31cf..45f086e801 100644 --- a/miner/miner_test.go +++ b/miner/miner_test.go @@ -19,24 +19,15 @@ package miner import ( "errors" - "math/big" "testing" "time" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/consensus/clique" "github.com/ethereum/go-ethereum/core" - "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/txpool" - "github.com/ethereum/go-ethereum/core/txpool/legacypool" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" - "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth/downloader" - "github.com/ethereum/go-ethereum/event" - "github.com/ethereum/go-ethereum/params" - "github.com/ethereum/go-ethereum/trie" ) type mockBackend struct { @@ -68,36 +59,6 @@ func (m *mockBackend) StateAtBlock(block *types.Block, reexec uint64, base *stat return nil, errors.New("not supported") } -type testBlockChain struct { - config *params.ChainConfig - statedb *state.StateDB - gasLimit uint64 - chainHeadFeed *event.Feed -} - -func (bc *testBlockChain) Config() *params.ChainConfig { - return bc.config -} - -func (bc *testBlockChain) CurrentBlock() *types.Header { - return &types.Header{ - Number: new(big.Int), - GasLimit: bc.gasLimit, - } -} - -func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block { - return types.NewBlock(bc.CurrentBlock(), nil, nil, nil, trie.NewStackTrie(nil)) -} - -func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) { - return bc.statedb, nil -} - -func (bc *testBlockChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { - return bc.chainHeadFeed.Subscribe(ch) -} - func TestMiner(t *testing.T) { t.Parallel() @@ -338,76 +299,76 @@ func waitForMiningState(t *testing.T, m *Miner, mining bool) { t.Fatalf("Mining() == %t, want %t", state, mining) } -func minerTestGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *core.Genesis { - config := *params.AllCliqueProtocolChanges - config.Clique = ¶ms.CliqueConfig{ - Period: period, - Epoch: config.Clique.Epoch, - } - - // Assemble and return the genesis with the precompiles and faucet pre-funded - return &core.Genesis{ - Config: &config, - ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), - GasLimit: gasLimit, - BaseFee: big.NewInt(params.InitialBaseFee), - Difficulty: big.NewInt(1), - Alloc: map[common.Address]core.GenesisAccount{ - common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover - common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 - common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD - common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity - common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp - common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd - common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul - common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing - common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b - faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, - }, - } -} - -func createMiner(t *testing.T) (*Miner, *event.TypeMux, func(skipMiner bool)) { - t.Helper() - - // Create Ethash config - config := Config{ - Etherbase: common.HexToAddress("123456789"), - } - // Create chainConfig - chainDB := rawdb.NewMemoryDatabase() - genesis := minerTestGenesisBlock(15, 11_500_000, common.HexToAddress("12345")) - chainConfig, _, err := core.SetupGenesisBlock(chainDB, trie.NewDatabase(chainDB), genesis) - if err != nil { - t.Fatalf("can't create new chain config: %v", err) - } - // Create consensus engine - engine := clique.New(chainConfig.Clique, chainDB) - // Create Ethereum backend - bc, err := core.NewBlockChain(chainDB, nil, genesis, nil, engine, vm.Config{}, nil, nil, nil) - if err != nil { - t.Fatalf("can't create new chain %v", err) - } - statedb, _ := state.New(types.EmptyRootHash, state.NewDatabase(chainDB), nil) - blockchain := &testBlockChain{chainConfig, statedb, 10000000, new(event.Feed)} - - pool := legacypool.New(testTxPoolConfig, blockchain) - txpool, _ := txpool.New(new(big.Int).SetUint64(testTxPoolConfig.PriceLimit), blockchain, []txpool.SubPool{pool}) - - backend := NewMockBackend(bc, txpool) - // Create event Mux - // nolint:staticcheck - mux := new(event.TypeMux) - // Create Miner - miner := New(backend, &config, chainConfig, mux, engine, nil) - cleanup := func(skipMiner bool) { - bc.Stop() - engine.Close() - txpool.Close() - if !skipMiner { - miner.Close() - } - } - - return miner, mux, cleanup -} +// func minerTestGenesisBlock(period uint64, gasLimit uint64, faucet common.Address) *core.Genesis { +// config := *params.AllCliqueProtocolChanges +// config.Clique = ¶ms.CliqueConfig{ +// Period: period, +// Epoch: config.Clique.Epoch, +// } + +// // Assemble and return the genesis with the precompiles and faucet pre-funded +// return &core.Genesis{ +// Config: &config, +// ExtraData: append(append(make([]byte, 32), faucet[:]...), make([]byte, crypto.SignatureLength)...), +// GasLimit: gasLimit, +// BaseFee: big.NewInt(params.InitialBaseFee), +// Difficulty: big.NewInt(1), +// Alloc: map[common.Address]core.GenesisAccount{ +// common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover +// common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256 +// common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD +// common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity +// common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp +// common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd +// common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul +// common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing +// common.BytesToAddress([]byte{9}): {Balance: big.NewInt(1)}, // BLAKE2b +// faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))}, +// }, +// } +// } + +// func createMiner(t *testing.T) (*Miner, *event.TypeMux, func(skipMiner bool)) { +// t.Helper() + +// // Create Ethash config +// config := Config{ +// Etherbase: common.HexToAddress("123456789"), +// } +// // Create chainConfig +// chainDB := rawdb.NewMemoryDatabase() +// genesis := minerTestGenesisBlock(15, 11_500_000, common.HexToAddress("12345")) +// chainConfig, _, err := core.SetupGenesisBlock(chainDB, trie.NewDatabase(chainDB), genesis) +// if err != nil { +// t.Fatalf("can't create new chain config: %v", err) +// } +// // Create consensus engine +// engine := clique.New(chainConfig.Clique, chainDB) +// // Create Ethereum backend +// bc, err := core.NewBlockChain(chainDB, nil, genesis, nil, engine, vm.Config{}, nil, nil, nil) +// if err != nil { +// t.Fatalf("can't create new chain %v", err) +// } +// statedb, _ := state.New(types.EmptyRootHash, state.NewDatabase(chainDB), nil) +// blockchain := &testBlockChain{chainConfig, statedb, 10000000, new(event.Feed)} + +// pool := legacypool.New(testTxPoolConfig, blockchain) +// txpool, _ := txpool.New(new(big.Int).SetUint64(testTxPoolConfig.PriceLimit), blockchain, []txpool.SubPool{pool}) + +// backend := NewMockBackend(bc, txpool) +// // Create event Mux +// // nolint:staticcheck +// mux := new(event.TypeMux) +// // Create Miner +// miner := New(backend, &config, chainConfig, mux, engine, nil) +// cleanup := func(skipMiner bool) { +// bc.Stop() +// engine.Close() +// txpool.Close() +// if !skipMiner { +// miner.Close() +// } +// } + +// return miner, mux, cleanup +// } diff --git a/miner/worker.go b/miner/worker.go index 88a67ae68f..c5240a6d6a 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -77,10 +77,6 @@ const ( // any newly arrived transactions. minRecommitInterval = 1 * time.Second - // maxRecommitInterval is the maximum time interval to recreate the sealing block with - // any newly arrived transactions. - maxRecommitInterval = 15 * time.Second - // intervalAdjustRatio is the impact a single interval adjustment has on sealing work // resubmitting interval. intervalAdjustRatio = 0.1 @@ -364,16 +360,6 @@ func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus return worker } -// disablePreseal disables pre-sealing feature -func (w *worker) disablePreseal() { - w.noempty.Store(true) -} - -// enablePreseal enables pre-sealing feature -func (w *worker) enablePreseal() { - w.noempty.Store(false) -} - // setEtherbase sets the etherbase used to initialize the block coinbase field. func (w *worker) setEtherbase(addr common.Address) { w.mu.Lock() @@ -1175,7 +1161,6 @@ mainloop: env.header.Extra = append(tempVanity, blockExtraDataBytes...) env.header.Extra = append(env.header.Extra, tempSeal...) - } if !w.IsRunning() && len(coalescedLogs) > 0 { diff --git a/rpc/client_test.go b/rpc/client_test.go index 210835c45a..a73a0d840a 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -814,14 +814,11 @@ func TestClientHTTP(t *testing.T) { func TestClientReconnect(t *testing.T) { startServer := func(addr string) (*Server, net.Listener) { srv := newTestServer() - l, err := net.Listen("tcp", addr) if err != nil { t.Fatal("can't listen:", err) } - go http.Serve(l, srv.WebsocketHandler([]string{"*"})) - return srv, l } @@ -830,14 +827,10 @@ func TestClientReconnect(t *testing.T) { // Start a server and corresponding client. s1, l1 := startServer("127.0.0.1:0") - client, err := DialContext(ctx, "ws://"+l1.Addr().String()) - defer client.Close() - if err != nil { t.Fatal("can't dial", err) } - defer client.Close() // Perform a call. This should work because the server is up. @@ -865,27 +858,22 @@ func TestClientReconnect(t *testing.T) { defer s2.Stop() start := make(chan struct{}) - errors := make(chan error, 20) for i := 0; i < cap(errors); i++ { go func() { <-start - var resp echoResult errors <- client.CallContext(ctx, &resp, "test_echo", "", 3, nil) }() } close(start) - errcount := 0 - for i := 0; i < cap(errors); i++ { if err = <-errors; err != nil { errcount++ } } t.Logf("%d errors, last error: %v", errcount, err) - if errcount > 1 { t.Errorf("expected one error after disconnect, got %d", errcount) } diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 86229e303b..b392e1301e 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -309,6 +309,7 @@ func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapsh return snaps, statedb, root, err } +// nolint:unused func (t *StateTest) gasLimit(subtest StateSubtest) uint64 { return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas] } diff --git a/trie/secure_trie.go b/trie/secure_trie.go index aa31f34a4d..99cdfac576 100644 --- a/trie/secure_trie.go +++ b/trie/secure_trie.go @@ -35,7 +35,6 @@ func NewSecure(stateRoot common.Hash, owner common.Hash, root common.Hash, db *D Owner: owner, Root: root, } - return NewStateTrie(id, db) } @@ -66,12 +65,11 @@ func NewStateTrie(id *ID, db *Database) (*StateTrie, error) { if db == nil { panic("trie.NewStateTrie called without a database") } - trie, err := New(id, db) if err != nil { return nil, err } - + // nolint return &StateTrie{trie: *trie, preimages: db.preimages}, nil } @@ -105,10 +103,8 @@ func (t *StateTrie) GetAccount(address common.Address) (*types.StateAccount, err if res == nil || err != nil { return nil, err } - ret := new(types.StateAccount) err = rlp.DecodeBytes(res, ret) - return ret, err } @@ -120,10 +116,8 @@ func (t *StateTrie) GetAccountByHash(addrHash common.Hash) (*types.StateAccount, if res == nil || err != nil { return nil, err } - ret := new(types.StateAccount) err = rlp.DecodeBytes(res, ret) - return ret, err } @@ -147,7 +141,6 @@ func (t *StateTrie) GetNode(path []byte) ([]byte, int, error) { func (t *StateTrie) MustUpdate(key, value []byte) { hk := t.hashKey(key) t.trie.MustUpdate(hk, value) - t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) } @@ -166,9 +159,7 @@ func (t *StateTrie) UpdateStorage(_ common.Address, key, value []byte) error { if err != nil { return err } - t.getSecKeyCache()[string(hk)] = common.CopyBytes(key) - return nil } @@ -176,17 +167,13 @@ func (t *StateTrie) UpdateStorage(_ common.Address, key, value []byte) error { func (t *StateTrie) UpdateAccount(address common.Address, acc *types.StateAccount) error { hk := t.hashKey(address.Bytes()) data, err := rlp.EncodeToBytes(acc) - if err != nil { return err } - if err := t.trie.Update(hk, data); err != nil { return err } - t.getSecKeyCache()[string(hk)] = address.Bytes() - return nil } @@ -208,7 +195,6 @@ func (t *StateTrie) MustDelete(key []byte) { func (t *StateTrie) DeleteStorage(_ common.Address, key []byte) error { hk := t.hashKey(key) delete(t.getSecKeyCache(), string(hk)) - return t.trie.Delete(hk) } @@ -216,7 +202,6 @@ func (t *StateTrie) DeleteStorage(_ common.Address, key []byte) error { func (t *StateTrie) DeleteAccount(address common.Address) error { hk := t.hashKey(address.Bytes()) delete(t.getSecKeyCache(), string(hk)) - return t.trie.Delete(hk) } @@ -226,11 +211,9 @@ func (t *StateTrie) GetKey(shaKey []byte) []byte { if key, ok := t.getSecKeyCache()[string(shaKey)]; ok { return key } - if t.preimages == nil { return nil } - return t.preimages.preimage(common.BytesToHash(shaKey)) } @@ -249,10 +232,8 @@ func (t *StateTrie) Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet, er for hk, key := range t.secKeyCache { preimages[common.BytesToHash([]byte(hk))] = key } - t.preimages.insertPreimage(preimages) } - t.secKeyCache = make(map[string][]byte) } // Commit the trie and return its modified nodeset. @@ -295,7 +276,6 @@ func (t *StateTrie) hashKey(key []byte) []byte { h.sha.Write(key) h.sha.Read(t.hashKeyBuf[:]) returnHasherToPool(h) - return t.hashKeyBuf[:] } @@ -307,6 +287,5 @@ func (t *StateTrie) getSecKeyCache() map[string][]byte { t.secKeyCacheOwner = t t.secKeyCache = make(map[string][]byte) } - return t.secKeyCache }