diff --git a/accounts/abi/bind/v2/lib_test.go b/accounts/abi/bind/v2/lib_test.go index fc895edad5..9aff767b81 100644 --- a/accounts/abi/bind/v2/lib_test.go +++ b/accounts/abi/bind/v2/lib_test.go @@ -72,7 +72,7 @@ func TestDeploymentLibraries(t *testing.T) { if err != nil { t.Fatalf("err setting up test: %v", err) } - defer bindBackend.Backend.Close() + defer bindBackend.Close() c := nested_libraries.NewC1() constructorInput := c.PackConstructor(big.NewInt(42), big.NewInt(1)) @@ -116,7 +116,7 @@ func TestDeploymentWithOverrides(t *testing.T) { if err != nil { t.Fatalf("err setting up test: %v", err) } - defer bindBackend.Backend.Close() + defer bindBackend.Close() // deploy all the library dependencies of our target contract, but not the target contract itself. deploymentParams := &bind.DeploymentParams{ diff --git a/accounts/abi/type.go b/accounts/abi/type.go index e59456f15a..f9af830cbf 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -421,7 +421,7 @@ func isValidFieldName(fieldName string) bool { return false } - if !(isLetter(c) || unicode.IsDigit(c)) { + if !isLetter(c) && !unicode.IsDigit(c) { return false } } diff --git a/accounts/keystore/passphrase.go b/accounts/keystore/passphrase.go index e7a7f8d0cb..9ed1819907 100644 --- a/accounts/keystore/passphrase.go +++ b/accounts/keystore/passphrase.go @@ -338,12 +338,13 @@ func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) { } dkLen := ensureInt(cryptoJSON.KDFParams["dklen"]) - if cryptoJSON.KDF == keyHeaderKDF { + switch cryptoJSON.KDF { + case keyHeaderKDF: n := ensureInt(cryptoJSON.KDFParams["n"]) r := ensureInt(cryptoJSON.KDFParams["r"]) p := ensureInt(cryptoJSON.KDFParams["p"]) return scrypt.Key(authArray, salt, n, r, p, dkLen) - } else if cryptoJSON.KDF == "pbkdf2" { + case "pbkdf2": c := ensureInt(cryptoJSON.KDFParams["c"]) prf := cryptoJSON.KDFParams["prf"].(string) if prf != "hmac-sha256" { diff --git a/accounts/usbwallet/wallet.go b/accounts/usbwallet/wallet.go index 0fd0415a9e..da2734bf71 100644 --- a/accounts/usbwallet/wallet.go +++ b/accounts/usbwallet/wallet.go @@ -531,7 +531,7 @@ func (w *wallet) signHash(account accounts.Account, hash []byte) ([]byte, error) // SignData signs keccak256(data). The mimetype parameter describes the type of data being signed func (w *wallet) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { // Unless we are doing 712 signing, simply dispatch to signHash - if !(mimeType == accounts.MimetypeTypedData && len(data) == 66 && data[0] == 0x19 && data[1] == 0x01) { + if mimeType != accounts.MimetypeTypedData || len(data) != 66 || data[0] != 0x19 || data[1] != 0x01 { return w.signHash(account, crypto.Keccak256(data)) } diff --git a/beacon/blsync/block_sync.go b/beacon/blsync/block_sync.go index a6252a55f1..44e7183dc7 100755 --- a/beacon/blsync/block_sync.go +++ b/beacon/blsync/block_sync.go @@ -129,7 +129,7 @@ func (s *beaconBlockSync) updateEventFeed() { var finalizedHash common.Hash if finality, ok := s.headTracker.ValidatedFinality(); ok { he := optimistic.Attested.Epoch() - fe := finality.Attested.Header.Epoch() + fe := finality.Attested.Epoch() switch { case he == fe: finalizedHash = finality.Finalized.PayloadHeader.BlockHash() diff --git a/beacon/light/sync/head_sync.go b/beacon/light/sync/head_sync.go index 5e41258053..cca3feab8e 100644 --- a/beacon/light/sync/head_sync.go +++ b/beacon/light/sync/head_sync.go @@ -90,7 +90,7 @@ func (s *HeadSync) Process(requester request.Requester, events []request.Event) if epoch < s.reqFinalityEpoch[event.Server] { continue } - if finality, ok := s.headTracker.ValidatedFinality(); ok && finality.Attested.Header.Epoch() >= epoch { + if finality, ok := s.headTracker.ValidatedFinality(); ok && finality.Attested.Epoch() >= epoch { continue } requester.Send(event.Server, ReqFinality{}) diff --git a/beacon/light/sync/head_sync_test.go b/beacon/light/sync/head_sync_test.go index d095d6a446..ef6de1d283 100644 --- a/beacon/light/sync/head_sync_test.go +++ b/beacon/light/sync/head_sync_test.go @@ -48,7 +48,7 @@ func finality(opt types.OptimisticUpdate) types.FinalityUpdate { return types.FinalityUpdate{ SignatureSlot: opt.SignatureSlot, Attested: opt.Attested, - Finalized: types.HeaderWithExecProof{Header: types.Header{Slot: (opt.Attested.Header.Slot - 64) & uint64(0xffffffffffffffe0)}}, + Finalized: types.HeaderWithExecProof{Header: types.Header{Slot: (opt.Attested.Slot - 64) & uint64(0xffffffffffffffe0)}}, } } diff --git a/beacon/light/sync/test_helpers.go b/beacon/light/sync/test_helpers.go index b331bf7110..aac6e370a4 100644 --- a/beacon/light/sync/test_helpers.go +++ b/beacon/light/sync/test_helpers.go @@ -233,12 +233,12 @@ func (ht *TestHeadTracker) ValidatedFinality() (types.FinalityUpdate, bool) { func (ht *TestHeadTracker) ExpValidated(t *testing.T, tci int, expHeads []types.OptimisticUpdate) { for i, expHead := range expHeads { if i >= len(ht.validated) { - t.Errorf("Missing validated head in test case #%d index #%d (expected {slot %d blockRoot %x}, got none)", tci, i, expHead.Attested.Header.Slot, expHead.Attested.Header.Hash()) + t.Errorf("Missing validated head in test case #%d index #%d (expected {slot %d blockRoot %x}, got none)", tci, i, expHead.Attested.Slot, expHead.Attested.Hash()) continue } if !reflect.DeepEqual(ht.validated[i], expHead) { vhead := ht.validated[i].Attested.Header - t.Errorf("Wrong validated head in test case #%d index #%d (expected {slot %d blockRoot %x}, got {slot %d blockRoot %x})", tci, i, expHead.Attested.Header.Slot, expHead.Attested.Header.Hash(), vhead.Slot, vhead.Hash()) + t.Errorf("Wrong validated head in test case #%d index #%d (expected {slot %d blockRoot %x}, got {slot %d blockRoot %x})", tci, i, expHead.Attested.Slot, expHead.Attested.Hash(), vhead.Slot, vhead.Hash()) } } for i := len(expHeads); i < len(ht.validated); i++ { diff --git a/cmd/clef/main.go b/cmd/clef/main.go index dde4ae853f..cd8c5f3361 100644 --- a/cmd/clef/main.go +++ b/cmd/clef/main.go @@ -801,9 +801,10 @@ func DefaultConfigDir() string { // Try to place the data folder in the user's home dir home := flags.HomeDir() if home != "" { - if runtime.GOOS == "darwin" { + switch runtime.GOOS { + case "darwin": return filepath.Join(home, "Library", "Signer") - } else if runtime.GOOS == "windows" { + case "windows": appdata := os.Getenv("APPDATA") if appdata != "" { return filepath.Join(appdata, "Signer") diff --git a/cmd/clef/run_test.go b/cmd/clef/run_test.go index d404457ba2..c0b2219782 100644 --- a/cmd/clef/run_test.go +++ b/cmd/clef/run_test.go @@ -75,7 +75,7 @@ func runWithKeystore(t *testing.T, keystore string, args ...string) *testproc { } func (proc *testproc) input(text string) *testproc { - proc.TestCmd.InputLine(text) + proc.InputLine(text) return proc } diff --git a/cmd/evm/internal/t8ntool/execution.go b/cmd/evm/internal/t8ntool/execution.go index 7de1eb6949..6c79c5ea01 100644 --- a/cmd/evm/internal/t8ntool/execution.go +++ b/cmd/evm/internal/t8ntool/execution.go @@ -299,7 +299,7 @@ func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig, // If the transaction created a contract, store the creation address in the receipt. if msg.To == nil { - receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce()) + receipt.ContractAddress = crypto.CreateAddress(evm.Origin, tx.Nonce()) } // Set the receipt logs and create the bloom filter. diff --git a/cmd/utils/export_test.go b/cmd/utils/export_test.go index d1a004d9b7..d29919e322 100644 --- a/cmd/utils/export_test.go +++ b/cmd/utils/export_test.go @@ -76,7 +76,7 @@ func testExport(t *testing.T, f string) { if (i < 5 || i == 42) && err == nil { t.Fatalf("expected no element at idx %d, got '%v'", i, string(v)) } - if !(i < 5 || i == 42) { + if i >= 5 && i != 42 { if err != nil { t.Fatalf("expected element idx %d: %v", i, err) } @@ -148,7 +148,7 @@ func testDeletion(t *testing.T, f string) { t.Fatalf("have %v, want %v", have, want) } } - if !(i < 5 || i == 42) { + if i >= 5 && i != 42 { if err == nil { t.Fatalf("expected no element idx %d: %v", i, string(v)) } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index ae58c2d053..539c272b69 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1902,7 +1902,7 @@ func MakeBeaconLightConfig(ctx *cli.Context) bparams.ClientConfig { Fatalf("Invalid hex string", "beacon.genesis.gvroot", ctx.String(BeaconGenesisRootFlag.Name), "error", err) } configFile := ctx.String(BeaconConfigFlag.Name) - if err := config.ChainConfig.LoadForks(configFile); err != nil { + if err := config.LoadForks(configFile); err != nil { Fatalf("Could not load beacon chain config", "file", configFile, "error", err) } log.Info("Using custom beacon chain config", "file", configFile) @@ -2093,10 +2093,8 @@ func MakeChainDatabase(ctx *cli.Context, stack *node.Node, readonly bool) ethdb. func tryMakeReadOnlyDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database { // If the database doesn't exist we need to open it in write-mode to allow // the engine to create files. - readonly := true - if rawdb.PreexistingDatabase(stack.ResolvePath("chaindata")) == "" { - readonly = false - } + readonly := !(rawdb.PreexistingDatabase(stack.ResolvePath("chaindata")) == "") + return MakeChainDatabase(ctx, stack, readonly) } diff --git a/common/lru/basiclru_test.go b/common/lru/basiclru_test.go index 29812bda15..ef9a2fe1ff 100644 --- a/common/lru/basiclru_test.go +++ b/common/lru/basiclru_test.go @@ -251,5 +251,5 @@ func BenchmarkLRU(b *testing.B) { // } // }) - fmt.Fprintln(io.Discard, sink) + fmt.Fprintln(io.Discard, string(sink)) } diff --git a/console/prompt/prompter.go b/console/prompt/prompter.go index 2a20b6906a..b67a250d45 100644 --- a/console/prompt/prompter.go +++ b/console/prompt/prompter.go @@ -116,7 +116,7 @@ func (p *terminalPrompter) PromptInput(prompt string) (string, error) { prompt = "" defer fmt.Println() } - return p.State.Prompt(prompt) + return p.Prompt(prompt) } // PromptPassword displays the given prompt to the user and requests some textual @@ -126,7 +126,7 @@ func (p *terminalPrompter) PromptPassword(prompt string) (passwd string, err err if p.supported { p.rawMode.ApplyMode() defer p.normalMode.ApplyMode() - return p.State.PasswordPrompt(prompt) + return p.PasswordPrompt(prompt) } if !p.warned { fmt.Println("!! Unsupported terminal, password will be echoed.") @@ -134,7 +134,7 @@ func (p *terminalPrompter) PromptPassword(prompt string) (passwd string, err err } // Just as in Prompt, handle printing the prompt here instead of relying on liner. fmt.Print(prompt) - passwd, err = p.State.Prompt("") + passwd, err = p.Prompt("") fmt.Println() return passwd, err } @@ -152,7 +152,7 @@ func (p *terminalPrompter) PromptConfirm(prompt string) (bool, error) { // SetHistory sets the input scrollback history that the prompter will allow // the user to scroll back to. func (p *terminalPrompter) SetHistory(history []string) { - p.State.ReadHistory(strings.NewReader(strings.Join(history, "\n"))) + p.ReadHistory(strings.NewReader(strings.Join(history, "\n"))) } // AppendHistory appends an entry to the scrollback history. diff --git a/core/blockchain_test.go b/core/blockchain_test.go index 04dfa87b8b..c3fbdfe1f5 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -2072,7 +2072,8 @@ func testInsertKnownChainData(t *testing.T, typ string, scheme string) { inserter func(blocks []*types.Block, receipts []types.Receipts) error asserter func(t *testing.T, block *types.Block) ) - if typ == "headers" { + switch typ { + case "headers": inserter = func(blocks []*types.Block, receipts []types.Receipts) error { headers := make([]*types.Header, 0, len(blocks)) for _, block := range blocks { @@ -2086,7 +2087,7 @@ func testInsertKnownChainData(t *testing.T, typ string, scheme string) { t.Fatalf("current head header mismatch, have %v, want %v", chain.CurrentHeader().Hash().Hex(), block.Hash().Hex()) } } - } else if typ == "receipts" { + case "receipts": inserter = func(blocks []*types.Block, receipts []types.Receipts) error { headers := make([]*types.Header, 0, len(blocks)) for _, block := range blocks { @@ -2104,7 +2105,7 @@ func testInsertKnownChainData(t *testing.T, typ string, scheme string) { t.Fatalf("current head fast block mismatch, have %v, want %v", chain.CurrentSnapBlock().Hash().Hex(), block.Hash().Hex()) } } - } else { + default: inserter = func(blocks []*types.Block, receipts []types.Receipts) error { _, err := chain.InsertChain(blocks) return err @@ -2243,7 +2244,8 @@ func testInsertKnownChainDataWithMerging(t *testing.T, typ string, mergeHeight i inserter func(blocks []*types.Block, receipts []types.Receipts) error asserter func(t *testing.T, block *types.Block) ) - if typ == "headers" { + switch typ { + case "headers": inserter = func(blocks []*types.Block, receipts []types.Receipts) error { headers := make([]*types.Header, 0, len(blocks)) for _, block := range blocks { @@ -2260,7 +2262,7 @@ func testInsertKnownChainDataWithMerging(t *testing.T, typ string, mergeHeight i t.Fatalf("current head header mismatch, have %v, want %v", chain.CurrentHeader().Hash().Hex(), block.Hash().Hex()) } } - } else if typ == "receipts" { + case "receipts": inserter = func(blocks []*types.Block, receipts []types.Receipts) error { headers := make([]*types.Header, 0, len(blocks)) for _, block := range blocks { @@ -2278,7 +2280,7 @@ func testInsertKnownChainDataWithMerging(t *testing.T, typ string, mergeHeight i t.Fatalf("current head fast block mismatch, have %v, want %v", chain.CurrentSnapBlock().Hash().Hex(), block.Hash().Hex()) } } - } else { + default: inserter = func(blocks []*types.Block, receipts []types.Receipts) error { i, err := chain.InsertChain(blocks) if err != nil { diff --git a/core/filtermaps/filtermaps.go b/core/filtermaps/filtermaps.go index db7ab0a426..6e00761be8 100644 --- a/core/filtermaps/filtermaps.go +++ b/core/filtermaps/filtermaps.go @@ -743,7 +743,7 @@ func (f *FilterMaps) exportCheckpoints() { if epoch == epochCount-1 { comma = "" } - w.WriteString(fmt.Sprintf("{\"blockNumber\": %d, \"blockId\": \"0x%064x\", \"firstIndex\": %d}%s\n", lastBlock, lastBlockId, lvPtr, comma)) + fmt.Fprintf(w, "{\"blockNumber\": %d, \"blockId\": \"0x%064x\", \"firstIndex\": %d}%s\n", lastBlock, lastBlockId, lvPtr, comma) } w.WriteString("]\n") f.lastFinalEpoch = epochCount diff --git a/core/rawdb/database.go b/core/rawdb/database.go index 7fca822155..5778f5855a 100644 --- a/core/rawdb/database.go +++ b/core/rawdb/database.go @@ -73,7 +73,7 @@ func (frdb *freezerdb) Freeze() error { } // Trigger a freeze cycle and block until it's done trigger := make(chan struct{}, 1) - frdb.chainFreezer.trigger <- trigger + frdb.trigger <- trigger <-trigger return nil } diff --git a/core/rawdb/freezer_test.go b/core/rawdb/freezer_test.go index 150734d3ac..40b3a9f360 100644 --- a/core/rawdb/freezer_test.go +++ b/core/rawdb/freezer_test.go @@ -241,7 +241,7 @@ func TestFreezerConcurrentModifyTruncate(t *testing.T) { if truncateErr != nil { t.Fatal("concurrent truncate failed:", err) } - if !(errors.Is(modifyErr, nil) || errors.Is(modifyErr, errOutOrderInsertion)) { + if !errors.Is(modifyErr, nil) && !errors.Is(modifyErr, errOutOrderInsertion) { t.Fatal("wrong error from concurrent modify:", modifyErr) } checkAncientCount(t, f, "test", 10) diff --git a/core/rawdb/key_length_iterator.go b/core/rawdb/key_length_iterator.go index d1c5af269a..050d356785 100644 --- a/core/rawdb/key_length_iterator.go +++ b/core/rawdb/key_length_iterator.go @@ -37,7 +37,7 @@ func NewKeyLengthIterator(it ethdb.Iterator, keyLen int) ethdb.Iterator { func (it *KeyLengthIterator) Next() bool { // Return true as soon as a key with the required key length is discovered for it.Iterator.Next() { - if len(it.Iterator.Key()) == it.requiredKeyLength { + if len(it.Key()) == it.requiredKeyLength { return true } } diff --git a/core/state_processor.go b/core/state_processor.go index 9241d091ad..05d4aa96fd 100644 --- a/core/state_processor.go +++ b/core/state_processor.go @@ -184,7 +184,7 @@ func MakeReceipt(evm *vm.EVM, result *ExecutionResult, statedb *state.StateDB, b // If the transaction created a contract, store the creation address in the receipt. if tx.To() == nil { - receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce()) + receipt.ContractAddress = crypto.CreateAddress(evm.Origin, tx.Nonce()) } // Set the receipt logs and create the bloom filter. diff --git a/core/vm/eips.go b/core/vm/eips.go index 6159eade7e..e208edb4e8 100644 --- a/core/vm/eips.go +++ b/core/vm/eips.go @@ -277,8 +277,8 @@ func opMcopy(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]by // opBlobHash implements the BLOBHASH opcode func opBlobHash(pc *uint64, interpreter *EVMInterpreter, scope *ScopeContext) ([]byte, error) { index := scope.Stack.peek() - if index.LtUint64(uint64(len(interpreter.evm.TxContext.BlobHashes))) { - blobHash := interpreter.evm.TxContext.BlobHashes[index.Uint64()] + if index.LtUint64(uint64(len(interpreter.evm.BlobHashes))) { + blobHash := interpreter.evm.BlobHashes[index.Uint64()] index.SetBytes32(blobHash[:]) } else { index.Clear() diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index a0038d1aa8..9d162cd9d3 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -237,7 +237,7 @@ func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) ( // if the PC ends up in a new "chunk" of verkleized code, charge the // associated costs. contractAddr := contract.Address() - contract.Gas -= in.evm.TxContext.AccessEvents.CodeChunksRangeGas(contractAddr, pc, 1, uint64(len(contract.Code)), false) + contract.Gas -= in.evm.AccessEvents.CodeChunksRangeGas(contractAddr, pc, 1, uint64(len(contract.Code)), false) } // Get the operation from the jump table and validate the stack to ensure there are diff --git a/core/vm/runtime/runtime_example_test.go b/core/vm/runtime/runtime_example_test.go index b7d0ddc384..ccb8f30c94 100644 --- a/core/vm/runtime/runtime_example_test.go +++ b/core/vm/runtime/runtime_example_test.go @@ -28,7 +28,7 @@ func ExampleExecute() { if err != nil { fmt.Println(err) } - fmt.Println(ret) + fmt.Println(string(ret)) // Output: // [96 96 96 64 82 96 8 86 91 0] } diff --git a/crypto/crypto.go b/crypto/crypto.go index 13e9b134f0..befd5fb92d 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -142,7 +142,7 @@ func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey { // it can also accept legacy encodings (0 prefixes). func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) { priv := new(ecdsa.PrivateKey) - priv.PublicKey.Curve = S256() + priv.Curve = S256() if strict && 8*len(d) != priv.Params().BitSize { return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize) } @@ -157,8 +157,8 @@ func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) { return nil, errors.New("invalid private key, zero or negative") } - priv.PublicKey.X, priv.PublicKey.Y = S256().ScalarBaseMult(d) - if priv.PublicKey.X == nil { + priv.X, priv.Y = S256().ScalarBaseMult(d) + if priv.X == nil { return nil, errors.New("invalid private key") } return priv, nil diff --git a/crypto/ecies/ecies.go b/crypto/ecies/ecies.go index 76f934c72d..6ced3d22b8 100644 --- a/crypto/ecies/ecies.go +++ b/crypto/ecies/ecies.go @@ -102,14 +102,14 @@ func GenerateKey(rand io.Reader, curve elliptic.Curve, params *ECIESParams) (prv return } prv = new(PrivateKey) - prv.PublicKey.X = sk.X - prv.PublicKey.Y = sk.Y - prv.PublicKey.Curve = curve + prv.X = sk.X + prv.Y = sk.Y + prv.Curve = curve prv.D = new(big.Int).Set(sk.D) if params == nil { params = ParamsFromCurve(curve) } - prv.PublicKey.Params = params + prv.Params = params return } @@ -121,14 +121,14 @@ func MaxSharedKeyLength(pub *PublicKey) int { // GenerateShared ECDH key agreement method used to establish secret keys for encryption. func (prv *PrivateKey) GenerateShared(pub *PublicKey, skLen, macLen int) (sk []byte, err error) { - if prv.PublicKey.Curve != pub.Curve { + if prv.Curve != pub.Curve { return nil, ErrInvalidCurve } if skLen+macLen > MaxSharedKeyLength(pub) { return nil, ErrSharedKeyTooBig } - x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, prv.D.Bytes()) + x, _ := pub.ScalarMult(pub.X, pub.Y, prv.D.Bytes()) if x == nil { return nil, ErrSharedKeyIsPointAtInfinity } @@ -258,7 +258,7 @@ func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err e d := messageTag(params.Hash, Km, em, s2) if curve, ok := pub.Curve.(crypto.EllipticCurve); ok { - Rb := curve.Marshal(R.PublicKey.X, R.PublicKey.Y) + Rb := curve.Marshal(R.X, R.Y) ct = make([]byte, len(Rb)+len(em)+len(d)) copy(ct, Rb) copy(ct[len(Rb):], em) @@ -282,7 +282,7 @@ func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) { var ( rLen int - hLen int = hash.Size() + hLen = hash.Size() mStart int mEnd int ) @@ -301,7 +301,7 @@ func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) { mEnd = len(c) - hLen R := new(PublicKey) - R.Curve = prv.PublicKey.Curve + R.Curve = prv.Curve if curve, ok := R.Curve.(crypto.EllipticCurve); ok { R.X, R.Y = curve.Unmarshal(c[:rLen]) diff --git a/crypto/ecies/ecies_test.go b/crypto/ecies/ecies_test.go index e3da71010e..dcda88c994 100644 --- a/crypto/ecies/ecies_test.go +++ b/crypto/ecies/ecies_test.go @@ -109,17 +109,17 @@ func TestSharedKeyPadding(t *testing.T) { y0, _ := new(big.Int).SetString("e040bd480b1deccc3bc40bd5b1fdcb7bfd352500b477cb9471366dbd4493f923", 16) y1, _ := new(big.Int).SetString("8ad915f2b503a8be6facab6588731fefeb584fd2dfa9a77a5e0bba1ec439e4fa", 16) - if prv0.PublicKey.X.Cmp(x0) != 0 { - t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.PublicKey.X.Bytes(), x0.Bytes()) + if prv0.X.Cmp(x0) != 0 { + t.Errorf("mismatched prv0.X:\nhave: %x\nwant: %x\n", prv0.X.Bytes(), x0.Bytes()) } - if prv0.PublicKey.Y.Cmp(y0) != 0 { - t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.PublicKey.Y.Bytes(), y0.Bytes()) + if prv0.Y.Cmp(y0) != 0 { + t.Errorf("mismatched prv0.Y:\nhave: %x\nwant: %x\n", prv0.Y.Bytes(), y0.Bytes()) } - if prv1.PublicKey.X.Cmp(x1) != 0 { - t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.PublicKey.X.Bytes(), x1.Bytes()) + if prv1.X.Cmp(x1) != 0 { + t.Errorf("mismatched prv1.X:\nhave: %x\nwant: %x\n", prv1.X.Bytes(), x1.Bytes()) } - if prv1.PublicKey.Y.Cmp(y1) != 0 { - t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.PublicKey.Y.Bytes(), y1.Bytes()) + if prv1.Y.Cmp(y1) != 0 { + t.Errorf("mismatched prv1.Y:\nhave: %x\nwant: %x\n", prv1.Y.Bytes(), y1.Bytes()) } // test shared secret generation diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index 3f3f9b7f0c..4eeef84f17 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -531,13 +531,14 @@ func (d *Downloader) syncToHead() (err error) { func() error { return d.fetchReceipts(origin + 1) }, // Receipts are retrieved during snap sync func() error { return d.processHeaders(origin + 1) }, } - if mode == ethconfig.SnapSync { + switch mode { + case ethconfig.SnapSync: d.pivotLock.Lock() d.pivotHeader = pivot d.pivotLock.Unlock() fetchers = append(fetchers, func() error { return d.processSnapSyncContent() }) - } else if mode == ethconfig.FullSync { + case ethconfig.FullSync: fetchers = append(fetchers, func() error { return d.processFullSyncContent() }) } return d.spawnSync(fetchers) diff --git a/eth/downloader/skeleton.go b/eth/downloader/skeleton.go index 04421a2bf5..ed9942dd04 100644 --- a/eth/downloader/skeleton.go +++ b/eth/downloader/skeleton.go @@ -277,26 +277,26 @@ func (s *skeleton) startup() { // higher layers request termination. There's no fancy explicit error // signalling as the sync loop should never terminate (TM). newhead, err := s.sync(head) - switch { - case err == errSyncLinked: + switch err { + case errSyncLinked: // Sync cycle linked up to the genesis block, or the existent chain // segment. Tear down the loop and restart it so, it can properly // notify the backfiller. Don't account a new head. head = nil - case err == errSyncMerged: + case errSyncMerged: // Subchains were merged, we just need to reinit the internal // start to continue on the tail of the merged chain. Don't // announce a new head, head = nil - case err == errSyncReorged: + case errSyncReorged: // The subchain being synced got modified at the head in a // way that requires resyncing it. Restart sync with the new // head to force a cleanup. head = newhead - case err == errTerminated: + case errTerminated: // Sync was requested to be terminated from within, stop and // return (no need to pass a message, was already done internally) return diff --git a/eth/handler.go b/eth/handler.go index 7179c9980b..6f15d21f35 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -275,7 +275,7 @@ func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error { } } // Ignore maxPeers if this is a trusted peer - if !peer.Peer.Info().Network.Trusted { + if !peer.Info().Network.Trusted { if reject || h.peers.len() >= h.maxPeers { return p2p.DiscTooManyPeers } @@ -386,7 +386,7 @@ func (h *handler) runSnapExtension(peer *snap.Peer, handler snap.Handler) error func (h *handler) removePeer(id string) { peer := h.peers.peer(id) if peer != nil { - peer.Peer.Disconnect(p2p.DiscUselessPeer) + peer.Disconnect(p2p.DiscUselessPeer) } } diff --git a/eth/protocols/eth/handlers.go b/eth/protocols/eth/handlers.go index ab56be7ffc..f4a1bbce3d 100644 --- a/eth/protocols/eth/handlers.go +++ b/eth/protocols/eth/handlers.go @@ -110,7 +110,7 @@ func serviceNonContiguousBlockHeaderQuery(chain *core.BlockChain, query *GetBloc next = current + query.Skip + 1 ) if next <= current { - infos, _ := json.MarshalIndent(peer.Peer.Info(), "", " ") + infos, _ := json.MarshalIndent(peer.Info(), "", " ") peer.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos) unknown = true } else { diff --git a/eth/protocols/eth/peer_test.go b/eth/protocols/eth/peer_test.go index efbbbc6fff..7511f0f2ac 100644 --- a/eth/protocols/eth/peer_test.go +++ b/eth/protocols/eth/peer_test.go @@ -60,7 +60,7 @@ func newTestPeer(name string, version uint, backend Backend) (*testPeer, <-chan // close terminates the local side of the peer, notifying the remote protocol // manager of termination. func (p *testPeer) close() { - p.Peer.Close() + p.Close() p.app.Close() } diff --git a/eth/protocols/snap/gentrie_test.go b/eth/protocols/snap/gentrie_test.go index 2da4f3c866..0751ac7ac7 100644 --- a/eth/protocols/snap/gentrie_test.go +++ b/eth/protocols/snap/gentrie_test.go @@ -469,10 +469,8 @@ func TestBoundSplit(t *testing.T) { lastRightRoot []byte ) - for { - if next == len(entries) { - break - } + for next != len(entries) { + last = rand.Intn(len(entries)-next) + next r := buildPartial(common.Hash{}, db, db.NewBatch(), entries, next, last) diff --git a/eth/protocols/snap/handler.go b/eth/protocols/snap/handler.go index 924aff7ac9..6f16825fa2 100644 --- a/eth/protocols/snap/handler.go +++ b/eth/protocols/snap/handler.go @@ -144,8 +144,8 @@ func HandleMessage(backend Backend, peer *Peer) error { }(start) } // Handle the message depending on its contents - switch { - case msg.Code == GetAccountRangeMsg: + switch msg.Code { + case GetAccountRangeMsg: // Decode the account retrieval request var req GetAccountRangePacket if err := msg.Decode(&req); err != nil { @@ -161,7 +161,7 @@ func HandleMessage(backend Backend, peer *Peer) error { Proof: proofs, }) - case msg.Code == AccountRangeMsg: + case AccountRangeMsg: // A range of accounts arrived to one of our previous requests res := new(AccountRangePacket) if err := msg.Decode(res); err != nil { @@ -177,7 +177,7 @@ func HandleMessage(backend Backend, peer *Peer) error { return backend.Handle(peer, res) - case msg.Code == GetStorageRangesMsg: + case GetStorageRangesMsg: // Decode the storage retrieval request var req GetStorageRangesPacket if err := msg.Decode(&req); err != nil { @@ -193,7 +193,7 @@ func HandleMessage(backend Backend, peer *Peer) error { Proof: proofs, }) - case msg.Code == StorageRangesMsg: + case StorageRangesMsg: // A range of storage slots arrived to one of our previous requests res := new(StorageRangesPacket) if err := msg.Decode(res); err != nil { @@ -211,7 +211,7 @@ func HandleMessage(backend Backend, peer *Peer) error { return backend.Handle(peer, res) - case msg.Code == GetByteCodesMsg: + case GetByteCodesMsg: // Decode bytecode retrieval request var req GetByteCodesPacket if err := msg.Decode(&req); err != nil { @@ -226,7 +226,7 @@ func HandleMessage(backend Backend, peer *Peer) error { Codes: codes, }) - case msg.Code == ByteCodesMsg: + case ByteCodesMsg: // A batch of byte codes arrived to one of our previous requests res := new(ByteCodesPacket) if err := msg.Decode(res); err != nil { @@ -236,7 +236,7 @@ func HandleMessage(backend Backend, peer *Peer) error { return backend.Handle(peer, res) - case msg.Code == GetTrieNodesMsg: + case GetTrieNodesMsg: // Decode trie node retrieval request var req GetTrieNodesPacket if err := msg.Decode(&req); err != nil { @@ -253,7 +253,7 @@ func HandleMessage(backend Backend, peer *Peer) error { Nodes: nodes, }) - case msg.Code == TrieNodesMsg: + case TrieNodesMsg: // A batch of trie nodes arrived to one of our previous requests res := new(TrieNodesPacket) if err := msg.Decode(res); err != nil { diff --git a/eth/protocols/snap/sync.go b/eth/protocols/snap/sync.go index 9e079f540f..c7133c22df 100644 --- a/eth/protocols/snap/sync.go +++ b/eth/protocols/snap/sync.go @@ -615,7 +615,7 @@ func (s *Syncer) Sync(root common.Hash, cancel chan struct{}) error { s.statelessPeers = make(map[string]struct{}) s.lock.Unlock() - if s.startTime == (time.Time{}) { + if s.startTime.Equal((time.Time{})) { s.startTime = time.Now() } // Retrieve the previous sync status from LevelDB and abort if already synced diff --git a/ethdb/pebble/pebble.go b/ethdb/pebble/pebble.go index b87ecb2595..9c0c38aef4 100644 --- a/ethdb/pebble/pebble.go +++ b/ethdb/pebble/pebble.go @@ -108,9 +108,10 @@ func (d *Database) onCompactionBegin(info pebble.CompactionInfo) { } func (d *Database) onCompactionEnd(info pebble.CompactionInfo) { - if d.activeComp == 1 { + switch d.activeComp { + case 1: d.compTime.Add(int64(time.Since(d.compStartTime))) - } else if d.activeComp == 0 { + case 0: panic("should not happen") } d.activeComp-- @@ -566,15 +567,16 @@ func (b *batch) Replay(w ethdb.KeyValueWriter) error { } // The (k,v) slices might be overwritten if the batch is reset/reused, // and the receiver should copy them if they are to be retained long-term. - if kind == pebble.InternalKeyKindSet { + switch kind { + case pebble.InternalKeyKindSet: if err = w.Put(k, v); err != nil { return err } - } else if kind == pebble.InternalKeyKindDelete { + case pebble.InternalKeyKindDelete: if err = w.Delete(k); err != nil { return err } - } else { + default: return fmt.Errorf("unhandled operation, keytype: %v", kind) } } diff --git a/internal/ethapi/simulate.go b/internal/ethapi/simulate.go index ba346b132f..d384f55cce 100644 --- a/internal/ethapi/simulate.go +++ b/internal/ethapi/simulate.go @@ -101,7 +101,7 @@ type simChainHeadReader struct { } func (m *simChainHeadReader) Config() *params.ChainConfig { - return m.Backend.ChainConfig() + return m.ChainConfig() } func (m *simChainHeadReader) CurrentHeader() *types.Header { @@ -109,7 +109,7 @@ func (m *simChainHeadReader) CurrentHeader() *types.Header { } func (m *simChainHeadReader) GetHeader(hash common.Hash, number uint64) *types.Header { - header, err := m.Backend.HeaderByNumber(m.Context, rpc.BlockNumber(number)) + header, err := m.HeaderByNumber(m.Context, rpc.BlockNumber(number)) if err != nil || header == nil { return nil } @@ -120,7 +120,7 @@ func (m *simChainHeadReader) GetHeader(hash common.Hash, number uint64) *types.H } func (m *simChainHeadReader) GetHeaderByNumber(number uint64) *types.Header { - header, err := m.Backend.HeaderByNumber(m.Context, rpc.BlockNumber(number)) + header, err := m.HeaderByNumber(m.Context, rpc.BlockNumber(number)) if err != nil { return nil } @@ -128,7 +128,7 @@ func (m *simChainHeadReader) GetHeaderByNumber(number uint64) *types.Header { } func (m *simChainHeadReader) GetHeaderByHash(hash common.Hash) *types.Header { - header, err := m.Backend.HeaderByHash(m.Context, hash) + header, err := m.HeaderByHash(m.Context, hash) if err != nil { return nil } diff --git a/internal/ethapi/transaction_args_test.go b/internal/ethapi/transaction_args_test.go index a5fd9bb0d4..6eb718a12b 100644 --- a/internal/ethapi/transaction_args_test.go +++ b/internal/ethapi/transaction_args_test.go @@ -296,19 +296,20 @@ func newBackendMock() *backendMock { } func (b *backendMock) setFork(fork string) error { - if fork == "legacy" { + switch fork { + case "legacy": b.current.Number = big.NewInt(900) b.current.Time = 555 - } else if fork == "london" { + case "london": b.current.Number = big.NewInt(1100) b.current.Time = 555 - } else if fork == "cancun" { + case "cancun": b.current.Number = big.NewInt(1100) b.current.Time = 700 // Blob base fee will be 2 excess := uint64(2314058) b.current.ExcessBlobGas = &excess - } else { + default: return errors.New("invalid fork") } return nil diff --git a/metrics/prometheus/collector.go b/metrics/prometheus/collector.go index 31b8c51b65..311857013e 100644 --- a/metrics/prometheus/collector.go +++ b/metrics/prometheus/collector.go @@ -99,7 +99,7 @@ func (c *collector) addHistogram(name string, m metrics.HistogramSnapshot) { pv := []float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999} ps := m.Percentiles(pv) c.writeSummaryCounter(name, m.Count()) - c.buff.WriteString(fmt.Sprintf(typeSummaryTpl, mutateKey(name))) + fmt.Fprintf(c.buff, typeSummaryTpl, mutateKey(name)) for i := range pv { c.writeSummaryPercentile(name, strconv.FormatFloat(pv[i], 'f', -1, 64), ps[i]) } @@ -114,7 +114,7 @@ func (c *collector) addTimer(name string, m *metrics.TimerSnapshot) { pv := []float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999} ps := m.Percentiles(pv) c.writeSummaryCounter(name, m.Count()) - c.buff.WriteString(fmt.Sprintf(typeSummaryTpl, mutateKey(name))) + fmt.Fprintf(c.buff, typeSummaryTpl, mutateKey(name)) for i := range pv { c.writeSummaryPercentile(name, strconv.FormatFloat(pv[i], 'f', -1, 64), ps[i]) } @@ -128,7 +128,7 @@ func (c *collector) addResettingTimer(name string, m *metrics.ResettingTimerSnap pv := []float64{0.5, 0.75, 0.95, 0.99, 0.999, 0.9999} ps := m.Percentiles(pv) c.writeSummaryCounter(name, m.Count()) - c.buff.WriteString(fmt.Sprintf(typeSummaryTpl, mutateKey(name))) + fmt.Fprintf(c.buff, typeSummaryTpl, mutateKey(name)) for i := range pv { c.writeSummaryPercentile(name, strconv.FormatFloat(pv[i], 'f', -1, 64), ps[i]) } @@ -137,7 +137,7 @@ func (c *collector) addResettingTimer(name string, m *metrics.ResettingTimerSnap func (c *collector) writeGaugeInfo(name string, value metrics.GaugeInfoValue) { name = mutateKey(name) - c.buff.WriteString(fmt.Sprintf(typeGaugeTpl, name)) + fmt.Fprintf(c.buff, typeGaugeTpl, name) c.buff.WriteString(name) c.buff.WriteString(" ") var kvs []string @@ -145,24 +145,24 @@ func (c *collector) writeGaugeInfo(name string, value metrics.GaugeInfoValue) { kvs = append(kvs, fmt.Sprintf("%v=%q", k, v)) } sort.Strings(kvs) - c.buff.WriteString(fmt.Sprintf("{%v} 1\n\n", strings.Join(kvs, ", "))) + fmt.Fprintf(c.buff, "{%v} 1\n\n", strings.Join(kvs, ", ")) } func (c *collector) writeGaugeCounter(name string, value interface{}) { name = mutateKey(name) - c.buff.WriteString(fmt.Sprintf(typeGaugeTpl, name)) - c.buff.WriteString(fmt.Sprintf(keyValueTpl, name, value)) + fmt.Fprintf(c.buff, typeGaugeTpl, name) + fmt.Fprintf(c.buff, keyValueTpl, name, value) } func (c *collector) writeSummaryCounter(name string, value interface{}) { name = mutateKey(name + "_count") - c.buff.WriteString(fmt.Sprintf(typeCounterTpl, name)) - c.buff.WriteString(fmt.Sprintf(keyValueTpl, name, value)) + fmt.Fprintf(c.buff, typeCounterTpl, name) + fmt.Fprintf(c.buff, keyValueTpl, name, value) } func (c *collector) writeSummaryPercentile(name, p string, value interface{}) { name = mutateKey(name) - c.buff.WriteString(fmt.Sprintf(keyQuantileTagValueTpl, name, p, value)) + fmt.Fprintf(c.buff, keyQuantileTagValueTpl, name, p, value) } func mutateKey(key string) string { diff --git a/metrics/resetting_sample.go b/metrics/resetting_sample.go index 730ef93416..e0cd8f80f1 100644 --- a/metrics/resetting_sample.go +++ b/metrics/resetting_sample.go @@ -19,6 +19,6 @@ type resettingSample struct { // Snapshot returns a read-only copy of the sample with the original reset. func (rs *resettingSample) Snapshot() *sampleSnapshot { s := rs.Sample.Snapshot() - rs.Sample.Clear() + rs.Clear() return s } diff --git a/node/node.go b/node/node.go index ec7382e725..38ff3a2b8d 100644 --- a/node/node.go +++ b/node/node.go @@ -133,12 +133,12 @@ func New(conf *Config) (*Node, error) { node.accman = accounts.NewManager(nil) // Initialize the p2p server. This creates the node key and discovery databases. - node.server.Config.PrivateKey = node.config.NodeKey() - node.server.Config.Name = node.config.NodeName() - node.server.Config.Logger = node.log + node.server.PrivateKey = node.config.NodeKey() + node.server.Name = node.config.NodeName() + node.server.Logger = node.log node.config.checkLegacyFiles() - if node.server.Config.NodeDatabase == "" { - node.server.Config.NodeDatabase = node.config.NodeDB() + if node.server.NodeDatabase == "" { + node.server.NodeDatabase = node.config.NodeDB() } // Check HTTP/WS prefixes are valid. diff --git a/p2p/discover/table.go b/p2p/discover/table.go index 6a3d1af3af..d94351685b 100644 --- a/p2p/discover/table.go +++ b/p2p/discover/table.go @@ -562,7 +562,7 @@ func (tab *Table) addReplacement(b *bucket, n *enode.Node) { } func (tab *Table) nodeAdded(b *bucket, n *tableNode) { - if n.addedToTable == (time.Time{}) { + if n.addedToTable.Equal((time.Time{})) { n.addedToTable = time.Now() } n.addedToBucket = time.Now() diff --git a/p2p/discover/v4wire/v4wire.go b/p2p/discover/v4wire/v4wire.go index 958cca324d..cd0072e6a6 100644 --- a/p2p/discover/v4wire/v4wire.go +++ b/p2p/discover/v4wire/v4wire.go @@ -291,7 +291,7 @@ func DecodePubkey(curve elliptic.Curve, e Pubkey) (*ecdsa.PublicKey, error) { half := len(e) / 2 p.X.SetBytes(e[:half]) p.Y.SetBytes(e[half:]) - if !p.Curve.IsOnCurve(p.X, p.Y) { + if !p.IsOnCurve(p.X, p.Y) { return nil, ErrBadPoint } return p, nil diff --git a/p2p/peer.go b/p2p/peer.go index a01df63d0c..44f6dcc443 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -553,7 +553,7 @@ func (p *Peer) Info() *PeerInfo { // Gather all the running protocol infos for _, proto := range p.running { protoInfo := interface{}("unknown") - if query := proto.Protocol.PeerInfo; query != nil { + if query := proto.PeerInfo; query != nil { if metadata := query(p.ID()); metadata != nil { protoInfo = metadata } else { diff --git a/rpc/client_test.go b/rpc/client_test.go index 6c1a4f8f6c..5e076f4f64 100644 --- a/rpc/client_test.go +++ b/rpc/client_test.go @@ -394,8 +394,8 @@ func testClientCancel(transport string, t *testing.T) { // Now perform a call with the context. // The key thing here is that no call will ever complete successfully. err := client.CallContext(ctx, nil, "test_block") - switch { - case err == nil: + switch err { + case nil: _, hasDeadline := ctx.Deadline() t.Errorf("no error for call with %v wait time (deadline: %v)", timeout, hasDeadline) // default: diff --git a/rpc/handler.go b/rpc/handler.go index f23b544b58..1f9d896dc3 100644 --- a/rpc/handler.go +++ b/rpc/handler.go @@ -218,11 +218,9 @@ func (h *handler) handleBatch(msgs []*jsonrpcMessage) { } responseBytes := 0 - for { + for cp.ctx.Err() == nil { // No need to handle rest of calls if timed out. - if cp.ctx.Err() != nil { - break - } + msg := callBuffer.nextCall() if msg == nil { break diff --git a/rpc/websocket.go b/rpc/websocket.go index 9f67caf859..a7808b3f08 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -362,11 +362,11 @@ func (wc *websocketCodec) pingLoop() { pingTimer.Reset(wsPingInterval) case <-pingTimer.C: - wc.jsonCodec.encMu.Lock() + wc.encMu.Lock() wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout)) wc.conn.WriteMessage(websocket.PingMessage, nil) wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout)) - wc.jsonCodec.encMu.Unlock() + wc.encMu.Unlock() pingTimer.Reset(wsPingInterval) case <-wc.pongReceived: diff --git a/signer/rules/rules.go b/signer/rules/rules.go index c9921e57a9..7f5b01d53a 100644 --- a/signer/rules/rules.go +++ b/signer/rules/rules.go @@ -140,10 +140,11 @@ func (r *rulesetUI) checkApproval(jsfunc string, jsarg []byte, err error) (bool, return false, err } result := v.ToString().String() - if result == "Approve" { + switch result { + case "Approve": log.Info("Op approved") return true, nil - } else if result == "Reject" { + case "Reject": log.Info("Op rejected") return false, nil } diff --git a/trie/database_test.go b/trie/database_test.go index 729d9f699b..ef567597de 100644 --- a/trie/database_test.go +++ b/trie/database_test.go @@ -105,10 +105,8 @@ func (db *testDb) dirties(root common.Hash, topToBottom bool) ([]*trienode.Merge pending []*trienode.MergedNodeSet roots []common.Hash ) - for { - if root == db.root { - break - } + for root != db.root { + nodes, ok := db.nodes[root] if !ok { break diff --git a/triedb/pathdb/journal.go b/triedb/pathdb/journal.go index 79a7a22e0b..4b0d74b1c2 100644 --- a/triedb/pathdb/journal.go +++ b/triedb/pathdb/journal.go @@ -105,7 +105,7 @@ func (db *Database) loadLayers() layer { // journal is not matched(or missing) with the persistent state, discard // it. Display log for discarding journal, but try to avoid showing // useless information when the db is created from scratch. - if !(root == types.EmptyRootHash && errors.Is(err, errMissJournal)) { + if root != types.EmptyRootHash || !errors.Is(err, errMissJournal) { log.Info("Failed to load journal, discard it", "err", err) } // Return single layer with persistent state.