diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 73c9ce7eb3..441849c20f 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -637,7 +637,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs // callContract implements common code between normal and pending contract calls. // state is modified during execution, make sure to copy it if necessary. -func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, header *types.Header, stateDB *state.StateDB) (*core.ExecutionResult, error) { +func (b *SimulatedBackend) callContract(_ context.Context, call ethereum.CallMsg, header *types.Header, stateDB *state.StateDB) (*core.ExecutionResult, error) { // Gas prices post 1559 need to be initialized if call.GasPrice != nil && (call.GasFeeCap != nil || call.GasTipCap != nil) { return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index bd0b95de6f..45b981ae2d 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -1483,7 +1483,7 @@ func TestCommitReturnValue(t *testing.T) { gasPrice := new(big.Int).Add(head.BaseFee, big.NewInt(1)) _tx := types.NewTransaction(0, testAddr, big.NewInt(1000), params.TxGas, gasPrice, nil) tx, _ := types.SignTx(_tx, types.HomesteadSigner{}, testKey) - sim.SendTransaction(context.Background(), tx) + _ = sim.SendTransaction(context.Background(), tx) h2 := sim.Commit() // Create another block in the original chain @@ -1518,8 +1518,8 @@ func TestAdjustTimeAfterFork(t *testing.T) { sim.Commit() // h1 h1 := sim.blockchain.CurrentHeader().Hash() sim.Commit() // h2 - sim.Fork(context.Background(), h1) - sim.AdjustTime(1 * time.Second) + _ = sim.Fork(context.Background(), h1) + _ = sim.AdjustTime(1 * time.Second) sim.Commit() head := sim.blockchain.CurrentHeader() diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go index 2a2f6e9b1f..450f430fcb 100644 --- a/accounts/abi/bind/base_test.go +++ b/accounts/abi/bind/base_test.go @@ -528,8 +528,8 @@ func TestCall(t *testing.T) { func TestCrashers(t *testing.T) { t.Parallel() - abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`)) - abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`)) - abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`)) - abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"foo.Bar"}]}]}]`)) + _, _ = abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"_1"}]}]}]`)) + _, _ = abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"&"}]}]}]`)) + _, _ = abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"----"}]}]}]`)) + _, _ = abi.JSON(strings.NewReader(`[{"inputs":[{"type":"tuple[]","components":[{"type":"bool","name":"foo.Bar"}]}]}]`)) } diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go index 15d98ab798..451be7254e 100644 --- a/cmd/abigen/main.go +++ b/cmd/abigen/main.go @@ -118,6 +118,7 @@ func abigen(c *cli.Context) error { aliases = make(map[string]string) ) + // nolint:nestif if c.String(abiFlag.Name) != "" { // Load up the ABI, optional bytecode and type name from the parameters var ( diff --git a/cmd/checkpoint-admin/common.go b/cmd/checkpoint-admin/common.go index c1da32d8c7..b1d2579fe2 100644 --- a/cmd/checkpoint-admin/common.go +++ b/cmd/checkpoint-admin/common.go @@ -17,9 +17,10 @@ package main import ( - "github.com/urfave/cli/v2" "strconv" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/external" diff --git a/cmd/checkpoint-admin/exec.go b/cmd/checkpoint-admin/exec.go index 84c00ec0eb..bb1a9e4711 100644 --- a/cmd/checkpoint-admin/exec.go +++ b/cmd/checkpoint-admin/exec.go @@ -140,6 +140,7 @@ func sign(ctx *cli.Context) error { oracle *checkpointoracle.CheckpointOracle ) + // nolint:nestif if !ctx.IsSet(nodeURLFlag.Name) { // Offline mode signing offline = true diff --git a/cmd/clef/consolecmd_test.go b/cmd/clef/consolecmd_test.go index 498bde959f..0b5e83fb58 100644 --- a/cmd/clef/consolecmd_test.go +++ b/cmd/clef/consolecmd_test.go @@ -27,7 +27,8 @@ import ( // TestImportRaw tests clef --importraw func TestImportRaw(t *testing.T) { keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name())) - os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + _ = os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + t.Cleanup(func() { os.Remove(keyPath) }) t.Parallel() @@ -72,7 +73,8 @@ func TestImportRaw(t *testing.T) { // TestListAccounts tests clef --list-accounts func TestListAccounts(t *testing.T) { keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name())) - os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + _ = os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + t.Cleanup(func() { os.Remove(keyPath) }) t.Parallel() @@ -103,7 +105,8 @@ func TestListAccounts(t *testing.T) { // TestListWallets tests clef --list-wallets func TestListWallets(t *testing.T) { keyPath := filepath.Join(os.TempDir(), fmt.Sprintf("%v-tempkey.test", t.Name())) - os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + _ = os.WriteFile(keyPath, []byte("0102030405060708090a0102030405060708090a0102030405060708090a0102"), 0777) + t.Cleanup(func() { os.Remove(keyPath) }) t.Parallel() diff --git a/cmd/devp2p/crawl.go b/cmd/devp2p/crawl.go index e13fa1e284..eba1583dc8 100644 --- a/cmd/devp2p/crawl.go +++ b/cmd/devp2p/crawl.go @@ -71,6 +71,7 @@ func newCrawler(input nodeSet, disc resolver, iters ...enode.Iterator) *crawler return c } +// nolint:gocognit func (c *crawler) run(timeout time.Duration, nthreads int) nodeSet { var ( timeoutTimer = time.NewTimer(timeout) diff --git a/cmd/devp2p/enrcmd.go b/cmd/devp2p/enrcmd.go index 73aaa83abb..13ba875b04 100644 --- a/cmd/devp2p/enrcmd.go +++ b/cmd/devp2p/enrcmd.go @@ -48,6 +48,7 @@ var enrdumpCommand = &cli.Command{ func enrdump(ctx *cli.Context) error { var source string + // nolint:nestif if file := ctx.String(fileFlag.Name); file != "" { if ctx.NArg() != 0 { return fmt.Errorf("can't dump record from command-line argument in -file mode") diff --git a/cmd/devp2p/internal/ethtest/transaction.go b/cmd/devp2p/internal/ethtest/transaction.go index 764cfc589d..6897cd5c86 100644 --- a/cmd/devp2p/internal/ethtest/transaction.go +++ b/cmd/devp2p/internal/ethtest/transaction.go @@ -57,7 +57,7 @@ func (s *Suite) sendSuccessfulTxs(t *utesting.T) error { return nil } -// nolint:typecheck +// nolint:typecheck, gocognit func sendSuccessfulTx(s *Suite, tx *types.Transaction, prevTx *types.Transaction) error { sendConn, recvConn, err := s.createSendAndRecvConns() if err != nil { diff --git a/cmd/evm/internal/t8ntool/block.go b/cmd/evm/internal/t8ntool/block.go index be44b51c25..634ede3166 100644 --- a/cmd/evm/internal/t8ntool/block.go +++ b/cmd/evm/internal/t8ntool/block.go @@ -22,10 +22,11 @@ import ( "encoding/json" "errors" "fmt" - "github.com/urfave/cli/v2" "math/big" "os" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/math" diff --git a/cmd/evm/internal/t8ntool/transaction.go b/cmd/evm/internal/t8ntool/transaction.go index 73735da7c2..02e9db1bf6 100644 --- a/cmd/evm/internal/t8ntool/transaction.go +++ b/cmd/evm/internal/t8ntool/transaction.go @@ -20,11 +20,12 @@ import ( "encoding/json" "errors" "fmt" - "github.com/urfave/cli/v2" "math/big" "os" "strings" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core" diff --git a/cmd/evm/internal/t8ntool/transition.go b/cmd/evm/internal/t8ntool/transition.go index 05dd193581..39fcfc344b 100644 --- a/cmd/evm/internal/t8ntool/transition.go +++ b/cmd/evm/internal/t8ntool/transition.go @@ -21,12 +21,13 @@ import ( "encoding/json" "errors" "fmt" - "github.com/urfave/cli/v2" "math/big" "os" "path" "strings" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/consensus/misc" @@ -458,6 +459,7 @@ func saveFile(baseDir, filename string, data interface{}) error { } location := path.Join(baseDir, filename) + // nolint:gosec if err = os.WriteFile(location, b, 0644); err != nil { return NewError(ErrorIO, fmt.Errorf("failed writing output: %v", err)) } diff --git a/cmd/geth/attach_test.go b/cmd/geth/attach_test.go index 396497e840..5c7c1f50fc 100644 --- a/cmd/geth/attach_test.go +++ b/cmd/geth/attach_test.go @@ -82,6 +82,7 @@ func testReceiveHeaders(t *testing.T, ln net.Listener, gethArgs ...string) { } atomic.StoreUint32(&ok, 1) }}} + //nolint:errcheck go server.Serve(ln) defer server.Close() diff --git a/cmd/geth/dbcmd.go b/cmd/geth/dbcmd.go index 29b0009a86..425f884a02 100644 --- a/cmd/geth/dbcmd.go +++ b/cmd/geth/dbcmd.go @@ -337,8 +337,8 @@ func checkStateContent(ctx *cli.Context) error { v := it.Value() hasher.Reset() - hasher.Write(v) - hasher.Read(got) + _, _ = hasher.Write(v) + _, _ = hasher.Read(got) if !bytes.Equal(k, got) { errs++ diff --git a/cmd/geth/main.go b/cmd/geth/main.go index f807da0c71..79aacbe3e8 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -284,6 +284,9 @@ 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. switch { case ctx.IsSet(utils.GoerliFlag.Name): @@ -320,7 +323,7 @@ func prepare(ctx *cli.Context) { log.Info("Starting Geth on Ethereum mainnet...") } // If we're a full node on mainnet without --cache specified, bump default cache allowance - if ctx.String(utils.SyncModeFlag.Name) != "light" && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) { + if ctx.String(utils.SyncModeFlag.Name) != light && !ctx.IsSet(utils.CacheFlag.Name) && !ctx.IsSet(utils.NetworkIdFlag.Name) { // Make sure we're not on any supported preconfigured testnet either if !ctx.IsSet(utils.SepoliaFlag.Name) && !ctx.IsSet(utils.GoerliFlag.Name) && @@ -328,13 +331,13 @@ func prepare(ctx *cli.Context) { !ctx.IsSet(utils.DeveloperFlag.Name) { // Nope, we're really on mainnet. Bump that cache up! log.Info("Bumping default cache on mainnet", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 4096) - ctx.Set(utils.CacheFlag.Name, strconv.Itoa(4096)) + _ = ctx.Set(utils.CacheFlag.Name, strconv.Itoa(4096)) } } // If we're running a light client on any network, drop the cache to some meaningfully low amount - if ctx.String(utils.SyncModeFlag.Name) == "light" && !ctx.IsSet(utils.CacheFlag.Name) { + if ctx.String(utils.SyncModeFlag.Name) == light && !ctx.IsSet(utils.CacheFlag.Name) { log.Info("Dropping default light client cache", "provided", ctx.Int(utils.CacheFlag.Name), "updated", 128) - ctx.Set(utils.CacheFlag.Name, strconv.Itoa(128)) + _ = ctx.Set(utils.CacheFlag.Name, strconv.Itoa(128)) } // Start metrics export if enabled diff --git a/cmd/geth/snapshot.go b/cmd/geth/snapshot.go index bb65297953..f4d046477d 100644 --- a/cmd/geth/snapshot.go +++ b/cmd/geth/snapshot.go @@ -442,8 +442,8 @@ func traverseRawState(ctx *cli.Context) error { } hasher.Reset() - hasher.Write(blob) - hasher.Read(got) + _, _ = hasher.Write(blob) + _, _ = hasher.Read(got) if !bytes.Equal(got, node.Bytes()) { log.Error("Invalid trie node(account)", "hash", node.Hex(), "value", blob) @@ -485,8 +485,8 @@ func traverseRawState(ctx *cli.Context) error { } hasher.Reset() - hasher.Write(blob) - hasher.Read(got) + _, _ = hasher.Write(blob) + _, _ = hasher.Read(got) if !bytes.Equal(got, node.Bytes()) { log.Error("Invalid trie node(storage)", "hash", node.Hex(), "value", blob) diff --git a/cmd/geth/verkle.go b/cmd/geth/verkle.go index 95449ebe3a..82b1c82be1 100644 --- a/cmd/geth/verkle.go +++ b/cmd/geth/verkle.go @@ -221,7 +221,8 @@ func expandVerkle(ctx *cli.Context) error { for i, key := range keylist { log.Info("Reading key", "index", i, "key", keylist[0]) - root.Get(key, chaindb.Get) + + _, _ = root.Get(key, chaindb.Get) } if err := os.WriteFile("dump.dot", []byte(verkle.ToDot(root)), 0600); err != nil { diff --git a/cmd/utils/bor_flags.go b/cmd/utils/bor_flags.go index 323ec1f885..3f35fa53d2 100644 --- a/cmd/utils/bor_flags.go +++ b/cmd/utils/bor_flags.go @@ -4,11 +4,11 @@ import ( "encoding/json" "os" - "github.com/ethereum/go-ethereum/eth/ethconfig" "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" ) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 662a5fd017..3f26035af5 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -22,7 +22,6 @@ import ( "compress/gzip" "errors" "fmt" - "github.com/urfave/cli/v2" "io" "os" "os/signal" @@ -31,6 +30,8 @@ import ( "syscall" "time" + "github.com/urfave/cli/v2" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index f0b9468188..d41bd77b79 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1435,6 +1435,7 @@ func SetP2PConfig(ctx *cli.Context, cfg *p2p.Config) { setBootstrapNodes(ctx, cfg) setBootstrapNodesV5(ctx, cfg) + // nolint:goconst lightClient := ctx.String(SyncModeFlag.Name) == "light" lightServer := (ctx.Int(LightServeFlag.Name) != 0) @@ -1829,8 +1830,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { CheckExclusive(ctx, LightServeFlag, SyncModeFlag, "light") CheckExclusive(ctx, DeveloperFlag, ExternalSignerFlag) // Can't use both ephemeral unlocked and external signer + // nolint:goconst if ctx.String(GCModeFlag.Name) == "archive" && ctx.Uint64(TxLookupLimitFlag.Name) != 0 { - ctx.Set(TxLookupLimitFlag.Name, "0") + _ = ctx.Set(TxLookupLimitFlag.Name, "0") log.Warn("Disable transaction unindexing for archive node") } @@ -1858,7 +1860,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { if cache := ctx.Int(CacheFlag.Name); cache > allowance { log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) - ctx.Set(CacheFlag.Name, strconv.Itoa(allowance)) + _ = ctx.Set(CacheFlag.Name, strconv.Itoa(allowance)) } } // Ensure Go's GC ignores the database cache for trigger percentage @@ -1886,6 +1888,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { cfg.DatabaseFreezer = ctx.String(AncientFlag.Name) } + // nolint:goconst if gcmode := ctx.String(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" { Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name) } @@ -2194,7 +2197,7 @@ func RegisterFullSyncTester(stack *node.Node, eth *eth.Ethereum, path string) { Fatalf("Failed to decode block: %v", err) } - ethcatalyst.RegisterFullSyncTester(stack, eth, &block) + _, _ = ethcatalyst.RegisterFullSyncTester(stack, eth, &block) log.Info("Registered full-sync tester", "number", block.NumberU64(), "hash", block.Hash()) } diff --git a/consensus/clique/clique.go b/consensus/clique/clique.go index 175c5ff804..1db06e121c 100644 --- a/consensus/clique/clique.go +++ b/consensus/clique/clique.go @@ -545,6 +545,7 @@ func (c *Clique) Prepare(chain consensus.ChainHeaderReader, header *types.Header } c.lock.RLock() + // nolint:nestif if number%c.config.Epoch != 0 { // Gather all the proposals that make sense voting on addresses := make([]common.Address, 0, len(c.proposals)) diff --git a/consensus/clique/snapshot_test.go b/consensus/clique/snapshot_test.go index 0736ca94f5..effdbf4674 100644 --- a/consensus/clique/snapshot_test.go +++ b/consensus/clique/snapshot_test.go @@ -389,6 +389,7 @@ func TestClique(t *testing.T) { } } +// nolint:gocognit func (tt *cliqueTest) run(t *testing.T) { // Create the account pool and generate the initial set of signers accounts := newTesterAccountPool() @@ -471,6 +472,7 @@ func (tt *cliqueTest) run(t *testing.T) { if err != nil { t.Fatalf("failed to create test chain: %v", err) } + defer chain.Stop() for j := 0; j < len(batches)-1; j++ { diff --git a/core/blockchain.go b/core/blockchain.go index 1f9c7f49e2..d3699e992d 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -340,6 +340,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis } // Make sure the state associated with the block is available head := bc.CurrentBlock() + // nolint:nestif if !bc.HasState(head.Root) { // Head state is missing, before the state recovery, find out the // disk layer point of snapshot(if it's enabled). Make sure the @@ -472,9 +473,9 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis log.Warn("Rewinding chain to upgrade configuration", "err", compat) if compat.RewindToTime > 0 { - bc.SetHeadWithTimestamp(compat.RewindToTime) + _ = bc.SetHeadWithTimestamp(compat.RewindToTime) } else { - bc.SetHead(compat.RewindToBlock) + _ = bc.SetHead(compat.RewindToBlock) } rawdb.WriteChainConfig(db, genesisHash, chainConfig) @@ -776,6 +777,7 @@ func (bc *BlockChain) SetSafe(header *types.Header) { // requested time. If both `head` and `time` is 0, the chain is rewound to genesis. // // The method returns the block number where the requested root cap was found. +// nolint:gocognit func (bc *BlockChain) setHeadBeyondRoot(head uint64, time uint64, root common.Hash, repair bool) (uint64, error) { if !bc.chainmu.TryLock() { return 0, errChainStopped @@ -794,6 +796,7 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, time uint64, root common.Ha // Rewind the blockchain, ensuring we don't end up with a stateless head // block. Note, depth equality is permitted to allow using SetHead as a // chain reparation mechanism without deleting any data! + // nolint:nestif if currentBlock := bc.CurrentBlock(); currentBlock != nil && header.Number.Uint64() <= currentBlock.Number.Uint64() { newHeadBlock := bc.GetBlock(header.Hash(), header.Number.Uint64()) if newHeadBlock == nil { @@ -1194,7 +1197,7 @@ func (bc *BlockChain) Stop() { // Ensure all live cached entries be saved into disk, so that we can skip // cache warmup when node restarts. if bc.cacheConfig.TrieCleanJournal != "" { - bc.triedb.SaveCache(bc.cacheConfig.TrieCleanJournal) + _ = bc.triedb.SaveCache(bc.cacheConfig.TrieCleanJournal) } log.Info("Blockchain stopped") @@ -1682,7 +1685,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. ) if nodes > limit || imgs > 4*1024*1024 { - bc.triedb.Cap(limit - ethdb.IdealBatchSize) + _ = bc.triedb.Cap(limit - ethdb.IdealBatchSize) } // Find the next state trie we need to commit chosen := current - bc.cacheConfig.TriesInMemory @@ -1701,7 +1704,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", flushInterval, "optimum", float64(chosen-bc.lastWrite)/float64(bc.cacheConfig.TriesInMemory)) } // Flush an entire trie and restart the counters - bc.triedb.Commit(header.Root, true) + _ = bc.triedb.Commit(header.Root, true) bc.lastWrite = chosen bc.gcproc = 0 } @@ -2551,7 +2554,7 @@ func (bc *BlockChain) collectLogs(b *types.Block, removed bool) []*types.Log { receipts = append(receipts, borReceipt) } - receipts.DeriveFields(bc.chainConfig, b.Hash(), b.NumberU64(), b.BaseFee(), b.Transactions()) + _ = receipts.DeriveFields(bc.chainConfig, b.Hash(), b.NumberU64(), b.BaseFee(), b.Transactions()) var logs []*types.Log @@ -2574,6 +2577,7 @@ func (bc *BlockChain) collectLogs(b *types.Block, removed bool) []*types.Log { // potential missing transactions and post an event about them. // Note the new head block won't be processed here, callers need to handle it // externally. +// nolint:gocognit func (bc *BlockChain) reorg(oldHead *types.Header, newHead *types.Block) error { var ( newChain types.Blocks diff --git a/core/blockchain_reader.go b/core/blockchain_reader.go index 41ccf26934..52ae339d94 100644 --- a/core/blockchain_reader.go +++ b/core/blockchain_reader.go @@ -17,7 +17,6 @@ package core import ( - "github.com/ethereum/go-ethereum/ethdb" "math/big" "github.com/ethereum/go-ethereum/common" @@ -27,6 +26,7 @@ import ( "github.com/ethereum/go-ethereum/core/state/snapshot" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" diff --git a/core/blockchain_test.go b/core/blockchain_test.go index c43c94a029..1843906524 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -2841,7 +2841,7 @@ func TestTransactionIndices(t *testing.T) { for _, l := range limit { frdir := t.TempDir() ancientDb, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) - rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) + _, _ = rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) l := l @@ -2867,7 +2867,7 @@ func TestTransactionIndices(t *testing.T) { ancientDb, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), t.TempDir(), "", false) defer ancientDb.Close() - rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) + _, _ = rawdb.WriteAncientBlocks(ancientDb, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) limit = []uint64{0, 64 /* drop stale */, 32 /* shorten history */, 64 /* extend history */, 0 /* restore all */} @@ -4072,17 +4072,20 @@ func TestSetCanonical(t *testing.T) { } } - chain.SetCanonical(side[len(side)-1]) + _, _ = chain.SetCanonical(side[len(side)-1]) verify(side[len(side)-1]) // Reset the chain head to original chain - chain.SetCanonical(canon[int(DefaultCacheConfig.TriesInMemory)-1]) + _, _ = chain.SetCanonical(canon[int(DefaultCacheConfig.TriesInMemory)-1]) verify(canon[int(DefaultCacheConfig.TriesInMemory)-1]) } // TestCanonicalHashMarker tests all the canonical hash markers are updated/deleted // correctly in case reorg is called. +// nolint:gocognit func TestCanonicalHashMarker(t *testing.T) { + t.Parallel() + var cases = []struct { forkA int forkB int @@ -4169,7 +4172,7 @@ func TestCanonicalHashMarker(t *testing.T) { verify(forkB[len(forkB)-1]) } else { verify(forkA[len(forkA)-1]) - chain.SetCanonical(forkB[len(forkB)-1]) + _, _ = chain.SetCanonical(forkB[len(forkB)-1]) verify(forkB[len(forkB)-1]) } @@ -4387,7 +4390,7 @@ func TestTxIndexer(t *testing.T) { for _, c := range cases { frdir := t.TempDir() db, _ := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), frdir, "", false) - rawdb.WriteAncientBlocks(db, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) + _, _ = rawdb.WriteAncientBlocks(db, append([]*types.Block{gspec.ToBlock()}, blocks...), append([]types.Receipts{{}}, receipts...), []types.Receipts{nil}, big.NewInt(0)) // Index the initial blocks from ancient store chain, _ := NewBlockChain(db, nil, gspec, nil, engine, vm.Config{}, nil, &c.limitA, nil) diff --git a/core/forkchoice_test.go b/core/forkchoice_test.go index c288d28b17..2457f86fdd 100644 --- a/core/forkchoice_test.go +++ b/core/forkchoice_test.go @@ -38,7 +38,7 @@ func TestPastChainInsert(t *testing.T) { gspec = &Genesis{BaseFee: big.NewInt(params.InitialBaseFee), Config: params.AllEthashProtocolChanges} ) - gspec.Commit(db, trie.NewDatabase(db)) + _, _ = gspec.Commit(db, trie.NewDatabase(db)) hc, err := NewHeaderChain(db, gspec.Config, ethash.NewFaker(), func() bool { return false }) if err != nil { @@ -110,7 +110,7 @@ func TestFutureChainInsert(t *testing.T) { gspec = &Genesis{BaseFee: big.NewInt(params.InitialBaseFee), Config: params.AllEthashProtocolChanges} ) - gspec.Commit(db, trie.NewDatabase(db)) + _, _ = gspec.Commit(db, trie.NewDatabase(db)) hc, err := NewHeaderChain(db, gspec.Config, ethash.NewFaker(), func() bool { return false }) if err != nil { @@ -170,7 +170,7 @@ func TestOverlappingChainInsert(t *testing.T) { gspec = &Genesis{BaseFee: big.NewInt(params.InitialBaseFee), Config: params.AllEthashProtocolChanges} ) - gspec.Commit(db, trie.NewDatabase(db)) + _, _ = gspec.Commit(db, trie.NewDatabase(db)) hc, err := NewHeaderChain(db, gspec.Config, ethash.NewFaker(), func() bool { return false }) if err != nil { diff --git a/core/genesis.go b/core/genesis.go index 37ccb9e43a..510bc3e34d 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -318,6 +318,7 @@ func SetupGenesisBlock(db ethdb.Database, triedb *trie.Database, genesis *Genesi return SetupGenesisBlockWithOverride(db, triedb, genesis, nil) } +// nolint:gocognit func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *trie.Database, genesis *Genesis, overrides *ChainOverrides) (*params.ChainConfig, common.Hash, error) { if genesis != nil && genesis.Config == nil { return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig diff --git a/core/headerchain.go b/core/headerchain.go index 74a3a6ff72..0e95f32b28 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -640,6 +640,7 @@ func (hc *HeaderChain) SetHeadWithTimestamp(time uint64, updateFn UpdateHeadBloc // setHead rewinds the local chain to a new head block or a head timestamp. // Everything above the new head will be deleted and the new one set. +// nolint:gocognit func (hc *HeaderChain) setHead(headBlock uint64, headTime uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { // Sanity check that there's no attempt to undo the genesis block. This is // a fairly synthetic case where someone enables a timestamp based fork diff --git a/core/headerchain_test.go b/core/headerchain_test.go index 8a1ecb9905..71d600b4c9 100644 --- a/core/headerchain_test.go +++ b/core/headerchain_test.go @@ -79,7 +79,7 @@ func TestHeaderInsertion(t *testing.T) { gspec = &Genesis{BaseFee: big.NewInt(params.InitialBaseFee), Config: params.AllEthashProtocolChanges} ) - gspec.Commit(db, trie.NewDatabase(db)) + _, _ = gspec.Commit(db, trie.NewDatabase(db)) hc, err := NewHeaderChain(db, gspec.Config, ethash.NewFaker(), func() bool { return false }) if err != nil { diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index 6f49f7ede4..cfeae6f0c9 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -37,7 +37,7 @@ import ( func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash { var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { data, _ = reader.Ancient(ChainFreezerHashTable, number) if len(data) == 0 { // Get it by hash from leveldb @@ -383,7 +383,7 @@ func ReadHeaderRange(db ethdb.Reader, number uint64, count uint64) []rlp.RawValu func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { // First try to look up the data in ancient database. Extra hash // comparison is necessary since ancient database only maintains // the canonical data. @@ -486,7 +486,7 @@ func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue // the canonical data. var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { // Check if the data is in ancients if isCanon(reader, number, hash) { data, _ = reader.Ancient(ChainFreezerBodiesTable, number) @@ -506,7 +506,7 @@ func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue func ReadCanonicalBodyRLP(db ethdb.Reader, number uint64) rlp.RawValue { var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { data, _ = reader.Ancient(ChainFreezerBodiesTable, number) if len(data) > 0 { return nil @@ -580,7 +580,7 @@ func DeleteBody(db ethdb.KeyValueWriter, hash common.Hash, number uint64) { func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { // Check if the data is in ancients if isCanon(reader, number, hash) { data, _ = reader.Ancient(ChainFreezerDifficultyTable, number) @@ -648,7 +648,7 @@ func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool { func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue { var data []byte - db.ReadAncients(func(reader ethdb.AncientReaderOp) error { + _ = db.ReadAncients(func(reader ethdb.AncientReaderOp) error { // Check if the data is in ancients if isCanon(reader, number, hash) { data, _ = reader.Ancient(ChainFreezerReceiptTable, number) diff --git a/core/rawdb/accessors_trie.go b/core/rawdb/accessors_trie.go index 1d7f8d4b3a..4737559080 100644 --- a/core/rawdb/accessors_trie.go +++ b/core/rawdb/accessors_trie.go @@ -59,8 +59,8 @@ func returnHasherToPool(h *nodeHasher) { hasherPool.Put(h) } func (h *nodeHasher) hashData(data []byte) (n common.Hash) { h.sha.Reset() - h.sha.Write(data) - h.sha.Read(n[:]) + _, _ = h.sha.Write(data) + _, _ = h.sha.Read(n[:]) return n } diff --git a/core/rawdb/freezer.go b/core/rawdb/freezer.go index b24fe8b0e6..48630c54f0 100644 --- a/core/rawdb/freezer.go +++ b/core/rawdb/freezer.go @@ -127,9 +127,9 @@ func NewFreezer(datadir string, namespace string, readonly bool, maxTableSize ui table, err := newTable(datadir, name, readMeter, writeMeter, sizeGauge, maxTableSize, disableSnappy, readonly) if err != nil { for _, table := range freezer.tables { - table.Close() + _ = table.Close() } - lock.Unlock() + _ = lock.Unlock() return nil, err } @@ -163,9 +163,9 @@ func NewFreezer(datadir string, namespace string, readonly bool, maxTableSize ui if err != nil { for _, table := range freezer.tables { - table.Close() + _ = table.Close() } - lock.Unlock() + _ = lock.Unlock() return nil, err } diff --git a/core/rawdb/freezer_resettable_test.go b/core/rawdb/freezer_resettable_test.go index c0cfd2cd4f..474e865152 100644 --- a/core/rawdb/freezer_resettable_test.go +++ b/core/rawdb/freezer_resettable_test.go @@ -39,9 +39,9 @@ func TestResetFreezer(t *testing.T) { f, _ := NewResettableFreezer(t.TempDir(), "", false, 2048, freezerTestTableDef) defer f.Close() - f.ModifyAncients(func(op ethdb.AncientWriteOp) error { + _, _ = f.ModifyAncients(func(op ethdb.AncientWriteOp) error { for _, item := range items { - op.AppendRaw("test", item.id, item.blob) + _ = op.AppendRaw("test", item.id, item.blob) } return nil @@ -55,7 +55,7 @@ func TestResetFreezer(t *testing.T) { } // Reset freezer - f.Reset() + _ = f.Reset() count, _ := f.Ancients() if count != 0 { @@ -70,9 +70,9 @@ func TestResetFreezer(t *testing.T) { } // Fill the freezer - f.ModifyAncients(func(op ethdb.AncientWriteOp) error { + _, _ = f.ModifyAncients(func(op ethdb.AncientWriteOp) error { for _, item := range items { - op.AppendRaw("test", item.id, item.blob) + _ = op.AppendRaw("test", item.id, item.blob) } return nil @@ -99,19 +99,19 @@ func TestFreezerCleanup(t *testing.T) { } datadir := t.TempDir() f, _ := NewResettableFreezer(datadir, "", false, 2048, freezerTestTableDef) - f.ModifyAncients(func(op ethdb.AncientWriteOp) error { + _, _ = f.ModifyAncients(func(op ethdb.AncientWriteOp) error { for _, item := range items { - op.AppendRaw("test", item.id, item.blob) + _ = op.AppendRaw("test", item.id, item.blob) } return nil }) - f.Close() - os.Rename(datadir, tmpName(datadir)) + _ = f.Close() + _ = os.Rename(datadir, tmpName(datadir)) // Open the freezer again, trigger cleanup operation f, _ = NewResettableFreezer(datadir, "", false, 2048, freezerTestTableDef) - f.Close() + _ = f.Close() if _, err := os.Lstat(tmpName(datadir)); !os.IsNotExist(err) { t.Fatal("Failed to cleanup leftover directory") diff --git a/core/rawdb/freezer_utils_test.go b/core/rawdb/freezer_utils_test.go index 3408b4aabe..2afda95293 100644 --- a/core/rawdb/freezer_utils_test.go +++ b/core/rawdb/freezer_utils_test.go @@ -45,7 +45,7 @@ func TestCopyFrom(t *testing.T) { } for _, c := range cases { - os.WriteFile(c.src, content, 0600) + _ = os.WriteFile(c.src, content, 0600) if err := copyFrom(c.src, c.dest, c.offset, func(f *os.File) error { if !c.writePrefix { diff --git a/core/state/iterator_test.go b/core/state/iterator_test.go index 114d5bf664..c6607809a7 100644 --- a/core/state/iterator_test.go +++ b/core/state/iterator_test.go @@ -27,7 +27,7 @@ import ( func TestNodeIteratorCoverage(t *testing.T) { // Create some arbitrary test state to iterate db, sdb, root, _ := makeTestState() - sdb.TrieDB().Commit(root, false) + _ = sdb.TrieDB().Commit(root, false) state, err := New(root, sdb, nil) if err != nil { diff --git a/core/state/snapshot/context.go b/core/state/snapshot/context.go index 1de39dcd23..146ade3f47 100644 --- a/core/state/snapshot/context.go +++ b/core/state/snapshot/context.go @@ -191,10 +191,10 @@ func (ctx *generatorContext) removeStorageBefore(account common.Hash) { count++ - ctx.batch.Delete(key) + _ = ctx.batch.Delete(key) if ctx.batch.ValueSize() > ethdb.IdealBatchSize { - ctx.batch.Write() + _ = ctx.batch.Write() ctx.batch.Reset() } } @@ -230,10 +230,10 @@ func (ctx *generatorContext) removeStorageAt(account common.Hash) error { count++ - ctx.batch.Delete(key) + _ = ctx.batch.Delete(key) if ctx.batch.ValueSize() > ethdb.IdealBatchSize { - ctx.batch.Write() + _ = ctx.batch.Write() ctx.batch.Reset() } } @@ -255,10 +255,10 @@ func (ctx *generatorContext) removeStorageLeft() { for iter.Next() { count++ - ctx.batch.Delete(iter.Key()) + _ = ctx.batch.Delete(iter.Key()) if ctx.batch.ValueSize() > ethdb.IdealBatchSize { - ctx.batch.Write() + _ = ctx.batch.Write() ctx.batch.Reset() } } diff --git a/core/state/snapshot/conversion.go b/core/state/snapshot/conversion.go index 39d4c1b7a2..0910b6d47c 100644 --- a/core/state/snapshot/conversion.go +++ b/core/state/snapshot/conversion.go @@ -400,7 +400,7 @@ func stackTrieGenerate(db ethdb.KeyValueWriter, scheme string, owner common.Hash t := trie.NewStackTrieWithOwner(nodeWriter, owner) for leaf := range in { - t.Update(leaf.key[:], leaf.value) + _ = t.Update(leaf.key[:], leaf.value) } var root common.Hash diff --git a/core/state/snapshot/difflayer_test.go b/core/state/snapshot/difflayer_test.go index 692cb8a68a..ad8ad41af2 100644 --- a/core/state/snapshot/difflayer_test.go +++ b/core/state/snapshot/difflayer_test.go @@ -79,7 +79,7 @@ func TestMergeBasics(t *testing.T) { if rand.Intn(2) == 0 { accStorage := make(map[common.Hash][]byte) value := make([]byte, 32) - crand.Read(value) + _, _ = crand.Read(value) accStorage[randomHash()] = value storage[h] = accStorage } @@ -322,7 +322,7 @@ func BenchmarkSearchSlot(b *testing.B) { for i := 0; i < 5; i++ { value := make([]byte, 32) - crand.Read(value) + _, _ = crand.Read(value) accStorage[randomHash()] = value storage[accountKey] = accStorage } @@ -364,7 +364,7 @@ func BenchmarkFlatten(b *testing.B) { for i := 0; i < 20; i++ { value := make([]byte, 32) - crand.Read(value) + _, _ = crand.Read(value) accStorage[randomHash()] = value } @@ -422,7 +422,7 @@ func BenchmarkJournal(b *testing.B) { for i := 0; i < 200; i++ { value := make([]byte, 32) - crand.Read(value) + _, _ = crand.Read(value) accStorage[randomHash()] = value } diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index c25c79437c..49d9b3d689 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -247,7 +247,7 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [ if origin == nil && !diskMore { stackTr := trie.NewStackTrie(nil) for i, key := range keys { - stackTr.Update(key, vals[i]) + _ = stackTr.Update(key, vals[i]) } if gotRoot := stackTr.Hash(); gotRoot != root { @@ -396,8 +396,8 @@ func (dl *diskLayer) generateRange(ctx *generatorContext, trieId *trie.ID, prefi root, nodes := snapTrie.Commit(false) if nodes != nil { - tdb.Update(trie.NewWithNodeSet(nodes)) - tdb.Commit(root, false) + _ = tdb.Update(trie.NewWithNodeSet(nodes)) + _ = tdb.Commit(root, false) } resolver = func(owner common.Hash, path []byte, hash common.Hash) []byte { @@ -635,7 +635,7 @@ func generateAccounts(ctx *generatorContext, dl *diskLayer, accMarker []byte) er snapWipedAccountMeter.Mark(1) snapAccountWriteCounter.Inc(time.Since(start).Nanoseconds()) - ctx.removeStorageAt(account) + _ = ctx.removeStorageAt(account) return nil } diff --git a/core/state/sync_test.go b/core/state/sync_test.go index 1e561fdc7e..3209b8db02 100644 --- a/core/state/sync_test.go +++ b/core/state/sync_test.go @@ -191,7 +191,7 @@ func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) { // Create a random state to copy _, srcDb, srcRoot, srcAccounts := makeTestState() if commit { - srcDb.TrieDB().Commit(srcRoot, false) + _ = srcDb.TrieDB().Commit(srcRoot, false) } srcTrie, _ := trie.New(trie.StateTrieID(srcRoot), srcDb.TrieDB()) diff --git a/core/state/trie_prefetcher.go b/core/state/trie_prefetcher.go index c5f1bf1687..1f8be547fd 100644 --- a/core/state/trie_prefetcher.go +++ b/core/state/trie_prefetcher.go @@ -354,9 +354,9 @@ func (sf *subfetcher) loop() { sf.dups++ } else { if len(task) == common.AddressLength { - sf.trie.GetAccount(common.BytesToAddress(task)) + _, _ = sf.trie.GetAccount(common.BytesToAddress(task)) } else { - sf.trie.GetStorage(sf.addr, task) + _, _ = sf.trie.GetStorage(sf.addr, task) } sf.seen[string(task)] = struct{}{} diff --git a/core/state_prefetcher.go b/core/state_prefetcher.go index 381152e89a..495af33f71 100644 --- a/core/state_prefetcher.go +++ b/core/state_prefetcher.go @@ -89,7 +89,7 @@ func (p *statePrefetcher) Prefetch(block *types.Block, statedb *state.StateDB, c // precacheTransaction attempts to apply a transaction to the given state database // and uses the input parameters for its environment. The goal is not to execute // the transaction successfully, rather to warm up touched data slots. -func precacheTransaction(msg *Message, config *params.ChainConfig, gaspool *GasPool, statedb *state.StateDB, header *types.Header, evm *vm.EVM) error { +func precacheTransaction(msg *Message, _ *params.ChainConfig, gaspool *GasPool, statedb *state.StateDB, _ *types.Header, evm *vm.EVM) error { // Update the evm with the new transaction context. evm.Reset(NewEVMTxContext(msg), statedb) // Add addresses to access list if applicable diff --git a/core/state_transition.go b/core/state_transition.go index b8ac74fd8b..89d572bebf 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -82,6 +82,7 @@ func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation b dataLen := uint64(len(data)) // Bump the required gas by the amount of transactional data + // nolint:nestif if dataLen > 0 { // Zero and non-zero bytes are priced differently var nz uint64 diff --git a/core/tests/blockchain_repair_test.go b/core/tests/blockchain_repair_test.go index 40b82b8843..bb3e3b04cd 100644 --- a/core/tests/blockchain_repair_test.go +++ b/core/tests/blockchain_repair_test.go @@ -2020,7 +2020,7 @@ func TestIssue23496(t *testing.T) { t.Fatalf("Failed to import canonical chain start: %v", err) } - chain.StateCache().TrieDB().Commit(blocks[2].Root(), false) + _ = chain.StateCache().TrieDB().Commit(blocks[2].Root(), false) // Insert the remaining blocks if _, err := chain.InsertChain(blocks[3:]); err != nil { diff --git a/core/txpool/txpool.go b/core/txpool/txpool.go index 33f17cc20f..869c47a443 100644 --- a/core/txpool/txpool.go +++ b/core/txpool/txpool.go @@ -747,6 +747,7 @@ func (pool *TxPool) local() map[common.Address]types.Transactions { // rules, but does not check state-dependent validation such as sufficient balance. // This check is meant as an early check which only needs to be performed once, // and does not require the pool mutex to be held. +// nolint:gocognit func (pool *TxPool) validateTxBasics(tx *types.Transaction, local bool) error { // Accept only legacy transactions until EIP-2718/2930 activates. if !pool.eip2718.Load() && tx.Type() != types.LegacyTxType { @@ -852,7 +853,7 @@ func (pool *TxPool) validateTxBasics(tx *types.Transaction, local bool) error { // validateTx checks whether a transaction is valid according to the consensus // rules and adheres to some heuristic limits of the local node (price and size). -func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error { +func (pool *TxPool) validateTx(tx *types.Transaction, _ bool) error { // Signature has been checked already, this cannot error. from, _ := types.Sender(pool.signer, tx) // Ensure the transaction adheres to nonce ordering @@ -1213,7 +1214,6 @@ func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error { var ( errs []error news = make([]*types.Transaction, 0, len(txs)) - err error hash common.Hash ) @@ -1230,22 +1230,22 @@ func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error { continue } - if pool.config.AllowUnprotectedTxs { - pool.signer = types.NewFakeSigner(tx.ChainId()) - } + // Exclude transactions with basic errors, e.g. invalid signatures and + // insufficient intrinsic gas as soon as possible and cache senders + // in transactions before obtaining lock - // Exclude transactions with invalid signatures as soon as - // possible and cache senders in transactions before - // obtaining lock - _, err = types.Sender(pool.signer, tx) - if err != nil { - errs = append(errs, ErrInvalidSender) + if err := pool.validateTxBasics(tx, local); err != nil { + errs = append(errs, ErrAlreadyKnown) invalidTxMeter.Mark(1) continue } + if pool.config.AllowUnprotectedTxs { + pool.signer = types.NewFakeSigner(tx.ChainId()) + } + // Accumulate all unknown transactions for deeper processing news = append(news, tx) } diff --git a/core/txpool/txpool_test.go b/core/txpool/txpool_test.go index 0b2a1681cd..9aa1f59266 100644 --- a/core/txpool/txpool_test.go +++ b/core/txpool/txpool_test.go @@ -81,7 +81,7 @@ type testBlockChain struct { chainHeadFeed *event.Feed } -func newTestBlockChain(gasLimit uint64, statedb *state.StateDB, chainHeadFeed *event.Feed) *testBlockChain { +func newTestBlockChain(gasLimit uint64, statedb *state.StateDB, _ *event.Feed) *testBlockChain { bc := testBlockChain{statedb: statedb, chainHeadFeed: new(event.Feed)} bc.gasLimit.Store(gasLimit) @@ -145,7 +145,7 @@ func setupPool() (*TxPool, *ecdsa.PrivateKey) { return setupPoolWithConfig(params.TestChainConfig, testTxPoolConfig, txPoolGasLimit) } -func setupPoolWithConfig(config *params.ChainConfig, txPoolConfig Config, gasLimit uint64, options ...func(pool *TxPool)) (*TxPool, *ecdsa.PrivateKey) { +func setupPoolWithConfig(config *params.ChainConfig, txPoolConfig Config, _ uint64, options ...func(pool *TxPool)) (*TxPool, *ecdsa.PrivateKey) { statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := newTestBlockChain(10000000, statedb, new(event.Feed)) @@ -775,6 +775,7 @@ func TestDropping(t *testing.T) { // Tests that if a transaction is dropped from the current pending pool (e.g. out // of fund), all consecutive (still valid, but not executable) transactions are // postponed back into the future queue to prevent broadcasting them. +// nolint:gocognit func TestPostponing(t *testing.T) { t.Parallel() @@ -1178,7 +1179,10 @@ func TestQueueTimeLimitingNoLocals(t *testing.T) { testQueueTimeLimiting(t, true) } +// nolint:gocognit func testQueueTimeLimiting(t *testing.T, nolocals bool) { + t.Helper() + // Reduce the eviction interval to a testable amount defer func(old time.Duration) { evictionInterval = old }(evictionInterval) evictionInterval = time.Millisecond * 100 diff --git a/core/types/withdrawal.go b/core/types/withdrawal.go index d1ad918f98..5524c389fd 100644 --- a/core/types/withdrawal.go +++ b/core/types/withdrawal.go @@ -52,5 +52,5 @@ func (s Withdrawals) Len() int { return len(s) } // because we assume that *Withdrawal will only ever contain valid withdrawals that were either // constructed by decoding or via public API in this package. func (s Withdrawals) EncodeIndex(i int, w *bytes.Buffer) { - rlp.Encode(w, s[i]) + _ = rlp.Encode(w, s[i]) } diff --git a/eth/backend.go b/eth/backend.go index b05aa385f1..36de38edea 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -262,7 +262,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { return nil, err } - ethereum.engine.VerifyHeader(ethereum.blockchain, ethereum.blockchain.CurrentHeader(), true) // TODO think on it + _ = ethereum.engine.VerifyHeader(ethereum.blockchain, ethereum.blockchain.CurrentHeader(), true) // TODO think on it // BOR changes ethereum.APIBackend.gpo.ProcessCache() @@ -303,7 +303,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { } ethereum.miner = miner.New(ethereum, &config.Miner, ethereum.blockchain.Config(), ethereum.EventMux(), ethereum.engine, ethereum.isLocalBlock) - ethereum.miner.SetExtra(makeExtraData(config.Miner.ExtraData)) + _ = ethereum.miner.SetExtra(makeExtraData(config.Miner.ExtraData)) // Setup DNS discovery iterators. dnsclient := dnsdisc.NewClient(dnsdisc.Config{}) diff --git a/eth/catalyst/api.go b/eth/catalyst/api.go index 8a8fcc7beb..a6a0a08d2e 100644 --- a/eth/catalyst/api.go +++ b/eth/catalyst/api.go @@ -206,6 +206,7 @@ func (api *ConsensusAPI) verifyPayloadAttributes(attr *engine.PayloadAttributes) return nil } +// nolint:gocognit func (api *ConsensusAPI) forkchoiceUpdated(update engine.ForkchoiceStateV1, payloadAttributes *engine.PayloadAttributes) (engine.ForkChoiceResponse, error) { api.forkchoiceLock.Lock() defer api.forkchoiceLock.Unlock() @@ -738,6 +739,7 @@ func (api *ConsensusAPI) heartbeat() { // If there have been no updates for the past while, warn the user // that the beacon client is probably offline + // nolint:nestif if api.eth.BlockChain().Config().TerminalTotalDifficultyPassed || api.eth.Merger().TDDReached() { if time.Since(lastForkchoiceUpdate) <= beaconUpdateConsensusTimeout || time.Since(lastNewPayloadUpdate) <= beaconUpdateConsensusTimeout { offlineLogged = time.Time{} diff --git a/eth/catalyst/api_test.go b/eth/catalyst/api_test.go index e8fc7f6a18..72be8ed121 100644 --- a/eth/catalyst/api_test.go +++ b/eth/catalyst/api_test.go @@ -315,6 +315,7 @@ func TestInvalidPayloadTimestamp(t *testing.T) { } } +// nolint:goconst func TestEth2NewBlock(t *testing.T) { t.Skip("ETH2 in Bor") @@ -539,7 +540,10 @@ func TestFullAPI(t *testing.T) { setupBlocks(t, ethservice, 10, parent, callback, nil) } +// nolint:unparam,prealloc func setupBlocks(t *testing.T, ethservice *eth.Ethereum, n int, parent *types.Header, callback func(parent *types.Header), withdrawals [][]*types.Withdrawal) []*types.Header { + t.Helper() + api := NewConsensusAPI(ethservice) var blocks []*types.Header @@ -925,6 +929,7 @@ func TestTrickRemoteBlockCache(t *testing.T) { setupBlocks(t, ethserviceA, 10, commonAncestor, func(parent *types.Header) {}, nil) commonAncestor = ethserviceA.BlockChain().CurrentBlock() + // nolint:prealloc var invalidChain []*engine.ExecutableData // create a valid payload (P1) //payload1 := getNewPayload(t, apiA, commonAncestor) @@ -1445,7 +1450,7 @@ func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) { statedb, _ := ethservice.BlockChain().StateAt(parent.Root) nonce := statedb.GetNonce(testAddr) tx, _ := types.SignTx(types.NewContractCreation(nonce, new(big.Int), 1000000, big.NewInt(2*params.InitialBaseFee), logCode), types.LatestSigner(ethservice.BlockChain().Config()), testKey) - ethservice.TxPool().AddLocal(tx) + _ = ethservice.TxPool().AddLocal(tx) } withdrawals := make([][]*types.Withdrawal, 10) @@ -1455,7 +1460,7 @@ func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) { for i := 2; i < len(withdrawals); i++ { addr := make([]byte, 20) - crand.Read(addr) + _, _ = crand.Read(addr) withdrawals[i] = []*types.Withdrawal{ {Index: rand.Uint64(), Validator: rand.Uint64(), Amount: rand.Uint64(), Address: common.BytesToAddress(addr)}, @@ -1473,7 +1478,8 @@ func setupBodies(t *testing.T) (*node.Node, *eth.Ethereum, []*types.Block) { } func allHashes(blocks []*types.Block) []common.Hash { - var hashes []common.Hash + hashes := make([]common.Hash, 0, len(blocks)) + for _, b := range blocks { hashes = append(hashes, b.Hash()) } @@ -1481,7 +1487,8 @@ func allHashes(blocks []*types.Block) []common.Hash { return hashes } func allBodies(blocks []*types.Block) []*types.Body { - var bodies []*types.Body + bodies := make([]*types.Body, 0, len(blocks)) + for _, b := range blocks { bodies = append(bodies, b.Body()) } diff --git a/eth/downloader/beaconsync.go b/eth/downloader/beaconsync.go index 80aab21822..e791db998c 100644 --- a/eth/downloader/beaconsync.go +++ b/eth/downloader/beaconsync.go @@ -313,6 +313,8 @@ func (d *Downloader) fetchBeaconHeaders(from uint64) error { // If the pivot became stale (older than 2*64-8 (bit of wiggle room)), // move it ahead to HEAD-64 d.pivotLock.Lock() + + // nolint:nestif if d.pivotHeader != nil { if head.Number.Uint64() > d.pivotHeader.Number.Uint64()+2*uint64(fsMinFullBlocks)-8 { // Retrieve the next pivot header, either from skeleton chain diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index 9fc3eb31ff..b1a4d88976 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -1992,6 +1992,7 @@ func (d *Downloader) DeliverSnapPacket(peer *snap.Peer, packet snap.Packet) erro // readHeaderRange returns a list of headers, using the given last header as the base, // and going backwards towards genesis. This method assumes that the caller already has // placed a reasonable cap on count. +// nolint:prealloc func (d *Downloader) readHeaderRange(last *types.Header, count int) []*types.Header { var ( current = last diff --git a/eth/downloader/downloader_test.go b/eth/downloader/downloader_test.go index 11ee4c9809..ddf2bf77d3 100644 --- a/eth/downloader/downloader_test.go +++ b/eth/downloader/downloader_test.go @@ -63,7 +63,9 @@ func newTester(t *testing.T) *downloadTester { } // newTester creates a new downloader test mocker. -func newTesterWithNotification(t *testing.T, success func()) *downloadTester { +func newTesterWithNotification(t *testing.T, _ func()) *downloadTester { + t.Helper() + freezer := t.TempDir() db, err := rawdb.NewDatabaseWithFreezer(rawdb.NewMemoryDatabase(), freezer, "", false) @@ -1928,7 +1930,7 @@ func testBeaconSync(t *testing.T, protocol uint, mode SyncMode) { // Build the local chain segment if it's required if c.local > 0 { - tester.chain.InsertChain(chain.blocks[1 : c.local+1]) + _, _ = tester.chain.InsertChain(chain.blocks[1 : c.local+1]) } if err := tester.downloader.BeaconSync(mode, chain.blocks[len(chain.blocks)-1].Header(), nil); err != nil { diff --git a/eth/downloader/skeleton_test.go b/eth/downloader/skeleton_test.go index 8cf2ad4dad..b7040113e8 100644 --- a/eth/downloader/skeleton_test.go +++ b/eth/downloader/skeleton_test.go @@ -380,15 +380,16 @@ func TestSkeletonSyncInit(t *testing.T) { skeleton := newSkeleton(db, newPeerSet(), nil, newHookedBackfiller()) skeleton.syncStarting = func() { close(wait) } - skeleton.Sync(tt.head, nil, true) + _ = skeleton.Sync(tt.head, nil, true) <-wait - skeleton.Terminate() + + _ = skeleton.Terminate() // Ensure the correct resulting sync status var progress skeletonProgress - json.Unmarshal(rawdb.ReadSkeletonSyncStatus(db), &progress) + _ = json.Unmarshal(rawdb.ReadSkeletonSyncStatus(db), &progress) if len(progress.Subchains) != len(tt.newstate) { t.Errorf("test %d: subchain count mismatch: have %d, want %d", i, len(progress.Subchains), len(tt.newstate)) @@ -498,7 +499,7 @@ func TestSkeletonSyncExtend(t *testing.T) { skeleton := newSkeleton(db, newPeerSet(), nil, newHookedBackfiller()) skeleton.syncStarting = func() { close(wait) } - skeleton.Sync(tt.head, nil, true) + _ = skeleton.Sync(tt.head, nil, true) <-wait @@ -544,7 +545,8 @@ func TestSkeletonSyncRetrievals(t *testing.T) { }) } // Some tests require a forking side chain to trigger cornercases. - var sidechain []*types.Header + sidechain := make([]*types.Header, 0, len(chain)) + for i := 0; i < len(chain)/2; i++ { // Fork at block #5000 sidechain = append(sidechain, chain[i]) } @@ -853,7 +855,7 @@ func TestSkeletonSyncRetrievals(t *testing.T) { filler = &hookedBackfiller{ resumeHook: func() { var progress skeletonProgress - json.Unmarshal(rawdb.ReadSkeletonSyncStatus(db), &progress) + _ = json.Unmarshal(rawdb.ReadSkeletonSyncStatus(db), &progress) for progress.Subchains[0].Tail < progress.Subchains[0].Head { header := rawdb.ReadSkeletonHeader(db, progress.Subchains[0].Tail) @@ -882,7 +884,7 @@ func TestSkeletonSyncRetrievals(t *testing.T) { } // Create a skeleton sync and run a cycle skeleton := newSkeleton(db, peerset, drop, filler) - skeleton.Sync(tt.head, nil, true) + _ = skeleton.Sync(tt.head, nil, true) var progress skeletonProgress // Wait a bit (bleah) for the initial sync loop to go to idle. This might @@ -943,7 +945,7 @@ func TestSkeletonSyncRetrievals(t *testing.T) { } // Apply the post-init events if there's any if tt.newHead != nil { - skeleton.Sync(tt.newHead, nil, true) + _ = skeleton.Sync(tt.newHead, nil, true) } if tt.newPeer != nil { diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go index b9f4c5f61f..77b127a3a8 100644 --- a/eth/ethconfig/config.go +++ b/eth/ethconfig/config.go @@ -253,6 +253,7 @@ type Config struct { // CreateConsensusEngine creates a consensus engine for the given chain configuration. func CreateConsensusEngine(stack *node.Node, chainConfig *params.ChainConfig, ethConfig *Config, ethashConfig *ethash.Config, cliqueConfig *params.CliqueConfig, notify []string, noverify bool, db ethdb.Database, blockchainAPI *ethapi.BlockChainAPI) consensus.Engine { var engine consensus.Engine + // nolint:nestif if cliqueConfig != nil { // If proof-of-authority is requested, set it up engine = clique.New(cliqueConfig, db) diff --git a/eth/filters/api.go b/eth/filters/api.go index 39d9eb793b..f0c1a79dad 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -171,9 +171,9 @@ func (api *FilterAPI) NewPendingTransactions(ctx context.Context, fullTx *bool) for _, tx := range txs { if fullTx != nil && *fullTx { rpcTx := ethapi.NewRPCPendingTransaction(tx, latest, chainConfig) - notifier.Notify(rpcSub.ID, rpcTx) + _ = notifier.Notify(rpcSub.ID, rpcTx) } else { - notifier.Notify(rpcSub.ID, tx.Hash()) + _ = notifier.Notify(rpcSub.ID, tx.Hash()) } } case <-rpcSub.Err(): diff --git a/eth/filters/filter_system_test.go b/eth/filters/filter_system_test.go index 1b79ce5e88..dc88b1ba68 100644 --- a/eth/filters/filter_system_test.go +++ b/eth/filters/filter_system_test.go @@ -77,6 +77,7 @@ func (b *testBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumbe num uint64 ) + // nolint:exhaustive switch blockNr { case rpc.LatestBlockNumber: hash = rawdb.ReadHeadBlockHash(b.db) @@ -221,7 +222,7 @@ func (b *testBackend) ServiceFilter(ctx context.Context, session *bloombits.Matc }() } -func newTestFilterSystem(t testing.TB, db ethdb.Database, cfg Config) (*testBackend, *FilterSystem) { +func newTestFilterSystem(_ testing.TB, db ethdb.Database, cfg Config) (*testBackend, *FilterSystem) { backend := &testBackend{db: db} sys := NewFilterSystem(backend, cfg) @@ -807,7 +808,7 @@ func TestPendingLogsSubscription(t *testing.T) { <-testCases[i].sub.Err() } } - +// nolint:gocognit func TestLightFilterLogs(t *testing.T) { t.Parallel() diff --git a/eth/gasprice/feehistory.go b/eth/gasprice/feehistory.go index 56b4f8bf76..6039c4d63d 100644 --- a/eth/gasprice/feehistory.go +++ b/eth/gasprice/feehistory.go @@ -234,6 +234,7 @@ func (oracle *Oracle) resolveBlockRange(ctx context.Context, reqEnd rpc.BlockNum // // Note: baseFee includes the next block after the newest of the returned range, because this // value can be derived from the newest block. +// nolint:gocognit func (oracle *Oracle) FeeHistory(ctx context.Context, blocks uint64, unresolvedLastBlock rpc.BlockNumber, rewardPercentiles []float64) (*big.Int, [][]*big.Int, []*big.Int, []float64, error) { if blocks < 1 { return common.Big0, nil, nil, nil, nil // returning with no data and no error means there are no retrievable blocks diff --git a/eth/handler.go b/eth/handler.go index 687f74513d..d6e6487b32 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -210,6 +210,7 @@ func newHandler(config *handlerConfig) (*handler, error) { } // Construct the downloader (long sync) h.downloader = downloader.New(h.checkpointNumber, config.Database, h.eventMux, h.chain, nil, h.removePeer, success, config.checker) + // nolint:nestif if ttd := h.chain.Config().TerminalTotalDifficulty; ttd != nil { if h.chain.Config().TerminalTotalDifficultyPassed { log.Info("Chain post-merge, sync via beacon client") diff --git a/eth/protocols/eth/handler_test.go b/eth/protocols/eth/handler_test.go index 1b4af22fb5..b8fa856daf 100644 --- a/eth/protocols/eth/handler_test.go +++ b/eth/protocols/eth/handler_test.go @@ -114,7 +114,7 @@ func newTestBackendWithGenerator(blocks int, shanghai bool, generator func(int, } for _, block := range bs { - chain.StateCache().TrieDB().Commit(block.Root(), false) + _ = chain.StateCache().TrieDB().Commit(block.Root(), false) } txconfig := txpool.DefaultConfig diff --git a/eth/protocols/eth/protocol.go b/eth/protocols/eth/protocol.go index dd55b9b87b..2154c48d9a 100644 --- a/eth/protocols/eth/protocol.go +++ b/eth/protocols/eth/protocol.go @@ -383,6 +383,7 @@ func (*GetReceiptsPacket) Kind() byte { return GetReceiptsMsg } func (*ReceiptsPacket) Name() string { return "Receipts" } func (*ReceiptsPacket) Kind() byte { return ReceiptsMsg } +// nolint:goconst func (*NewPooledTransactionHashesPacket66) Name() string { return "NewPooledTransactionHashes" } func (*NewPooledTransactionHashesPacket66) Kind() byte { return NewPooledTransactionHashesMsg } diff --git a/eth/protocols/snap/handler.go b/eth/protocols/snap/handler.go index 96ea6cb412..0eabf9dd4b 100644 --- a/eth/protocols/snap/handler.go +++ b/eth/protocols/snap/handler.go @@ -431,6 +431,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP // Generate the Merkle proofs for the first and last storage slot, but // only if the response was capped. If the entire storage trie included // in the response, no need for any proofs. + // nolint:nestif if origin != (common.Hash{}) || (abort && len(storage) > 0) { // Request started at a non-zero hash or was capped prematurely, add // the endpoint Merkle proofs diff --git a/eth/protocols/snap/sort_test.go b/eth/protocols/snap/sort_test.go index 2ed06566b5..9a13c05090 100644 --- a/eth/protocols/snap/sort_test.go +++ b/eth/protocols/snap/sort_test.go @@ -24,6 +24,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) +// nolint:prealloc func hexToNibbles(s string) []byte { if len(s) >= 2 && s[0] == '0' && s[1] == 'x' { s = s[2:] @@ -38,6 +39,7 @@ func hexToNibbles(s string) []byte { return common.Hex2Bytes(string(s2)) } +// nolint:prealloc func TestRequestSorting(t *testing.T) { t.Parallel() diff --git a/eth/protocols/snap/sync.go b/eth/protocols/snap/sync.go index c9bf9fe571..1d0d7a88ea 100644 --- a/eth/protocols/snap/sync.go +++ b/eth/protocols/snap/sync.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "golang.org/x/crypto/sha3" gomath "math" "math/big" "math/rand" @@ -30,6 +29,8 @@ import ( "sync/atomic" "time" + "golang.org/x/crypto/sha3" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/core/rawdb" @@ -3351,7 +3352,8 @@ func (t *healRequestSort) Merge() []TrieNodePathSet { // sortByAccountPath takes hashes and paths, and sorts them. After that, it generates // the TrieNodePaths and merges paths which belongs to the same account path. func sortByAccountPath(paths []string, hashes []common.Hash) ([]string, []common.Hash, []trie.SyncPath, []TrieNodePathSet) { - var syncPaths []trie.SyncPath + syncPaths := make([]trie.SyncPath, 0, len(paths)) + for _, path := range paths { syncPaths = append(syncPaths, trie.NewSyncPath([]byte(path))) } diff --git a/eth/protocols/snap/sync_test.go b/eth/protocols/snap/sync_test.go index 3d0701f4b9..f640ca7d4b 100644 --- a/eth/protocols/snap/sync_test.go +++ b/eth/protocols/snap/sync_test.go @@ -1529,9 +1529,10 @@ func makeAccountTrieNoStorage(n int) (string, *trie.Trie, entrySlice) { var ( db = trie.NewDatabase(rawdb.NewMemoryDatabase()) accTrie = trie.NewEmpty(db) - entries entrySlice ) + entries := make(entrySlice, uint64(n)) + for i := uint64(1); i <= uint64(n); i++ { value, _ := rlp.EncodeToBytes(&types.StateAccount{ Nonce: i, @@ -1549,7 +1550,7 @@ func makeAccountTrieNoStorage(n int) (string, *trie.Trie, entrySlice) { // Commit the state changes into db and re-create the trie // for accessing later. root, nodes := accTrie.Commit(false) - db.Update(trie.NewWithNodeSet(nodes)) + _ = db.Update(trie.NewWithNodeSet(nodes)) accTrie, _ = trie.New(trie.StateTrieID(root), db) @@ -1614,7 +1615,7 @@ func makeBoundaryAccountTrie(n int) (string, *trie.Trie, entrySlice) { // Commit the state changes into db and re-create the trie // for accessing later. root, nodes := accTrie.Commit(false) - db.Update(trie.NewWithNodeSet(nodes)) + _ = db.Update(trie.NewWithNodeSet(nodes)) accTrie, _ = trie.New(trie.StateTrieID(root), db) @@ -1643,7 +1644,7 @@ func makeAccountTrieWithStorageWithUniqueStorage(accounts, slots int, code bool) } // Create a storage trie stRoot, stNodes, stEntries := makeStorageTrieWithSeed(common.BytesToHash(key), uint64(slots), i, db) - nodes.Merge(stNodes) + _ = nodes.Merge(stNodes) value, _ := rlp.EncodeToBytes(&types.StateAccount{ Nonce: i, @@ -1662,10 +1663,10 @@ func makeAccountTrieWithStorageWithUniqueStorage(accounts, slots int, code bool) // Commit account trie root, set := accTrie.Commit(true) - nodes.Merge(set) + _ = nodes.Merge(set) // Commit gathered dirty nodes into database - db.Update(nodes) + _ = db.Update(nodes) // Re-create tries with new root accTrie, _ = trie.New(trie.StateTrieID(root), db) @@ -1712,7 +1713,7 @@ func makeAccountTrieWithStorage(accounts, slots int, code, boundary bool) (strin stRoot, stNodes, stEntries = makeStorageTrieWithSeed(common.BytesToHash(key), uint64(slots), 0, db) } - nodes.Merge(stNodes) + _ = nodes.Merge(stNodes) value, _ := rlp.EncodeToBytes(&types.StateAccount{ Nonce: i, @@ -1732,10 +1733,10 @@ func makeAccountTrieWithStorage(accounts, slots int, code, boundary bool) (strin // Commit account trie root, set := accTrie.Commit(true) - nodes.Merge(set) + _ = nodes.Merge(set) // Commit gathered dirty nodes into database - db.Update(nodes) + _ = db.Update(nodes) // Re-create tries with new root accTrie, err := trie.New(trie.StateTrieID(root), db) diff --git a/eth/state_accessor.go b/eth/state_accessor.go index d23e6940ff..92081a86a5 100644 --- a/eth/state_accessor.go +++ b/eth/state_accessor.go @@ -57,6 +57,8 @@ var noopReleaser = tracers.StateReleaseFunc(func() {}) // - preferDisk: this arg can be used by the caller to signal that even though the 'base' is // provided, it would be preferable to start from a fresh state, if we have it // on disk. +// +// nolint:gocognit func (eth *Ethereum) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, readOnly bool, preferDisk bool) (statedb *state.StateDB, release tracers.StateReleaseFunc, err error) { var ( current *types.Block diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 45d62ece5b..9aae926060 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -307,7 +307,7 @@ func (api *API) TraceChain(ctx context.Context, start, end rpc.BlockNumber, conf go func() { for result := range resCh { - notifier.Notify(sub.ID, result) + _ = notifier.Notify(sub.ID, result) } }() @@ -319,6 +319,7 @@ func (api *API) TraceChain(ctx context.Context, start, end rpc.BlockNumber, conf // the end block but excludes the start one. The return value will be one item per // transaction, dependent on the requested tracer. // The tracing procedure should be aborted in case the closed signal is received. +// nolint:gocognit func (api *API) traceChain(start, end *types.Block, config *TraceConfig, closed <-chan interface{}) chan *blockTraceResult { if config == nil { config = &TraceConfig{ diff --git a/eth/tracers/internal/tracetest/calltrace_test.go b/eth/tracers/internal/tracetest/calltrace_test.go index efd35a37ec..24dc50627c 100644 --- a/eth/tracers/internal/tracetest/calltrace_test.go +++ b/eth/tracers/internal/tracetest/calltrace_test.go @@ -174,7 +174,7 @@ func testCallTracer(tracerName string, dirPath string, t *testing.T) { // we remove the legacy tracer. var x callTrace - json.Unmarshal(res, &x) + _ = json.Unmarshal(res, &x) res, _ = json.Marshal(x) } diff --git a/eth/tracers/internal/tracetest/flat_calltrace_test.go b/eth/tracers/internal/tracetest/flat_calltrace_test.go index e9c702c517..6803af168a 100644 --- a/eth/tracers/internal/tracetest/flat_calltrace_test.go +++ b/eth/tracers/internal/tracetest/flat_calltrace_test.go @@ -199,13 +199,13 @@ func jsonEqualFlat(x, y interface{}) bool { yTrace := new([]flatCallTrace) if xj, err := json.Marshal(x); err == nil { - json.Unmarshal(xj, xTrace) + _ = json.Unmarshal(xj, xTrace) } else { return false } if yj, err := json.Marshal(y); err == nil { - json.Unmarshal(yj, yTrace) + _ = json.Unmarshal(yj, yTrace) } else { return false } diff --git a/eth/tracers/internal/tracetest/prestate_test.go b/eth/tracers/internal/tracetest/prestate_test.go index 89c980f78c..e2e1843eb0 100644 --- a/eth/tracers/internal/tracetest/prestate_test.go +++ b/eth/tracers/internal/tracetest/prestate_test.go @@ -55,20 +55,23 @@ type testcase struct { func TestPrestateTracerLegacy(t *testing.T) { t.Parallel() - testPrestateDiffTracer("prestateTracerLegacy", "prestate_tracer_legacy", t) + testPrestateDiffTracer(t, "prestateTracerLegacy", "prestate_tracer_legacy") } func TestPrestateTracer(t *testing.T) { t.Parallel() - testPrestateDiffTracer("prestateTracer", "prestate_tracer", t) + testPrestateDiffTracer(t, "prestateTracer", "prestate_tracer") } func TestPrestateWithDiffModeTracer(t *testing.T) { t.Parallel() - testPrestateDiffTracer("prestateTracer", "prestate_tracer_with_diff_mode", t) + testPrestateDiffTracer(t, "prestateTracer", "prestate_tracer_with_diff_mode") } -func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) { +// nolint:gocognit +func testPrestateDiffTracer(t *testing.T, tracerName string, dirPath string) { + t.Helper() + files, err := os.ReadDir(filepath.Join("testdata", dirPath)) if err != nil { t.Fatalf("failed to retrieve tracer test suite: %v", err) @@ -146,7 +149,7 @@ func testPrestateDiffTracer(tracerName string, dirPath string, t *testing.T) { // we remove the legacy tracer. var x prestateTrace - json.Unmarshal(res, &x) + _ = json.Unmarshal(res, &x) res, _ = json.Marshal(x) } diff --git a/eth/tracers/js/goja.go b/eth/tracers/js/goja.go index eb16fcf42f..d9bda68f0a 100644 --- a/eth/tracers/js/goja.go +++ b/eth/tracers/js/goja.go @@ -166,7 +166,7 @@ func newJsTracer(code string, ctx *tracers.Context, cfg json.RawMessage) (tracer } } - t.setTypeConverters() + _ = t.setTypeConverters() t.setBuiltinFunctions() ret, err := vm.RunString("(" + code + ")") @@ -404,10 +404,11 @@ func wrapError(context string, err error) error { // setBuiltinFunctions injects Go functions which are available to tracers into the environment. // It depends on type converters having been set up. +// nolint:gocognit func (t *jsTracer) setBuiltinFunctions() { vm := t.vm // TODO: load console from goja-nodejs - vm.Set("toHex", func(v goja.Value) string { + _ = vm.Set("toHex", func(v goja.Value) string { b, err := t.fromBuf(vm, v, false) if err != nil { vm.Interrupt(err) @@ -416,7 +417,7 @@ func (t *jsTracer) setBuiltinFunctions() { return hexutil.Encode(b) }) - vm.Set("toWord", func(v goja.Value) goja.Value { + _ = vm.Set("toWord", func(v goja.Value) goja.Value { // TODO: add test with []byte len < 32 or > 32 b, err := t.fromBuf(vm, v, true) if err != nil { @@ -434,7 +435,7 @@ func (t *jsTracer) setBuiltinFunctions() { return res }) - vm.Set("toAddress", func(v goja.Value) goja.Value { + _ = vm.Set("toAddress", func(v goja.Value) goja.Value { a, err := t.fromBuf(vm, v, true) if err != nil { vm.Interrupt(err) @@ -451,7 +452,7 @@ func (t *jsTracer) setBuiltinFunctions() { return res }) - vm.Set("toContract", func(from goja.Value, nonce uint) goja.Value { + _ = vm.Set("toContract", func(from goja.Value, nonce uint) goja.Value { a, err := t.fromBuf(vm, from, true) if err != nil { vm.Interrupt(err) @@ -469,7 +470,7 @@ func (t *jsTracer) setBuiltinFunctions() { return res }) - vm.Set("toContract2", func(from goja.Value, salt string, initcode goja.Value) goja.Value { + _ = vm.Set("toContract2", func(from goja.Value, salt string, initcode goja.Value) goja.Value { a, err := t.fromBuf(vm, from, true) if err != nil { vm.Interrupt(err) @@ -496,7 +497,7 @@ func (t *jsTracer) setBuiltinFunctions() { return res }) - vm.Set("isPrecompiled", func(v goja.Value) bool { + _ = vm.Set("isPrecompiled", func(v goja.Value) bool { a, err := t.fromBuf(vm, v, true) if err != nil { vm.Interrupt(err) @@ -512,7 +513,7 @@ func (t *jsTracer) setBuiltinFunctions() { return false }) - vm.Set("slice", func(slice goja.Value, start, end int) goja.Value { + _ = vm.Set("slice", func(slice goja.Value, start, end int) goja.Value { b, err := t.fromBuf(vm, slice, false) if err != nil { vm.Interrupt(err) @@ -589,9 +590,9 @@ func (o *opObj) IsPush() bool { func (o *opObj) setupObject() *goja.Object { obj := o.vm.NewObject() - obj.Set("toNumber", o.vm.ToValue(o.ToNumber)) - obj.Set("toString", o.vm.ToValue(o.ToString)) - obj.Set("isPush", o.vm.ToValue(o.IsPush)) + _ = obj.Set("toNumber", o.vm.ToValue(o.ToNumber)) + _ = obj.Set("toString", o.vm.ToValue(o.ToString)) + _ = obj.Set("isPush", o.vm.ToValue(o.IsPush)) return obj } @@ -671,9 +672,9 @@ func (mo *memoryObj) Length() int { func (m *memoryObj) setupObject() *goja.Object { o := m.vm.NewObject() - o.Set("slice", m.vm.ToValue(m.Slice)) - o.Set("getUint", m.vm.ToValue(m.GetUint)) - o.Set("length", m.vm.ToValue(m.Length)) + _ = o.Set("slice", m.vm.ToValue(m.Slice)) + _ = o.Set("getUint", m.vm.ToValue(m.GetUint)) + _ = o.Set("length", m.vm.ToValue(m.Length)) return o } @@ -716,8 +717,8 @@ func (s *stackObj) Length() int { func (s *stackObj) setupObject() *goja.Object { o := s.vm.NewObject() - o.Set("peek", s.vm.ToValue(s.Peek)) - o.Set("length", s.vm.ToValue(s.Length)) + _ = o.Set("peek", s.vm.ToValue(s.Peek)) + _ = o.Set("length", s.vm.ToValue(s.Length)) return o } @@ -821,11 +822,11 @@ func (do *dbObj) Exists(addrSlice goja.Value) bool { func (do *dbObj) setupObject() *goja.Object { o := do.vm.NewObject() - o.Set("getBalance", do.vm.ToValue(do.GetBalance)) - o.Set("getNonce", do.vm.ToValue(do.GetNonce)) - o.Set("getCode", do.vm.ToValue(do.GetCode)) - o.Set("getState", do.vm.ToValue(do.GetState)) - o.Set("exists", do.vm.ToValue(do.Exists)) + _ = o.Set("getBalance", do.vm.ToValue(do.GetBalance)) + _ = o.Set("getNonce", do.vm.ToValue(do.GetNonce)) + _ = o.Set("getCode", do.vm.ToValue(do.GetCode)) + _ = o.Set("getState", do.vm.ToValue(do.GetState)) + _ = o.Set("exists", do.vm.ToValue(do.Exists)) return o } @@ -887,10 +888,10 @@ func (co *contractObj) GetInput() goja.Value { func (c *contractObj) setupObject() *goja.Object { o := c.vm.NewObject() - o.Set("getCaller", c.vm.ToValue(c.GetCaller)) - o.Set("getAddress", c.vm.ToValue(c.GetAddress)) - o.Set("getValue", c.vm.ToValue(c.GetValue)) - o.Set("getInput", c.vm.ToValue(c.GetInput)) + _ = o.Set("getCaller", c.vm.ToValue(c.GetCaller)) + _ = o.Set("getAddress", c.vm.ToValue(c.GetAddress)) + _ = o.Set("getValue", c.vm.ToValue(c.GetValue)) + _ = o.Set("getInput", c.vm.ToValue(c.GetInput)) return o } @@ -969,12 +970,12 @@ func (f *callframe) GetValue() goja.Value { func (f *callframe) setupObject() *goja.Object { o := f.vm.NewObject() - o.Set("getType", f.vm.ToValue(f.GetType)) - o.Set("getFrom", f.vm.ToValue(f.GetFrom)) - o.Set("getTo", f.vm.ToValue(f.GetTo)) - o.Set("getInput", f.vm.ToValue(f.GetInput)) - o.Set("getGas", f.vm.ToValue(f.GetGas)) - o.Set("getValue", f.vm.ToValue(f.GetValue)) + _ = o.Set("getType", f.vm.ToValue(f.GetType)) + _ = o.Set("getFrom", f.vm.ToValue(f.GetFrom)) + _ = o.Set("getTo", f.vm.ToValue(f.GetTo)) + _ = o.Set("getInput", f.vm.ToValue(f.GetInput)) + _ = o.Set("getGas", f.vm.ToValue(f.GetGas)) + _ = o.Set("getValue", f.vm.ToValue(f.GetValue)) return o } @@ -1012,9 +1013,9 @@ func (r *callframeResult) GetError() goja.Value { func (r *callframeResult) setupObject() *goja.Object { o := r.vm.NewObject() - o.Set("getGasUsed", r.vm.ToValue(r.GetGasUsed)) - o.Set("getOutput", r.vm.ToValue(r.GetOutput)) - o.Set("getError", r.vm.ToValue(r.GetError)) + _ = o.Set("getGasUsed", r.vm.ToValue(r.GetGasUsed)) + _ = o.Set("getOutput", r.vm.ToValue(r.GetOutput)) + _ = o.Set("getError", r.vm.ToValue(r.GetError)) return o } @@ -1052,17 +1053,17 @@ func (l *steplog) GetError() goja.Value { func (l *steplog) setupObject() *goja.Object { o := l.vm.NewObject() // Setup basic fields. - o.Set("getPC", l.vm.ToValue(l.GetPC)) - o.Set("getGas", l.vm.ToValue(l.GetGas)) - o.Set("getCost", l.vm.ToValue(l.GetCost)) - o.Set("getDepth", l.vm.ToValue(l.GetDepth)) - o.Set("getRefund", l.vm.ToValue(l.GetRefund)) - o.Set("getError", l.vm.ToValue(l.GetError)) + _ = o.Set("getPC", l.vm.ToValue(l.GetPC)) + _ = o.Set("getGas", l.vm.ToValue(l.GetGas)) + _ = o.Set("getCost", l.vm.ToValue(l.GetCost)) + _ = o.Set("getDepth", l.vm.ToValue(l.GetDepth)) + _ = o.Set("getRefund", l.vm.ToValue(l.GetRefund)) + _ = o.Set("getError", l.vm.ToValue(l.GetError)) // Setup nested objects. - o.Set("op", l.op.setupObject()) - o.Set("stack", l.stack.setupObject()) - o.Set("memory", l.memory.setupObject()) - o.Set("contract", l.contract.setupObject()) + _ = o.Set("op", l.op.setupObject()) + _ = o.Set("stack", l.stack.setupObject()) + _ = o.Set("memory", l.memory.setupObject()) + _ = o.Set("contract", l.contract.setupObject()) return o } diff --git a/eth/tracers/logger/logger_json.go b/eth/tracers/logger/logger_json.go index 76c5fec5b1..1d693f9a8b 100644 --- a/eth/tracers/logger/logger_json.go +++ b/eth/tracers/logger/logger_json.go @@ -95,6 +95,7 @@ func (l *JSONLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { errMsg = err.Error() } + // nolint:errchkjson _ = l.encoder.Encode(endLog{common.Bytes2Hex(output), math.HexOrDecimal64(gasUsed), errMsg}) } diff --git a/ethclient/gethclient/gethclient_test.go b/ethclient/gethclient/gethclient_test.go index ed25be8cd4..1c2b729caf 100644 --- a/ethclient/gethclient/gethclient_test.go +++ b/ethclient/gethclient/gethclient_test.go @@ -357,7 +357,7 @@ func testSubscribeFullPendingTransactions(t *testing.T, client *rpc.Client) { ethcl := ethclient.NewClient(client) // Subscribe to Transactions ch := make(chan *types.Transaction) - ec.SubscribeFullPendingTransactions(context.Background(), ch) + _, _ = ec.SubscribeFullPendingTransactions(context.Background(), ch) // Send a transaction chainID, err := ethcl.ChainID(context.Background()) if err != nil { diff --git a/graphql/graphql.go b/graphql/graphql.go index 1929164548..000225c18e 100644 --- a/graphql/graphql.go +++ b/graphql/graphql.go @@ -205,6 +205,7 @@ type Transaction struct { // resolve returns the internal transaction object, fetching it if needed. // It also returns the block the tx blongs to, unless it is a pending tx. +// nolint:unparam func (t *Transaction) resolve(ctx context.Context) (*types.Transaction, *Block, error) { t.mu.Lock() defer t.mu.Unlock() @@ -540,7 +541,7 @@ func (t *Transaction) getLogs(ctx context.Context, hash common.Hash) (*[]*Log, e return nil, err } - var ret []*Log + ret := make([]*Log, len(logs)) // Select tx logs from all block logs ix := sort.Search(len(logs), func(i int) bool { return uint64(logs[i].TxIndex) >= t.index }) for ix < len(logs) && uint64(logs[ix].TxIndex) == t.index { diff --git a/graphql/service.go b/graphql/service.go index c98de90de7..ab87614a1d 100644 --- a/graphql/service.go +++ b/graphql/service.go @@ -82,7 +82,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // chunked transfer encoding must be disabled by setting content-length. w.Header().Set("content-type", "application/json") w.Header().Set("content-length", strconv.Itoa(len(responseJSON))) - w.Write(responseJSON) + _, _ = w.Write(responseJSON) if flush, ok := w.(http.Flusher); ok { flush.Flush() @@ -106,7 +106,7 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } w.Header().Set("Content-Type", "application/json") - w.Write(responseJSON) + _, _ = w.Write(responseJSON) }) } diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 7c3d67bd24..a393326dba 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -2335,6 +2335,7 @@ func (s *TransactionAPI) PendingTransactions() ([]*RPCTransaction, error) { // Resend accepts an existing transaction and a new gas price and limit. It will remove // the given transaction from the pool and reinsert it with the new gas price and limit. +// nolint:gocognit func (s *TransactionAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { if sendArgs.Nonce == nil { return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") diff --git a/internal/flags/helpers.go b/internal/flags/helpers.go index 8d7b153fe4..21689840f0 100644 --- a/internal/flags/helpers.go +++ b/internal/flags/helpers.go @@ -125,9 +125,9 @@ func doMigrateFlags(ctx *cli.Context) { // "alfa, beta, gamma" instead of "[alfa beta gamma]", in order // for the backing StringSlice to parse it properly. if result := parent.StringSlice(name); len(result) > 0 { - ctx.Set(name, strings.Join(result, ",")) + _ = ctx.Set(name, strings.Join(result, ",")) } else { - ctx.Set(name, parent.String(name)) + _ = ctx.Set(name, parent.String(name)) } break diff --git a/les/api_test.go b/les/api_test.go index 16f451edae..b3d05391e4 100644 --- a/les/api_test.go +++ b/les/api_test.go @@ -335,7 +335,7 @@ func testRequest(ctx context.Context, t *testing.T, client *rpc.Client) bool { var addr common.Address - crand.Read(addr[:]) + _, _ = crand.Read(addr[:]) c, cancel := context.WithTimeout(ctx, time.Second*12) defer cancel() diff --git a/les/benchmark.go b/les/benchmark.go index 3bfb8e79b4..5867761214 100644 --- a/les/benchmark.go +++ b/les/benchmark.go @@ -123,7 +123,7 @@ func (b *benchmarkProofsOrCode) init(h *serverHandler, count int) error { func (b *benchmarkProofsOrCode) request(peer *serverPeer, index int) error { key := make([]byte, 32) - crand.Read(key) + _, _ = crand.Read(key) if b.code { return peer.requestCode(0, []CodeReq{{BHash: b.headHash, AccKey: key}}) @@ -190,7 +190,7 @@ func (b *benchmarkTxSend) init(h *serverHandler, count int) error { for i := range b.txs { data := make([]byte, txSizeCostLimit) - crand.Read(data) + _, _ = crand.Read(data) tx, err := types.SignTx(types.NewTransaction(0, addr, new(big.Int), 0, new(big.Int), data), signer, key) if err != nil { @@ -218,7 +218,7 @@ func (b *benchmarkTxStatus) init(h *serverHandler, count int) error { func (b *benchmarkTxStatus) request(peer *serverPeer, index int) error { var hash common.Hash - crand.Read(hash[:]) + _, _ = crand.Read(hash[:]) return peer.requestTxStatus(0, []common.Hash{hash}) } @@ -305,7 +305,7 @@ func (h *serverHandler) measure(setup *benchmarkSetup, count int) error { var id enode.ID - crand.Read(id[:]) + _, _ = crand.Read(id[:]) peer1 := newServerPeer(lpv2, NetworkId, false, p2p.NewPeer(id, "client", nil), clientMeteredPipe) peer2 := newClientPeer(lpv2, NetworkId, p2p.NewPeer(id, "server", nil), serverMeteredPipe) diff --git a/les/catalyst/api_test.go b/les/catalyst/api_test.go index cf1d727237..9f945b2044 100644 --- a/les/catalyst/api_test.go +++ b/les/catalyst/api_test.go @@ -44,6 +44,7 @@ var ( testBalance = big.NewInt(2e18) ) +// nolint:unparam func generatePreMergeChain(pre, post int) (*core.Genesis, []*types.Header, []*types.Block, []*types.Header, []*types.Block) { config := *params.AllEthashProtocolChanges genesis := &core.Genesis{ @@ -57,7 +58,7 @@ func generatePreMergeChain(pre, post int) (*core.Genesis, []*types.Header, []*ty db, preBLocks, _ := core.GenerateChainWithGenesis(genesis, ethash.NewFaker(), pre, nil) totalDifficulty := new(big.Int).Set(params.GenesisDifficulty) - var preHeaders []*types.Header + preHeaders := make([]*types.Header, 0, len(preBLocks)) for _, b := range preBLocks { totalDifficulty.Add(totalDifficulty, b.Difficulty()) @@ -72,7 +73,7 @@ func generatePreMergeChain(pre, post int) (*core.Genesis, []*types.Header, []*ty b.SetPoS() }) - var postHeaders []*types.Header + postHeaders := make([]*types.Header, 0, len(postBlocks)) for _, b := range postBlocks { postHeaders = append(postHeaders, b.Header()) } diff --git a/les/client.go b/les/client.go index cec1d9c15a..40bdef6a02 100644 --- a/les/client.go +++ b/les/client.go @@ -19,7 +19,6 @@ package les import ( "fmt" - "github.com/ethereum/go-ethereum/eth/downloader/whitelist" "strings" "time" @@ -32,6 +31,7 @@ import ( "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/eth/downloader/whitelist" "github.com/ethereum/go-ethereum/eth/ethconfig" "github.com/ethereum/go-ethereum/eth/gasprice" "github.com/ethereum/go-ethereum/event" @@ -188,9 +188,9 @@ func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) { log.Warn("Rewinding chain to upgrade configuration", "err", compat) if compat.RewindToTime > 0 { - leth.blockchain.SetHeadWithTimestamp(compat.RewindToTime) + _ = leth.blockchain.SetHeadWithTimestamp(compat.RewindToTime) } else { - leth.blockchain.SetHead(compat.RewindToBlock) + _ = leth.blockchain.SetHead(compat.RewindToBlock) } rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig) diff --git a/les/downloader/statesync.go b/les/downloader/statesync.go index 5c18521f39..7500dc2833 100644 --- a/les/downloader/statesync.go +++ b/les/downloader/statesync.go @@ -631,8 +631,8 @@ func (s *stateSync) processNodeData(nodeTasks map[string]*trieTask, codeTasks ma var hash common.Hash s.keccak.Reset() - s.keccak.Write(blob) - s.keccak.Read(hash[:]) + _, _ = s.keccak.Write(blob) + _, _ = s.keccak.Read(hash[:]) if _, present := codeTasks[hash]; present { err := s.sched.ProcessCode(trie.CodeSyncResult{ diff --git a/les/state_accessor.go b/les/state_accessor.go index 1d6a70f5e8..1998e176bb 100644 --- a/les/state_accessor.go +++ b/les/state_accessor.go @@ -34,7 +34,7 @@ import ( var noopReleaser = tracers.StateReleaseFunc(func() {}) // stateAtBlock retrieves the state database associated with a certain block. -func (leth *LightEthereum) stateAtBlock(ctx context.Context, block *types.Block, reexec uint64) (*state.StateDB, tracers.StateReleaseFunc, error) { +func (leth *LightEthereum) stateAtBlock(ctx context.Context, block *types.Block, _ uint64) (*state.StateDB, tracers.StateReleaseFunc, error) { return light.NewState(ctx, block.Header(), leth.odr), noopReleaser, nil } diff --git a/light/lightchain.go b/light/lightchain.go index 2c4cc04d2e..cd39090f63 100644 --- a/light/lightchain.go +++ b/light/lightchain.go @@ -424,6 +424,7 @@ func (lc *LightChain) SetCanonical(header *types.Header) error { } // Emit events block := types.NewBlockWithHeader(header) + lc.chainFeed.Send(core.ChainEvent{Block: block, Hash: block.Hash()}) lc.chainHeadFeed.Send(core.ChainHeadEvent{Block: block}) log.Info("Set the chain head", "number", block.Number(), "hash", block.Hash()) diff --git a/light/odr_test.go b/light/odr_test.go index 8f067766c9..38322c3c7d 100644 --- a/light/odr_test.go +++ b/light/odr_test.go @@ -216,6 +216,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, bc *core.BlockChain // Perform read-only call. st.SetBalance(testBankAddress, math.MaxBig256) + msg := &core.Message{ From: testBankAddress, To: &testContractAddr, @@ -307,6 +308,7 @@ func testChainOdr(t *testing.T, protocol int, fn odrTestFn) { } gspec.MustCommit(ldb) + odr := &testOdr{sdb: sdb, ldb: ldb, serverState: blockchain.StateCache(), indexerConfig: TestClientIndexerConfig} lightchain, err := NewLightChain(odr, gspec.Config, ethash.NewFullFaker(), nil, nil) diff --git a/light/postprocess.go b/light/postprocess.go index a660db29b6..1200114ae4 100644 --- a/light/postprocess.go +++ b/light/postprocess.go @@ -125,7 +125,7 @@ func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common var encNumber [8]byte binary.BigEndian.PutUint64(encNumber[:], sectionIdx) - db.Put(append(append(rawdb.ChtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes()) + _ = db.Put(append(append(rawdb.ChtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes()) } // ChtIndexerBackend implements core.ChainIndexerBackend. @@ -264,7 +264,7 @@ func (c *ChtIndexerBackend) Commit() error { trimmed := bytes.TrimPrefix(it.Key(), rawdb.ChtTablePrefix) if len(trimmed) == common.HashLength { if _, ok := hashes[common.BytesToHash(trimmed)]; !ok { - batch.Delete(trimmed) + _ = batch.Delete(trimmed) deleted += 1 } @@ -352,7 +352,7 @@ func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root var encNumber [8]byte binary.BigEndian.PutUint64(encNumber[:], sectionIdx) - db.Put(append(append(rawdb.BloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes()) + _ = db.Put(append(append(rawdb.BloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes()) } // BloomTrieIndexerBackend implements core.ChainIndexerBackend @@ -558,7 +558,7 @@ func (b *BloomTrieIndexerBackend) Commit() error { trimmed := bytes.TrimPrefix(it.Key(), rawdb.BloomTrieTablePrefix) if len(trimmed) == common.HashLength { if _, ok := hashes[common.BytesToHash(trimmed)]; !ok { - batch.Delete(trimmed) + _ = batch.Delete(trimmed) deleted += 1 } diff --git a/light/txpool_test.go b/light/txpool_test.go index 203973c0ee..931d1d02b2 100644 --- a/light/txpool_test.go +++ b/light/txpool_test.go @@ -99,6 +99,7 @@ func TestTxPool(t *testing.T) { } gspec.MustCommit(ldb) + odr := &testOdr{sdb: sdb, ldb: ldb, serverState: blockchain.StateCache(), indexerConfig: TestClientIndexerConfig} relay := &testTxRelay{ send: make(chan int, 1), diff --git a/miner/fake_miner.go b/miner/fake_miner.go index b5b90a1e4b..90db1221f6 100644 --- a/miner/fake_miner.go +++ b/miner/fake_miner.go @@ -2,8 +2,6 @@ package miner import ( "errors" - "github.com/ethereum/go-ethereum/core/txpool" - "github.com/ethereum/go-ethereum/trie" "math/big" "testing" "time" @@ -18,6 +16,7 @@ import ( "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/types" "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" @@ -26,6 +25,7 @@ import ( "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/tests/bor/mocks" + "github.com/ethereum/go-ethereum/trie" ) type DefaultBorMiner struct { diff --git a/miner/miner.go b/miner/miner.go index 49e450a2e4..349b08d583 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -73,6 +73,7 @@ var DefaultConfig = Config{ } // Miner creates blocks and searches for proof-of-work values. +// nolint:staticcheck type Miner struct { mux *event.TypeMux eth Backend diff --git a/miner/miner_test.go b/miner/miner_test.go index 359ed6a81a..f0f1d96182 100644 --- a/miner/miner_test.go +++ b/miner/miner_test.go @@ -270,7 +270,11 @@ func waitForMiningState(t *testing.T, m *Miner, mining bool) { t.Fatalf("Mining() == %t, want %t", state, mining) } +// createMiner is not used in bor as NewBorDefaultMiner replaces it +// nolint:staticcheck func createMiner(t *testing.T) (*Miner, *event.TypeMux, func(skipMiner bool)) { + t.Helper() + // Create Ethash config config := Config{ Etherbase: common.HexToAddress("123456789"), @@ -297,6 +301,7 @@ func createMiner(t *testing.T) (*Miner, *event.TypeMux, func(skipMiner bool)) { pool := txpool.NewTxPool(testTxPoolConfig, chainConfig, blockchain) backend := NewMockBackend(bc, pool) // Create event Mux + // nolint:staticcheck mux := new(event.TypeMux) // Create Miner miner := New(backend, &config, chainConfig, mux, engine, nil) diff --git a/miner/payload_building.go b/miner/payload_building.go index 9177c77897..0009a9f487 100644 --- a/miner/payload_building.go +++ b/miner/payload_building.go @@ -47,10 +47,10 @@ func (args *BuildPayloadArgs) Id() engine.PayloadID { // Hash hasher := sha256.New() hasher.Write(args.Parent[:]) - binary.Write(hasher, binary.BigEndian, args.Timestamp) + _ = binary.Write(hasher, binary.BigEndian, args.Timestamp) hasher.Write(args.Random[:]) hasher.Write(args.FeeRecipient[:]) - rlp.Encode(hasher, args.Withdrawals) + _ = rlp.Encode(hasher, args.Withdrawals) var out engine.PayloadID diff --git a/miner/payload_building_test.go b/miner/payload_building_test.go index 6ecfcae49d..821d0854af 100644 --- a/miner/payload_building_test.go +++ b/miner/payload_building_test.go @@ -30,6 +30,8 @@ import ( ) func TestBuildPayload(t *testing.T) { + t.Parallel() + var ( db = rawdb.NewMemoryDatabase() recipient = common.HexToAddress("0xdeadbeef") @@ -90,51 +92,53 @@ func TestBuildPayload(t *testing.T) { } func TestPayloadId(t *testing.T) { + t.Parallel() + ids := make(map[string]int) for i, tt := range []*BuildPayloadArgs{ - &BuildPayloadArgs{ + { Parent: common.Hash{1}, Timestamp: 1, Random: common.Hash{0x1}, FeeRecipient: common.Address{0x1}, }, // Different parent - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 1, Random: common.Hash{0x1}, FeeRecipient: common.Address{0x1}, }, // Different timestamp - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 2, Random: common.Hash{0x1}, FeeRecipient: common.Address{0x1}, }, // Different Random - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 2, Random: common.Hash{0x2}, FeeRecipient: common.Address{0x1}, }, // Different fee-recipient - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 2, Random: common.Hash{0x2}, FeeRecipient: common.Address{0x2}, }, // Different withdrawals (non-empty) - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 2, Random: common.Hash{0x2}, FeeRecipient: common.Address{0x2}, Withdrawals: []*types.Withdrawal{ - &types.Withdrawal{ + { Index: 0, Validator: 0, Address: common.Address{}, @@ -143,13 +147,13 @@ func TestPayloadId(t *testing.T) { }, }, // Different withdrawals (non-empty) - &BuildPayloadArgs{ + { Parent: common.Hash{2}, Timestamp: 2, Random: common.Hash{0x2}, FeeRecipient: common.Address{0x2}, Withdrawals: []*types.Withdrawal{ - &types.Withdrawal{ + { Index: 2, Validator: 0, Address: common.Address{}, diff --git a/miner/stress/1559/main.go b/miner/stress/1559/main.go index 600f804344..283b4a8f0d 100644 --- a/miner/stress/1559/main.go +++ b/miner/stress/1559/main.go @@ -171,7 +171,7 @@ func makeTransaction(nonce uint64, privKey *ecdsa.PrivateKey, signer types.Signe // larger buffer for creating both valid and invalid transactions. var buf = make([]byte, 32+5) - crand.Read(buf) + _, _ = crand.Read(buf) gasTipCap := new(big.Int).SetBytes(buf) // If the given base fee is nil(the 1559 is still not available), @@ -183,7 +183,7 @@ func makeTransaction(nonce uint64, privKey *ecdsa.PrivateKey, signer types.Signe var gasFeeCap *big.Int if rand.Intn(4) == 0 { - crand.Read(buf) + _, _ = crand.Read(buf) gasFeeCap = new(big.Int).SetBytes(buf) } else { gasFeeCap = new(big.Int).Add(baseFee, gasTipCap) diff --git a/miner/stress/beacon/main.go b/miner/stress/beacon/main.go index 4b4f8eb76a..a94e6e9467 100644 --- a/miner/stress/beacon/main.go +++ b/miner/stress/beacon/main.go @@ -212,7 +212,7 @@ func (n *ethNode) insertBlock(eb engine.ExecutableData) error { } } -func (n *ethNode) insertBlockAndSetHead(parent *types.Header, ed engine.ExecutableData) error { +func (n *ethNode) insertBlockAndSetHead(_ *types.Header, ed engine.ExecutableData) error { if !eth2types(n.typ) { return errors.New("invalid node type") } @@ -359,7 +359,7 @@ func (mgr *nodeManager) run() { SafeBlockHash: oldest.Hash(), FinalizedBlockHash: oldest.Hash(), } - node.api.ForkchoiceUpdatedV1(fcState, nil) + _, _ = node.api.ForkchoiceUpdatedV1(fcState, nil) } log.Info("Finalised eth2 block", "number", oldest.NumberU64(), "hash", oldest.Hash()) @@ -473,6 +473,7 @@ func main() { node := nodes[index%len(nodes)] // Create a self transaction and inject into the pool + // nolint:gosec tx, err := types.SignTx(types.NewTransaction(nonces[index], crypto.PubkeyToAddress(faucets[index].PublicKey), new(big.Int), 21000, big.NewInt(10_000_000_000+rand.Int63n(6_553_600_000)), nil), types.HomesteadSigner{}, faucets[index]) if err != nil { panic(err) diff --git a/miner/test_backend.go b/miner/test_backend.go index 65f9c39ee0..5d0e8a09c5 100644 --- a/miner/test_backend.go +++ b/miner/test_backend.go @@ -50,6 +50,18 @@ const ( ) func init() { + + testTxPoolConfig = txpool.DefaultConfig + testTxPoolConfig.Journal = "" + ethashChainConfig = new(params.ChainConfig) + *ethashChainConfig = *params.TestChainConfig + cliqueChainConfig = new(params.ChainConfig) + *cliqueChainConfig = *params.TestChainConfig + cliqueChainConfig.Clique = ¶ms.CliqueConfig{ + Period: 10, + Epoch: 30000, + } + signer := types.LatestSigner(params.TestChainConfig) tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{ @@ -204,7 +216,7 @@ func (b *testWorkerBackend) newRandomTxWithNonce(creation bool, nonce uint64) *t return tx } -// newRandomTxWithGas creates a new transaction to deploy a storage smart contract. +// newStorageCreateContractTx creates a new transaction to deploy a storage smart contract. func (b *testWorkerBackend) newStorageCreateContractTx() (*types.Transaction, common.Address) { var tx *types.Transaction diff --git a/miner/worker.go b/miner/worker.go index 29eb7d0f08..c45f6033cd 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -637,7 +637,7 @@ func (w *worker) newWorkLoop(ctx context.Context, recommit time.Duration) { // mainLoop is responsible for generating and submitting sealing work based on // the received event. It can support two modes: automatically generate task and // submit it or return task according to given parameters for various proposes. -// nolint: gocognit +// nolint: gocognit, contextcheck func (w *worker) mainLoop(ctx context.Context) { defer w.wg.Done() defer w.txsSub.Unsubscribe() @@ -655,7 +655,6 @@ func (w *worker) mainLoop(ctx context.Context) { for { select { case req := <-w.newWorkCh: - //nolint:contextcheck if w.isRunning() { w.commitWork(req.ctx, req.interrupt, req.noempty, req.timestamp) } @@ -1696,7 +1695,7 @@ func (w *worker) commitWork(ctx context.Context, interrupt *atomic.Int32, noempt // Create an empty block based on temporary copied state for // sealing in advance without waiting block execution finished. if !noempty && !w.noempty.Load() { - w.commit(ctx, work.copy(), nil, false, start) + _ = w.commit(ctx, work.copy(), nil, false, start) } // Fill pending transactions from the txpool into the block. err = w.fillTransactions(ctx, interrupt, work, interruptCtx) @@ -1730,7 +1729,7 @@ func (w *worker) commitWork(ctx context.Context, interrupt *atomic.Int32, noempt return } // Submit the generated block for consensus sealing. - w.commit(ctx, work.copy(), w.fullTaskHook, true, start) + _ = w.commit(ctx, work.copy(), w.fullTaskHook, true, start) // Swap out the old work with the new one, terminating any leftover // prefetcher processes in the mean time and starting a new one. diff --git a/miner/worker_test.go b/miner/worker_test.go index 7febc7dba1..240eca136a 100644 --- a/miner/worker_test.go +++ b/miner/worker_test.go @@ -17,11 +17,6 @@ package miner import ( - "crypto/rand" - "errors" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/event" "math/big" "os" "sync/atomic" @@ -40,10 +35,11 @@ import ( "github.com/ethereum/go-ethereum/consensus/ethash" "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/types" "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/tests/bor/mocks" @@ -83,6 +79,7 @@ func init() { } // newTestWorker creates a new test worker with the given parameters. +// nolint:unparam func newTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int, noempty bool, delay uint, opcodeDelay uint) (*worker, *testWorkerBackend, func()) { backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks) backend.txPool.AddLocals(pendingTxs) @@ -105,89 +102,6 @@ func newTestWorker(t TensingObject, chainConfig *params.ChainConfig, engine cons return w, backend, w.close } -func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain } -func (b *testWorkerBackend) TxPool() *txpool.TxPool { return b.txPool } -func (b *testWorkerBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) { - return nil, errors.New("not supported") -} - -func (b *testWorkerBackend) newRandomUncle() (*types.Block, error) { - var parent *types.Block - - cur := b.chain.CurrentBlock() - if cur.Number.Uint64() == 0 { - parent = b.chain.Genesis() - } else { - parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash) - } - - var err error - - blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.DB, 1, func(i int, gen *core.BlockGen) { - var addr = make([]byte, common.AddressLength) - - _, err = rand.Read(addr) - if err != nil { - return - } - - gen.SetCoinbase(common.BytesToAddress(addr)) - }) - - return blocks[0], err -} - -func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction { - var tx *types.Transaction - - gasPrice := big.NewInt(10 * params.InitialBaseFee) - if creation { - tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey) - } else { - tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(TestBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey) - } - - return tx -} - -// newRandomTxWithNonce creates a new transaction with the given nonce. -func (b *testWorkerBackend) newRandomTxWithNonce(creation bool, nonce uint64) *types.Transaction { - var tx *types.Transaction - - gasPrice := big.NewInt(100 * params.InitialBaseFee) - - if creation { - tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey) - } else { - tx, _ = types.SignTx(types.NewTransaction(nonce, testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey) - } - - return tx -} - -// newRandomTxWithGas creates a new transaction to deploy a storage smart contract. -func (b *testWorkerBackend) newStorageCreateContractTx() (*types.Transaction, common.Address) { - var tx *types.Transaction - - gasPrice := big.NewInt(10 * params.InitialBaseFee) - - tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(TestBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(storageContractByteCode)), types.HomesteadSigner{}, testBankKey) - contractAddr := crypto.CreateAddress(TestBankAddress, b.txPool.Nonce(TestBankAddress)) - - return tx, contractAddr -} - -// newStorageContractCallTx creates a new transaction to call a storage smart contract. -func (b *testWorkerBackend) newStorageContractCallTx(to common.Address, nonce uint64) *types.Transaction { - var tx *types.Transaction - - gasPrice := big.NewInt(10 * params.InitialBaseFee) - - tx, _ = types.SignTx(types.NewTransaction(nonce, to, nil, storageCallTxGas, gasPrice, common.FromHex(storageContractTxCallData)), types.HomesteadSigner{}, testBankKey) - - return tx -} - // nolint : paralleltest func TestGenerateBlockAndImportEthash(t *testing.T) { testGenerateBlockAndImport(t, false, false) @@ -615,7 +529,10 @@ func TestGetSealingWorkPostMerge(t *testing.T) { testGetSealingWork(t, local, ethash.NewFaker()) } +// nolint:gocognit func testGetSealingWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { + t.Helper() + defer engine.Close() w, b, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0, false, 0, 0) diff --git a/node/config.go b/node/config.go index f3fd882e50..c6957ec350 100644 --- a/node/config.go +++ b/node/config.go @@ -19,7 +19,6 @@ package node import ( "crypto/ecdsa" "fmt" - "github.com/ethereum/go-ethereum/p2p/enode" "os" "path/filepath" "runtime" @@ -31,6 +30,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/p2p" + "github.com/ethereum/go-ethereum/p2p/enode" "github.com/ethereum/go-ethereum/rpc" ) @@ -413,8 +413,9 @@ func (c *Config) parsePersistentNodes(w *bool, path string) []*enode.Node { log.Error(fmt.Sprintf("Can't load node list file: %v", err)) return nil } + // Interpret the list as a discovery node array - var nodes []*enode.Node + nodes := make([]*enode.Node, 0, len(nodelist)) for _, url := range nodelist { if url == "" { diff --git a/node/node.go b/node/node.go index 071fc4d652..e9d51f5c95 100644 --- a/node/node.go +++ b/node/node.go @@ -409,7 +409,7 @@ func (n *Node) obtainJWTSecret(cliParam string) ([]byte, error) { // assumptions about the state of the node. func (n *Node) startRPC() error { // Filter out personal api - var apis []rpc.API + apis := make([]rpc.API, 0, len(n.rpcAPIs)) for _, api := range n.rpcAPIs { if api.Namespace == "personal" { diff --git a/node/rpcstack.go b/node/rpcstack.go index 9b7d90e7a0..d5e50bbed5 100644 --- a/node/rpcstack.go +++ b/node/rpcstack.go @@ -20,7 +20,6 @@ import ( "compress/gzip" "context" "fmt" - "github.com/rs/cors" "io" "net" "net/http" @@ -31,6 +30,8 @@ import ( "sync/atomic" "time" + "github.com/rs/cors" + "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/rpc" ) diff --git a/node/rpcstack_test.go b/node/rpcstack_test.go index ff6e3fddc3..f56ee47185 100644 --- a/node/rpcstack_test.go +++ b/node/rpcstack_test.go @@ -49,10 +49,12 @@ func TestCorsHandler(t *testing.T) { resp = rpcRequest(t, url, testMethod, "origin", "test.com") assert.Equal(t, "test.com", resp.Header.Get("Access-Control-Allow-Origin")) + defer resp.Body.Close() resp2 = rpcRequest(t, url, testMethod, "origin", "bad") assert.Equal(t, "", resp2.Header.Get("Access-Control-Allow-Origin")) + defer resp2.Body.Close() } @@ -66,10 +68,12 @@ func TestVhosts(t *testing.T) { resp = rpcRequest(t, url, testMethod, "host", "test") assert.Equal(t, resp.StatusCode, http.StatusOK) + defer resp.Body.Close() resp2 = rpcRequest(t, url, testMethod, "host", "bad") assert.Equal(t, resp2.StatusCode, http.StatusForbidden) + defer resp2.Body.Close() } @@ -408,6 +412,7 @@ func TestJWT(t *testing.T) { } token = tokenFn() + // nolint:bodyclose if resp := rpcRequest(t, htUrl, testMethod, "Authorization", token); resp.StatusCode != 200 { t.Errorf("test %d-http, token '%v': expected ok, got %v", i, token, resp.StatusCode) } @@ -503,7 +508,7 @@ func TestGzipHandler(t *testing.T) { { name: "Write", handler: func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("response")) + _, _ = w.Write([]byte("response")) }, isGzip: true, status: 200, @@ -513,7 +518,7 @@ func TestGzipHandler(t *testing.T) { handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("x-foo", "bar") w.WriteHeader(205) - w.Write([]byte("response")) + _, _ = w.Write([]byte("response")) }, isGzip: true, status: 205, @@ -523,7 +528,7 @@ func TestGzipHandler(t *testing.T) { name: "WriteContentLength", handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("content-length", "8") - w.Write([]byte("response")) + _, _ = w.Write([]byte("response")) }, isGzip: true, status: 200, @@ -531,9 +536,9 @@ func TestGzipHandler(t *testing.T) { { name: "Flush", handler: func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("res")) + _, _ = w.Write([]byte("res")) w.(http.Flusher).Flush() - w.Write([]byte("ponse")) + _, _ = w.Write([]byte("ponse")) }, isGzip: true, status: 200, @@ -543,7 +548,7 @@ func TestGzipHandler(t *testing.T) { handler: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("transfer-encoding", "identity") w.Header().Set("x-foo", "bar") - w.Write([]byte("response")) + _, _ = w.Write([]byte("response")) }, isGzip: false, status: 200, @@ -555,7 +560,7 @@ func TestGzipHandler(t *testing.T) { w.Header().Set("transfer-encoding", "identity") w.Header().Set("x-foo", "bar") w.WriteHeader(205) - w.Write([]byte("response")) + _, _ = w.Write([]byte("response")) }, isGzip: false, status: 205, diff --git a/tests/bor/bor_sprint_length_change_test.go b/tests/bor/bor_sprint_length_change_test.go index fcc8766045..05302cd069 100644 --- a/tests/bor/bor_sprint_length_change_test.go +++ b/tests/bor/bor_sprint_length_change_test.go @@ -5,7 +5,6 @@ import ( "encoding/csv" "encoding/json" "fmt" - "github.com/ethereum/go-ethereum/core/txpool" "io/ioutil" // nolint: staticcheck _log "log" "math/big" @@ -19,6 +18,7 @@ import ( "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common/fdlimit" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/txpool" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth/downloader" diff --git a/tests/fuzzers/stacktrie/trie_fuzzer.go b/tests/fuzzers/stacktrie/trie_fuzzer.go index 826a7de9a1..60ca825646 100644 --- a/tests/fuzzers/stacktrie/trie_fuzzer.go +++ b/tests/fuzzers/stacktrie/trie_fuzzer.go @@ -199,10 +199,10 @@ func (f *fuzzer) fuzz() int { // Flush trie -> database rootA, nodes := trieA.Commit(false) if nodes != nil { - dbA.Update(trie.NewWithNodeSet(nodes)) + _ = dbA.Update(trie.NewWithNodeSet(nodes)) } // Flush memdb -> disk (sponge) - dbA.Commit(rootA, false) + _ = dbA.Commit(rootA, false) // Stacktrie requires sorted insertion sort.Sort(vals) @@ -216,7 +216,7 @@ func (f *fuzzer) fuzz() int { } rootB := trieB.Hash() - trieB.Commit() + _, _ = trieB.Commit() if rootA != rootB { panic(fmt.Sprintf("roots differ: (trie) %x != %x (stacktrie)", rootA, rootB)) diff --git a/tests/state_test_util.go b/tests/state_test_util.go index ab65a635f8..f222e30f08 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -297,7 +297,7 @@ func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapsh // the coinbase gets no txfee, so isn't created, and thus needs to be touched statedb.AddBalance(block.Coinbase(), new(big.Int)) // Commit block - statedb.Commit(config.IsEIP158(block.Number())) + _, _ = statedb.Commit(config.IsEIP158(block.Number())) // And _now_ get the state root root := statedb.IntermediateRoot(config.IsEIP158(block.Number())) diff --git a/trie/encoding_test.go b/trie/encoding_test.go index 9b809b529f..1684a4a996 100644 --- a/trie/encoding_test.go +++ b/trie/encoding_test.go @@ -101,7 +101,7 @@ func TestHexToCompactInPlaceRandom(t *testing.T) { for i := 0; i < 10000; i++ { l := rand.Intn(128) key := make([]byte, l) - crand.Read(key) + _, _ = crand.Read(key) hexBytes := keybytesToHex(key) hexOrig := []byte(string(hexBytes)) exp := hexToCompact(hexBytes) diff --git a/trie/iterator_test.go b/trie/iterator_test.go index e993d99953..abfb115458 100644 --- a/trie/iterator_test.go +++ b/trie/iterator_test.go @@ -64,7 +64,7 @@ func TestIterator(t *testing.T) { } root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) found := make(map[string]string) @@ -240,7 +240,7 @@ func TestDifferenceIterator(t *testing.T) { } rootA, nodesA := triea.Commit(false) - dba.Update(NewWithNodeSet(nodesA)) + _ = dba.Update(NewWithNodeSet(nodesA)) triea, _ = New(TrieID(rootA), dba) dbb := NewDatabase(rawdb.NewMemoryDatabase()) @@ -251,7 +251,7 @@ func TestDifferenceIterator(t *testing.T) { } rootB, nodesB := trieb.Commit(false) - dbb.Update(NewWithNodeSet(nodesB)) + _ = dbb.Update(NewWithNodeSet(nodesB)) trieb, _ = New(TrieID(rootB), dbb) found := make(map[string]string) @@ -288,7 +288,7 @@ func TestUnionIterator(t *testing.T) { } rootA, nodesA := triea.Commit(false) - dba.Update(NewWithNodeSet(nodesA)) + _ = dba.Update(NewWithNodeSet(nodesA)) triea, _ = New(TrieID(rootA), dba) dbb := NewDatabase(rawdb.NewMemoryDatabase()) @@ -299,7 +299,7 @@ func TestUnionIterator(t *testing.T) { } rootB, nodesB := trieb.Commit(false) - dbb.Update(NewWithNodeSet(nodesB)) + _ = dbb.Update(NewWithNodeSet(nodesB)) trieb, _ = New(TrieID(rootB), dbb) di, _ := NewUnionIterator([]NodeIterator{triea.NodeIterator(nil), trieb.NodeIterator(nil)}) @@ -362,10 +362,10 @@ func testIteratorContinueAfterError(t *testing.T, memonly bool) { } _, nodes := tr.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) if !memonly { - triedb.Commit(tr.Hash(), false) + _ = triedb.Commit(tr.Hash(), false) } wantNodeCount := checkIteratorNoDups(t, tr.NodeIterator(nil), nil) @@ -466,10 +466,10 @@ func testIteratorContinueAfterSeekError(t *testing.T, memonly bool) { } root, nodes := ctr.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) if !memonly { - triedb.Commit(root, false) + _ = triedb.Commit(root, false) } barNodeHash := common.HexToHash("05041990364eb72fcb1127652ce40d8bab765f2bfe53225b1170d276cc101c2e") @@ -596,7 +596,7 @@ func makeLargeTestTrie() (*Database, *StateTrie, *loggingDb) { } _, nodes := trie.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) // Return the generated trie return triedb, trie, logDb } @@ -639,8 +639,8 @@ func TestIteratorNodeBlob(t *testing.T) { } _, nodes := trie.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) - triedb.Cap(0) + _ = triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Cap(0) found := make(map[common.Hash][]byte) diff --git a/trie/nodeset.go b/trie/nodeset.go index 2e5ba818fa..57be519a72 100644 --- a/trie/nodeset.go +++ b/trie/nodeset.go @@ -211,7 +211,7 @@ func NewMergedNodeSet() *MergedNodeSet { // NewWithNodeSet constructs a merged nodeset with the provided single set. func NewWithNodeSet(set *NodeSet) *MergedNodeSet { merged := NewMergedNodeSet() - merged.Merge(set) + _ = merged.Merge(set) return merged } diff --git a/trie/proof.go b/trie/proof.go index 5d869e4a58..5ef8441e91 100644 --- a/trie/proof.go +++ b/trie/proof.go @@ -549,7 +549,7 @@ func VerifyRangeProof(rootHash common.Hash, firstKey []byte, lastKey []byte, key if proof == nil { tr := NewStackTrie(nil) for index, key := range keys { - tr.Update(key, values[index]) + _ = tr.Update(key, values[index]) } if have, want := tr.Hash(), rootHash; have != want { @@ -627,7 +627,7 @@ func VerifyRangeProof(rootHash common.Hash, firstKey []byte, lastKey []byte, key } for index, key := range keys { - tr.Update(key, values[index]) + _ = tr.Update(key, values[index]) } if tr.Hash() != rootHash { diff --git a/trie/proof_test.go b/trie/proof_test.go index 62bf11f7bd..26c9594ddb 100644 --- a/trie/proof_test.go +++ b/trie/proof_test.go @@ -38,7 +38,7 @@ var prng = initRnd() func initRnd() *mrand.Rand { var seed [8]byte - crand.Read(seed[:]) + _, _ = crand.Read(seed[:]) rnd := mrand.New(mrand.NewSource(int64(binary.LittleEndian.Uint64(seed[:])))) fmt.Printf("Seed: %x\n", seed) diff --git a/trie/stacktrie_test.go b/trie/stacktrie_test.go index 589c124d21..f96abaebae 100644 --- a/trie/stacktrie_test.go +++ b/trie/stacktrie_test.go @@ -197,8 +197,8 @@ func TestSizeBug(t *testing.T) { leaf := common.FromHex("290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563") value := common.FromHex("94cf40d0d2b44f2b66e07cace1372ca42b73cf21a3") - nt.Update(leaf, value) - st.Update(leaf, value) + _ = nt.Update(leaf, value) + _ = st.Update(leaf, value) if nt.Hash() != st.Hash() { t.Fatalf("error %x != %x", st.Hash(), nt.Hash()) @@ -222,8 +222,8 @@ func TestEmptyBug(t *testing.T) { } for _, kv := range kvs { - nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) - st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) } if nt.Hash() != st.Hash() { @@ -245,8 +245,8 @@ func TestValLength56(t *testing.T) { } for _, kv := range kvs { - nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) - st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) } if nt.Hash() != st.Hash() { @@ -268,8 +268,8 @@ func TestUpdateSmallNodes(t *testing.T) { } for _, kv := range kvs { - nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) - st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) } if nt.Hash() != st.Hash() { @@ -299,8 +299,8 @@ func TestUpdateVariableKeys(t *testing.T) { } for _, kv := range kvs { - nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) - st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = nt.Update(common.FromHex(kv.K), common.FromHex(kv.V)) + _ = st.Update(common.FromHex(kv.K), common.FromHex(kv.V)) } if nt.Hash() != st.Hash() { @@ -318,7 +318,7 @@ func TestStacktrieNotModifyValues(t *testing.T) { value := make([]byte, 1, 100) value[0] = 0x2 want := common.CopyBytes(value) - st.Update([]byte{0x01}, value) + _ = st.Update([]byte{0x01}, value) st.Hash() if have := value; !bytes.Equal(have, want) { @@ -344,7 +344,7 @@ func TestStacktrieNotModifyValues(t *testing.T) { for i := 0; i < 1000; i++ { key := common.BigToHash(keyB) value := getValue(i) - st.Update(key.Bytes(), value) + _ = st.Update(key.Bytes(), value) vals = append(vals, value) keyB = keyB.Add(keyB, keyDelta) keyDelta.Add(keyDelta, common.Big1) @@ -388,7 +388,7 @@ func TestStacktrieSerialization(t *testing.T) { } for i, k := range keys { - nt.Update(k, common.CopyBytes(vals[i])) + _ = nt.Update(k, common.CopyBytes(vals[i])) } for i, k := range keys { @@ -403,7 +403,7 @@ func TestStacktrieSerialization(t *testing.T) { } st = newSt - st.Update(k, common.CopyBytes(vals[i])) + _ = st.Update(k, common.CopyBytes(vals[i])) } if have, want := st.Hash(), nt.Hash(); have != want { diff --git a/trie/sync.go b/trie/sync.go index bc76aa52a9..48918908bb 100644 --- a/trie/sync.go +++ b/trie/sync.go @@ -354,7 +354,7 @@ func (s *Sync) ProcessNode(result NodeSyncResult) error { } if len(requests) == 0 && req.deps == 0 { - s.commitNodeRequest(req) + _ = s.commitNodeRequest(req) } else { req.deps += len(requests) diff --git a/trie/sync_test.go b/trie/sync_test.go index faa465f602..8cd150fcc0 100644 --- a/trie/sync_test.go +++ b/trie/sync_test.go @@ -566,13 +566,13 @@ func TestIncompleteSync(t *testing.T) { // Sanity check that removing any node from the database is detected for _, hash := range added { value, _ := diskdb.Get(hash.Bytes()) - diskdb.Delete(hash.Bytes()) + _ = diskdb.Delete(hash.Bytes()) if err := checkTrieConsistency(triedb, root); err == nil { t.Fatalf("trie inconsistency not caught, missing: %x", hash) } - diskdb.Put(hash.Bytes(), value) + _ = diskdb.Put(hash.Bytes(), value) } } diff --git a/trie/tracer_test.go b/trie/tracer_test.go index a83677f643..411dfc0290 100644 --- a/trie/tracer_test.go +++ b/trie/tracer_test.go @@ -73,7 +73,7 @@ func testTrieTracer(t *testing.T, vals []struct{ k, v string }) { insertSet := copySet(trie.tracer.inserts) // copy before commit deleteSet := copySet(trie.tracer.deletes) // copy before commit root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) seen := setKeys(iterNodes(db, root)) if !compareSet(insertSet, seen) { @@ -153,7 +153,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) { } root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, nodes); err != nil { @@ -169,7 +169,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) { } root, nodes = trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, nodes); err != nil { @@ -189,7 +189,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) { } root, nodes = trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, nodes); err != nil { @@ -205,7 +205,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) { } root, nodes = trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, nodes); err != nil { @@ -221,7 +221,7 @@ func testAccessList(t *testing.T, vals []struct{ k, v string }) { } root, nodes = trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, nodes); err != nil { @@ -243,7 +243,7 @@ func TestAccessListLeak(t *testing.T) { } root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) var cases = []struct { op func(tr *Trie) @@ -265,7 +265,7 @@ func TestAccessListLeak(t *testing.T) { { func(tr *Trie) { for _, val := range standard { - tr.Prove([]byte(val.k), 0, rawdb.NewMemoryDatabase()) + _ = tr.Prove([]byte(val.k), 0, rawdb.NewMemoryDatabase()) } }, }, @@ -298,7 +298,7 @@ func TestTinyTree(t *testing.T) { } root, set := trie.Commit(false) - db.Update(NewWithNodeSet(set)) + _ = db.Update(NewWithNodeSet(set)) trie, _ = New(TrieID(root), db) orig := trie.Copy() @@ -308,7 +308,7 @@ func TestTinyTree(t *testing.T) { } root, set = trie.Commit(false) - db.Update(NewWithNodeSet(set)) + _ = db.Update(NewWithNodeSet(set)) trie, _ = New(TrieID(root), db) if err := verifyAccessList(orig, trie, set); err != nil { diff --git a/trie/trie_test.go b/trie/trie_test.go index ae797bd8ec..4db5869077 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -88,10 +88,10 @@ func testMissingNode(t *testing.T, memonly bool) { updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer") updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf") root, nodes := trie.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) if !memonly { - triedb.Commit(root, false) + _ = triedb.Commit(root, false) } trie, _ = New(TrieID(root), triedb) @@ -220,7 +220,7 @@ func TestGet(t *testing.T) { } root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) trie, _ = New(TrieID(root), db) } } @@ -297,7 +297,7 @@ func TestReplication(t *testing.T) { } exp, nodes := trie.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) // create a new trie on top of the database and check that lookups work. trie2, err := New(TrieID(exp), triedb) @@ -318,7 +318,7 @@ func TestReplication(t *testing.T) { // recreate the trie after commit if nodes != nil { - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) } trie2, err = New(TrieID(hash), triedb) @@ -549,7 +549,7 @@ func runRandTest(rt randTest) bool { case opCommit: root, nodes := tr.Commit(true) if nodes != nil { - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) } newtr, err := New(TrieID(root), triedb) @@ -929,9 +929,9 @@ func TestCommitSequence(t *testing.T) { } // Flush trie -> database root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) // Flush memdb -> disk (sponge) - db.Commit(root, false) + _ = db.Commit(root, false) if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) { t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp) @@ -973,9 +973,9 @@ func TestCommitSequenceRandomBlobs(t *testing.T) { } // Flush trie -> database root, nodes := trie.Commit(false) - db.Update(NewWithNodeSet(nodes)) + _ = db.Update(NewWithNodeSet(nodes)) // Flush memdb -> disk (sponge) - db.Commit(root, false) + _ = db.Commit(root, false) if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) { t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp) @@ -1010,14 +1010,14 @@ func TestCommitSequenceStackTrie(t *testing.T) { } prng.Read(val) - trie.Update(key, val) - stTrie.Update(key, val) + _ = trie.Update(key, val) + _ = stTrie.Update(key, val) } // Flush trie -> database root, nodes := trie.Commit(false) // Flush memdb -> disk (sponge) - db.Update(NewWithNodeSet(nodes)) - db.Commit(root, false) + _ = db.Update(NewWithNodeSet(nodes)) + _ = db.Commit(root, false) // And flush stacktrie -> disk stRoot, err := stTrie.Commit() if err != nil { @@ -1065,13 +1065,13 @@ func TestCommitSequenceSmallRoot(t *testing.T) { // Add a single small-element to the trie(s) key := make([]byte, 5) key[0] = 1 - trie.Update(key, []byte{0x1}) - stTrie.Update(key, []byte{0x1}) + _ = trie.Update(key, []byte{0x1}) + _ = stTrie.Update(key, []byte{0x1}) // Flush trie -> database root, nodes := trie.Commit(false) // Flush memdb -> disk (sponge) - db.Update(NewWithNodeSet(nodes)) - db.Commit(root, false) + _ = db.Update(NewWithNodeSet(nodes)) + _ = db.Commit(root, false) // And flush stacktrie -> disk stRoot, err := stTrie.Commit() if err != nil { @@ -1266,7 +1266,7 @@ func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [] h := trie.Hash() _, nodes := trie.Commit(false) - triedb.Update(NewWithNodeSet(nodes)) + _ = triedb.Update(NewWithNodeSet(nodes)) b.StartTimer() triedb.Dereference(h) b.StopTimer()