From 418a37612a8e536d9363637a261e091e53e4d92d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= <93934272+Stefan-Ethernal@users.noreply.github.com> Date: Mon, 16 Sep 2024 10:57:15 +0200 Subject: [PATCH] fix: Linters warning fixes (#74) * feat: use the latest golangci-lint version and fix config warnings * fix: linter warnings * fix: linter warnings (part 2) * fix: propagate the error from aggregator.Start * fix: format golangci config file * fix: suppress gosec overflow issues * fix: exclude G115 gosec linter rule * fix: use crypto/rand number generator --- .github/workflows/lint.yml | 2 +- .golangci.yml | 86 +++++++++---------- aggoracle/oracle.go | 9 +- aggregator/aggregator.go | 32 ++++--- aggregator/profitabilitychecker.go | 12 +-- aggregator/prover/prover.go | 14 +-- claimsponsor/claimsponsor.go | 10 ++- cmd/run.go | 1 + config/types/duration_test.go | 2 +- .../datacommittee/datacommittee.go | 10 ++- etherman/errors.go | 4 +- hex/hex.go | 6 +- l1infotree/hash.go | 2 +- l1infotree/tree.go | 7 +- l1infotreesync/processor.go | 16 ++-- lastgersync/processor.go | 10 ++- log/log.go | 2 +- log/log_test.go | 2 +- merkletree/key.go | 6 +- merkletree/split.go | 20 ++--- reorgdetector/reorgdetector.go | 2 +- rpc/bridge.go | 10 ++- sequencesender/seqsendertypes/types.go | 5 +- sequencesender/sequencesender.go | 43 +++++----- sequencesender/txbuilder/banana_base.go | 2 +- sequencesender/txbuilder/banana_base_test.go | 2 +- sequencesender/txbuilder/interface.go | 4 +- .../txbuilder/validium_cond_num_batches.go | 2 +- .../txbuilder/zkevm_cond_max_size.go | 1 - state/encoding_batch_v2_test.go | 4 +- state/helper.go | 2 +- state/pgstatestorage/proof.go | 4 +- sync/evmdownloader.go | 2 +- test/helpers/aggoracle_e2e.go | 10 +-- tree/appendonlytree.go | 1 + tree/testvectors/types.go | 4 +- 36 files changed, 187 insertions(+), 164 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 257488da..99b68b8c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -20,4 +20,4 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v6 with: - version: v1.60 + version: v1.61 diff --git a/.golangci.yml b/.golangci.yml index 5dd6e0ec..98197d74 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,50 +3,45 @@ run: timeout: 3m tests: true - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ skip-dirs-use-default: true - skip-dirs: - - tests - - aggregator/db/migrations service: - golangci-lint-version: 1.59.1 + golangci-lint-version: 1.61.0 linters: disable-all: true enable: - - whitespace # Tool for detection of leading and trailing whitespace - # - wsl # Forces you to use empty lines - - wastedassign # Finds wasted assignment statements - - unconvert # Unnecessary type conversions - - tparallel # Detects inappropriate usage of t.Parallel() method in your Go test codes - - thelper # Detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - stylecheck # Stylecheck is a replacement for golint - - prealloc # Finds slice declarations that could potentially be pre-allocated - - predeclared # Finds code that shadows one of Go's predeclared identifiers - - nolintlint # Ill-formed or insufficient nolint directives - # - nlreturn # Checks for a new line before return and branch statements to increase code clarity - - misspell # Misspelled English words in comments - - makezero # Finds slice declarations with non-zero initial length - - lll # Long lines - - importas # Enforces consistent import aliases - - gosec # Security problems - - gofmt # Whether the code was gofmt-ed - - goimports # Unused imports - - goconst # Repeated strings that could be replaced by a constant - - forcetypeassert # Finds forced type assertions - - dogsled # Checks assignments with too many blank identifiers (e.g. x, , , _, := f()) - - dupl # Code clone detection - - errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13 - - gocritic # gocritic is a Go source code linter that maintains checks that are not in other linters - - errcheck # Errcheck is a go lint rule for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - # - godox # Godox is a linter for TODOs and FIXMEs left in the code - - gci # Gci is a linter for checking the consistency of the code with the go code style guide - - gomnd # Gomnd is a linter for magic numbers - # - revive - - unparam # Unparam is a linter for unused function parameters + - whitespace # Tool for detection of leading and trailing whitespace + # - wsl # Forces you to use empty lines + - wastedassign # Finds wasted assignment statements + - unconvert # Unnecessary type conversions + - tparallel # Detects inappropriate usage of t.Parallel() method in your Go test codes + - thelper # Detects golang test helpers without t.Helper() call and checks the consistency of test helpers + - stylecheck # Stylecheck is a replacement for golint + - prealloc # Finds slice declarations that could potentially be pre-allocated + - predeclared # Finds code that shadows one of Go's predeclared identifiers + - nolintlint # Ill-formed or insufficient nolint directives + # - nlreturn # Checks for a new line before return and branch statements to increase code clarity + - misspell # Misspelled English words in comments + - makezero # Finds slice declarations with non-zero initial length + - lll # Long lines + - importas # Enforces consistent import aliases + - gosec # Security problems + - gofmt # Whether the code was gofmt-ed + - goimports # Unused imports + - goconst # Repeated strings that could be replaced by a constant + - forcetypeassert # Finds forced type assertions + - dogsled # Checks assignments with too many blank identifiers (e.g. x, , , _, := f()) + - dupl # Code clone detection + - errname # Checks that sentinel errors are prefixed with Err and error types are suffixed with Error + - errorlint # Error wrapping introduced in Go 1.13 + - gocritic # gocritic is a Go source code linter that maintains checks that are not in other linters + - errcheck # Errcheck is a go lint rule for checking for unchecked errors + # - godox # Linter for TODOs and FIXMEs left in the code + - gci # Gci checks the consistency of the code with the Go code style guide + - mnd # mnd is a linter for magic numbers + # - revive + - unparam # Unused function parameters linters-settings: gofmt: @@ -54,20 +49,19 @@ linters-settings: gocritic: enabled-checks: - ruleguard - # settings: - # ruleguard: - # rules: "./gorules/rules.go" revive: rules: - - name: exported - arguments: - - disableStutteringCheck + - name: exported + arguments: + - disableStutteringCheck goconst: min-len: 3 min-occurrences: 3 + gosec: + excludes: + - G115 # Potential integer overflow when converting between integer types issues: - # new-from-rev: origin/develop # report only new issues with reference to develop branch whole-files: true exclude-rules: - path: '(_test\.go|^test/.*)' @@ -78,9 +72,11 @@ issues: - path: 'etherman/contracts/contracts_(banana|elderberry)\.go' linters: - dupl + exclude-dirs: + - tests + - aggregator/db/migrations include: - EXC0012 # Exported (.+) should have comment( \(or a comment on this block\))? or be unexported - EXC0013 # Package comment should be of the form "(.+)... - EXC0014 # Comment on exported (.+) should be of the form "(.+)..." - EXC0015 # Should have a package comment - \ No newline at end of file diff --git a/aggoracle/oracle.go b/aggoracle/oracle.go index 27383f43..df5b0297 100644 --- a/aggoracle/oracle.go +++ b/aggoracle/oracle.go @@ -63,12 +63,15 @@ func (a *AggOracle) Start(ctx context.Context) { case <-a.ticker.C: blockNumToFetch, gerToInject, err = a.getLastFinalisedGER(ctx, blockNumToFetch) if err != nil { - if errors.Is(err, l1infotreesync.ErrBlockNotProcessed) { + switch { + case errors.Is(err, l1infotreesync.ErrBlockNotProcessed): log.Debugf("syncer is not ready for the block %d", blockNumToFetch) - } else if errors.Is(err, l1infotreesync.ErrNotFound) { + + case errors.Is(err, l1infotreesync.ErrNotFound): blockNumToFetch = 0 log.Debugf("syncer has not found any GER until block %d", blockNumToFetch) - } else { + + default: log.Error("error calling getLastFinalisedGER: ", err) } diff --git a/aggregator/aggregator.go b/aggregator/aggregator.go index 0ba92c25..c5344b15 100644 --- a/aggregator/aggregator.go +++ b/aggregator/aggregator.go @@ -277,7 +277,7 @@ func (a *Aggregator) handleReorg(reorgData synchronizer.ReorgExecutionResult) { "Halting the aggregator due to a L1 reorg. " + "Reorged data has been deleted, so it is safe to manually restart the aggregator.", ) - time.Sleep(10 * time.Second) //nolint:gomnd + time.Sleep(10 * time.Second) //nolint:mnd } } @@ -375,6 +375,7 @@ func (a *Aggregator) handleRollbackBatches(rollbackData synchronizer.RollbackBat } marshalledBookMark, err = proto.Marshal(bookMark) + //nolint:gocritic if err != nil { log.Error("failed to marshal bookmark: %v", err) } else { @@ -403,7 +404,7 @@ func (a *Aggregator) handleRollbackBatches(rollbackData synchronizer.RollbackBat a.halted.Store(true) for { log.Errorf("Halting the aggregator due to an error handling rollback batches event: %v", err) - time.Sleep(10 * time.Second) //nolint:gomnd + time.Sleep(10 * time.Second) //nolint:mnd } } } @@ -738,7 +739,7 @@ func (a *Aggregator) Start() error { err = a.streamClient.Start() if err != nil { - log.Fatalf("failed to start stream client, error: %v", err) + return fmt.Errorf("failed to start stream client, error: %w", err) } bookMark := &datastream.BookMark{ @@ -748,12 +749,12 @@ func (a *Aggregator) Start() error { marshalledBookMark, err := proto.Marshal(bookMark) if err != nil { - log.Fatalf("failed to marshal bookmark: %v", err) + return fmt.Errorf("failed to marshal bookmark: %w", err) } err = a.streamClient.ExecCommandStartBookmark(marshalledBookMark) if err != nil { - log.Fatalf("failed to connect to data stream: %v", err) + return fmt.Errorf("failed to connect to data stream: %w", err) } // A this point everything is ready, so start serving @@ -1151,6 +1152,7 @@ func (a *Aggregator) validateEligibleFinalProof( batchNumberToVerify := lastVerifiedBatchNum + 1 if proof.BatchNumber != batchNumberToVerify { + //nolint:gocritic if proof.BatchNumber < batchNumberToVerify && proof.BatchNumberFinal >= batchNumberToVerify { // We have a proof that contains some batches below the last batch verified, anyway can be eligible as final proof log.Warnf( @@ -1764,8 +1766,9 @@ func (a *Aggregator) buildInputProver( l1InfoTreeData := map[uint32]*prover.L1Data{} forcedBlockhashL1 := common.Hash{} l1InfoRoot := batchToVerify.L1InfoRoot.Bytes() + //nolint:gocritic if !isForcedBatch { - tree, err := l1infotree.NewL1InfoTree(32, [][32]byte{}) //nolint:gomnd + tree, err := l1infotree.NewL1InfoTree(32, [][32]byte{}) //nolint:mnd if err != nil { return nil, err } @@ -1777,7 +1780,10 @@ func (a *Aggregator) buildInputProver( aLeaves := make([][32]byte, len(leaves)) for i, leaf := range leaves { - aLeaves[i] = l1infotree.HashLeafData(leaf.GlobalExitRoot, leaf.PreviousBlockHash, uint64(leaf.Timestamp.Unix())) + aLeaves[i] = l1infotree.HashLeafData( + leaf.GlobalExitRoot, + leaf.PreviousBlockHash, + uint64(leaf.Timestamp.Unix())) } for _, l2blockRaw := range batchRawData.Blocks { @@ -1877,10 +1883,12 @@ func (a *Aggregator) buildInputProver( return inputProver, nil } -func getWitness(batchNumber uint64, URL string, fullWitness bool) ([]byte, error) { - var witness string - var response rpc.Response - var err error +func getWitness(batchNumber uint64, url string, fullWitness bool) ([]byte, error) { + var ( + witness string + response rpc.Response + err error + ) witnessType := "trimmed" if fullWitness { @@ -1889,7 +1897,7 @@ func getWitness(batchNumber uint64, URL string, fullWitness bool) ([]byte, error log.Infof("Requesting witness for batch %d of type %s", batchNumber, witnessType) - response, err = rpc.JSONRPCCall(URL, "zkevm_getBatchWitness", batchNumber, witnessType) + response, err = rpc.JSONRPCCall(url, "zkevm_getBatchWitness", batchNumber, witnessType) if err != nil { return nil, err } diff --git a/aggregator/profitabilitychecker.go b/aggregator/profitabilitychecker.go index 225cedb9..f05799eb 100644 --- a/aggregator/profitabilitychecker.go +++ b/aggregator/profitabilitychecker.go @@ -36,7 +36,7 @@ func NewTxProfitabilityCheckerBase( // IsProfitable checks pol collateral with min reward func (pc *TxProfitabilityCheckerBase) IsProfitable(ctx context.Context, polCollateral *big.Int) (bool, error) { - //if pc.IntervalAfterWhichBatchSentAnyway != 0 { + // if pc.IntervalAfterWhichBatchSentAnyway != 0 { // ok, err := isConsolidatedBatchAppeared(ctx, pc.State, pc.IntervalAfterWhichBatchSentAnyway) // if err != nil { // return false, err @@ -44,7 +44,7 @@ func (pc *TxProfitabilityCheckerBase) IsProfitable(ctx context.Context, polColla // if ok { // return true, nil // } - //} + // } return polCollateral.Cmp(pc.MinReward) >= 0, nil } @@ -64,7 +64,7 @@ func NewTxProfitabilityCheckerAcceptAll(state stateInterface, interval time.Dura // IsProfitable validate batch anyway and don't check anything func (pc *TxProfitabilityCheckerAcceptAll) IsProfitable(ctx context.Context, polCollateral *big.Int) (bool, error) { - //if pc.IntervalAfterWhichBatchSentAnyway != 0 { + // if pc.IntervalAfterWhichBatchSentAnyway != 0 { // ok, err := isConsolidatedBatchAppeared(ctx, pc.State, pc.IntervalAfterWhichBatchSentAnyway) // if err != nil { // return false, err @@ -72,12 +72,12 @@ func (pc *TxProfitabilityCheckerAcceptAll) IsProfitable(ctx context.Context, pol // if ok { // return true, nil // } - //} + // } return true, nil } // TODO: now it's impossible to check, when batch got consolidated, bcs it's not saved -//func isConsolidatedBatchAppeared(ctx context.Context, state stateInterface, +// func isConsolidatedBatchAppeared(ctx context.Context, state stateInterface, // intervalAfterWhichBatchConsolidatedAnyway time.Duration) (bool, error) { // batch, err := state.GetLastVerifiedBatch(ctx, nil) // if err != nil { @@ -89,4 +89,4 @@ func (pc *TxProfitabilityCheckerAcceptAll) IsProfitable(ctx context.Context, pol // } // // return false, err -//} +// } diff --git a/aggregator/prover/prover.go b/aggregator/prover/prover.go index 285eadb2..a0a782f3 100644 --- a/aggregator/prover/prover.go +++ b/aggregator/prover/prover.go @@ -442,13 +442,13 @@ func fea2scalar(v []uint64) *big.Int { return big.NewInt(0) } res := new(big.Int).SetUint64(v[0]) - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[1]), 32)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[2]), 64)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[3]), 96)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[4]), 128)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[5]), 160)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[6]), 192)) //nolint:gomnd - res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[7]), 224)) //nolint:gomnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[1]), 32)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[2]), 64)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[3]), 96)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[4]), 128)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[5]), 160)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[6]), 192)) //nolint:mnd + res.Add(res, new(big.Int).Lsh(new(big.Int).SetUint64(v[7]), 224)) //nolint:mnd return res } diff --git a/claimsponsor/claimsponsor.go b/claimsponsor/claimsponsor.go index bad29c86..4537888b 100644 --- a/claimsponsor/claimsponsor.go +++ b/claimsponsor/claimsponsor.go @@ -271,15 +271,19 @@ func (c *ClaimSponsor) AddClaimToQueue(ctx context.Context, claim *Claim) error var queuePosition uint64 lastQueuePosition, _, err := getLastQueueIndex(tx) - if errors.Is(err, ErrNotFound) { + switch { + case errors.Is(err, ErrNotFound): queuePosition = 0 - } else if err != nil { + + case err != nil: tx.Rollback() return err - } else { + + default: queuePosition = lastQueuePosition + 1 } + err = tx.Put(queueTable, dbCommon.Uint64ToBytes(queuePosition), claim.Key()) if err != nil { tx.Rollback() diff --git a/cmd/run.go b/cmd/run.go index af5ff7a4..477bd90e 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -101,6 +101,7 @@ func start(cliCtx *cli.Context) error { // start aggregator in a goroutine, checking for errors go func() { if err := aggregator.Start(); err != nil { + aggregator.Stop() log.Fatal(err) } }() diff --git a/config/types/duration_test.go b/config/types/duration_test.go index 71e06a04..c11bd083 100644 --- a/config/types/duration_test.go +++ b/config/types/duration_test.go @@ -43,7 +43,7 @@ func TestDurationUnmarshal(t *testing.T) { err = json.Unmarshal(input, &d) if testCase.expectedResult != nil { - require.Equal(t, (*testCase.expectedResult).Nanoseconds(), d.Nanoseconds()) + require.Equal(t, testCase.expectedResult.Nanoseconds(), d.Nanoseconds()) } if err != nil { diff --git a/dataavailability/datacommittee/datacommittee.go b/dataavailability/datacommittee/datacommittee.go index 2a3cca8e..4ae4a751 100644 --- a/dataavailability/datacommittee/datacommittee.go +++ b/dataavailability/datacommittee/datacommittee.go @@ -2,10 +2,10 @@ package datacommittee import ( "crypto/ecdsa" + "crypto/rand" "errors" "fmt" "math/big" - "math/rand" "sort" "strings" @@ -91,7 +91,11 @@ func (d *Backend) Init() error { if committee != nil { d.committeeMembers = committee.Members if len(committee.Members) > 0 { - selectedCommitteeMember = rand.Intn(len(committee.Members)) //nolint:gosec + nBig, err := rand.Int(rand.Reader, big.NewInt(int64(len(committee.Members)))) + if err != nil { + return err + } + selectedCommitteeMember = int(nBig.Int64()) } } d.selectedCommitteeMember = selectedCommitteeMember @@ -304,7 +308,7 @@ func requestSignatureFromMember(ctx context.Context, signedSequence daTypes.Sign // request c := client.New(member.URL) log.Infof("sending request to sign the sequence to %s at %s", member.Addr.Hex(), member.URL) - //funcSign must call something like that c.SignSequenceBanana(ctx, signedSequence) + // funcSign must call something like that c.SignSequenceBanana(ctx, signedSequence) signature, err := funcSign(c) if err != nil { diff --git a/etherman/errors.go b/etherman/errors.go index c4fd9387..a2d748e7 100644 --- a/etherman/errors.go +++ b/etherman/errors.go @@ -10,9 +10,9 @@ var ( ErrGasRequiredExceedsAllowance = errors.New("gas required exceeds allowance") // ErrContentLengthTooLarge content length is too large ErrContentLengthTooLarge = errors.New("content length too large") - //ErrTimestampMustBeInsideRange Timestamp must be inside range + // ErrTimestampMustBeInsideRange Timestamp must be inside range ErrTimestampMustBeInsideRange = errors.New("timestamp must be inside range") - //ErrInsufficientAllowance insufficient allowance + // ErrInsufficientAllowance insufficient allowance ErrInsufficientAllowance = errors.New("insufficient allowance") // ErrBothGasPriceAndMaxFeeGasAreSpecified both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified ErrBothGasPriceAndMaxFeeGasAreSpecified = errors.New( diff --git a/hex/hex.go b/hex/hex.go index 7e5b1d01..c7e1f860 100644 --- a/hex/hex.go +++ b/hex/hex.go @@ -68,7 +68,7 @@ func DecodeUint64(str string) uint64 { // EncodeUint64 encodes a number as a hex string with 0x prefix. func EncodeUint64(i uint64) string { - enc := make([]byte, 2, 10) //nolint:gomnd + enc := make([]byte, 2, 10) //nolint:mnd copy(enc, "0x") return string(strconv.AppendUint(enc, i, Base)) @@ -83,9 +83,9 @@ func DecodeNibble(in byte) uint64 { case in >= '0' && in <= '9': return uint64(in - '0') case in >= 'A' && in <= 'F': - return uint64(in - 'A' + 10) //nolint:gomnd + return uint64(in - 'A' + 10) //nolint:mnd case in >= 'a' && in <= 'f': - return uint64(in - 'a' + 10) //nolint:gomnd + return uint64(in - 'a' + 10) //nolint:mnd default: return BadNibble } diff --git a/l1infotree/hash.go b/l1infotree/hash.go index 120ba6c6..5a33f5a3 100644 --- a/l1infotree/hash.go +++ b/l1infotree/hash.go @@ -37,7 +37,7 @@ func generateZeroHashes(height uint8) [][32]byte { // HashLeafData calculates the keccak hash of the leaf values. func HashLeafData(ger, prevBlockHash common.Hash, minTimestamp uint64) [32]byte { var res [32]byte - t := make([]byte, 8) //nolint:gomnd + t := make([]byte, 8) //nolint:mnd binary.BigEndian.PutUint64(t, minTimestamp) copy(res[:], keccak256.Hash(ger.Bytes(), prevBlockHash.Bytes(), t)) diff --git a/l1infotree/tree.go b/l1infotree/tree.go index 6f6b7406..d6503b01 100644 --- a/l1infotree/tree.go +++ b/l1infotree/tree.go @@ -30,8 +30,7 @@ func NewL1InfoTree(height uint8, initialLeaves [][32]byte) (*L1InfoTree, error) return nil, err } - log.Debug("Initial count: ", mt.count) - log.Debug("Initial root: ", mt.currentRoot) + log.Debugf("Initial count: %d, Initial root %s", mt.count, mt.currentRoot) return mt, nil } @@ -112,7 +111,7 @@ func (mt *L1InfoTree) ComputeMerkleProof(gerIndex uint32, leaves [][32]byte) ([] if index >= uint32(len(leaves)) { siblings = append(siblings, mt.zeroHashes[h]) } else { - if index%2 == 1 { //If it is odd + if index%2 == 1 { // If it is odd siblings = append(siblings, leaves[index-1]) } else { // It is even siblings = append(siblings, leaves[index+1]) @@ -130,7 +129,7 @@ func (mt *L1InfoTree) ComputeMerkleProof(gerIndex uint32, leaves [][32]byte) ([] } // Find the index of the leaf in the next level of the tree. // Divide the index by 2 to find the position in the upper level - index = uint32(float64(index) / 2) //nolint:gomnd + index = uint32(float64(index) / 2) //nolint:mnd ns = nsi leaves = hashes } diff --git a/l1infotreesync/processor.go b/l1infotreesync/processor.go index a6fa28a1..b5fb781d 100644 --- a/l1infotreesync/processor.go +++ b/l1infotreesync/processor.go @@ -100,7 +100,7 @@ type storeLeaf struct { // Hash as expected by the tree func (l *storeLeaf) Hash() ethCommon.Hash { var res [32]byte - t := make([]byte, 8) //nolint:gomnd + t := make([]byte, 8) //nolint:mnd binary.BigEndian.PutUint64(t, l.Timestamp) copy(res[:], keccak256.Hash(l.GlobalExitRoot().Bytes(), l.ParentHash.Bytes(), t)) @@ -376,16 +376,18 @@ func (p *processor) ProcessBlock(ctx context.Context, b sync.Block) error { l1InfoTreeLeavesToAdd := []tree.Leaf{} rollupExitTreeLeavesToAdd := []tree.Leaf{} if len(b.Events) > 0 { - var initialL1InfoIndex uint32 - var l1InfoLeavesAdded uint32 + var ( + initialL1InfoIndex uint32 + l1InfoLeavesAdded uint32 + ) lastIndex, err := p.getLastIndex(tx) - if errors.Is(err, ErrNotFound) { + switch { + case errors.Is(err, ErrNotFound): initialL1InfoIndex = 0 - } else if err != nil { + case err != nil: rollback() - return err - } else { + default: initialL1InfoIndex = lastIndex + 1 } for _, e := range b.Events { diff --git a/lastgersync/processor.go b/lastgersync/processor.go index 049b2847..628ea04a 100644 --- a/lastgersync/processor.go +++ b/lastgersync/processor.go @@ -141,13 +141,15 @@ func (p *processor) ProcessBlock(ctx context.Context, block sync.Block) error { var lastIndex int64 if lenEvents > 0 { li, err := p.getLastIndexWithTx(tx) - if errors.Is(err, ErrNotFound) { + switch { + case errors.Is(err, ErrNotFound): lastIndex = -1 - } else if err != nil { - tx.Rollback() + case err != nil: + tx.Rollback() return err - } else { + + default: lastIndex = int64(li) } } diff --git a/log/log.go b/log/log.go index eae9f543..525ee0e3 100644 --- a/log/log.go +++ b/log/log.go @@ -96,7 +96,7 @@ func NewLogger(cfg Config) (*zap.SugaredLogger, *zap.AtomicLevel, error) { defer logger.Sync() //nolint:errcheck // skip 2 callers: one for our wrapper methods and one for the package functions - withOptions := logger.WithOptions(zap.AddCallerSkip(2)) //nolint:gomnd + withOptions := logger.WithOptions(zap.AddCallerSkip(2)) //nolint:mnd return withOptions.Sugar(), &level, nil } diff --git a/log/log_test.go b/log/log_test.go index 9d33bcd0..9a596608 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -20,7 +20,7 @@ func TestLog(t *testing.T) { cfg := Config{ Environment: EnvironmentDevelopment, Level: "debug", - Outputs: []string{"stderr"}, //[]string{"stdout", "test.log"} + Outputs: []string{"stderr"}, // []string{"stdout", "test.log"} } Init(cfg) diff --git a/merkletree/key.go b/merkletree/key.go index 1fd6feec..7926df60 100644 --- a/merkletree/key.go +++ b/merkletree/key.go @@ -127,14 +127,14 @@ func HashContractBytecode(code []byte) ([]uint64, error) { ) // add 0x01 - code = append(code, 0x01) //nolint:gomnd + code = append(code, 0x01) //nolint:mnd // add padding for len(code)%(56) != 0 { - code = append(code, 0x00) //nolint:gomnd + code = append(code, 0x00) //nolint:mnd } - code[len(code)-1] = code[len(code)-1] | 0x80 //nolint:gomnd + code[len(code)-1] = code[len(code)-1] | 0x80 //nolint:mnd numHashes := int(math.Ceil(float64(len(code)) / float64(maxBytesToAdd))) diff --git a/merkletree/split.go b/merkletree/split.go index 77189b20..e264807a 100644 --- a/merkletree/split.go +++ b/merkletree/split.go @@ -17,16 +17,16 @@ const wordLength = 64 // scalar2fea splits a *big.Int into array of 32bit uint64 values. func scalar2fea(value *big.Int) []uint64 { - val := make([]uint64, 8) //nolint:gomnd - mask, _ := new(big.Int).SetString("FFFFFFFF", 16) //nolint:gomnd + val := make([]uint64, 8) //nolint:mnd + mask, _ := new(big.Int).SetString("FFFFFFFF", 16) //nolint:mnd val[0] = new(big.Int).And(value, mask).Uint64() - val[1] = new(big.Int).And(new(big.Int).Rsh(value, 32), mask).Uint64() //nolint:gomnd - val[2] = new(big.Int).And(new(big.Int).Rsh(value, 64), mask).Uint64() //nolint:gomnd - val[3] = new(big.Int).And(new(big.Int).Rsh(value, 96), mask).Uint64() //nolint:gomnd - val[4] = new(big.Int).And(new(big.Int).Rsh(value, 128), mask).Uint64() //nolint:gomnd - val[5] = new(big.Int).And(new(big.Int).Rsh(value, 160), mask).Uint64() //nolint:gomnd - val[6] = new(big.Int).And(new(big.Int).Rsh(value, 192), mask).Uint64() //nolint:gomnd - val[7] = new(big.Int).And(new(big.Int).Rsh(value, 224), mask).Uint64() //nolint:gomnd + val[1] = new(big.Int).And(new(big.Int).Rsh(value, 32), mask).Uint64() //nolint:mnd + val[2] = new(big.Int).And(new(big.Int).Rsh(value, 64), mask).Uint64() //nolint:mnd + val[3] = new(big.Int).And(new(big.Int).Rsh(value, 96), mask).Uint64() //nolint:mnd + val[4] = new(big.Int).And(new(big.Int).Rsh(value, 128), mask).Uint64() //nolint:mnd + val[5] = new(big.Int).And(new(big.Int).Rsh(value, 160), mask).Uint64() //nolint:mnd + val[6] = new(big.Int).And(new(big.Int).Rsh(value, 192), mask).Uint64() //nolint:mnd + val[7] = new(big.Int).And(new(big.Int).Rsh(value, 224), mask).Uint64() //nolint:mnd return val } @@ -69,7 +69,7 @@ func StringToh4(str string) ([]uint64, error) { func scalarToh4(s *big.Int) []uint64 { b := ScalarToFilledByteSlice(s) - r := make([]uint64, 4) //nolint:gomnd + r := make([]uint64, 4) //nolint:mnd f, _ := hex.DecodeHex("0xFFFFFFFFFFFFFFFF") fbe := binary.BigEndian.Uint64(f) diff --git a/reorgdetector/reorgdetector.go b/reorgdetector/reorgdetector.go index 22c4693e..7a995bac 100644 --- a/reorgdetector/reorgdetector.go +++ b/reorgdetector/reorgdetector.go @@ -134,7 +134,7 @@ func (rd *ReorgDetector) detectReorgInTrackedList(ctx context.Context) error { headersCacheLock.Lock() currentHeader, ok := headersCache[hdr.Num] if !ok || currentHeader == nil { - if currentHeader, err = rd.client.HeaderByNumber(ctx, big.NewInt(int64(hdr.Num))); err != nil { + if currentHeader, err = rd.client.HeaderByNumber(ctx, new(big.Int).SetUint64(hdr.Num)); err != nil { headersCacheLock.Unlock() return fmt.Errorf("failed to get the header: %w", err) } diff --git a/rpc/bridge.go b/rpc/bridge.go index eb6da780..d2ffddba 100644 --- a/rpc/bridge.go +++ b/rpc/bridge.go @@ -170,12 +170,14 @@ func (b *BridgeEndpoints) ClaimProof( return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get rollup exit proof, error: %s", err)) } var proofLocalExitRoot [32]common.Hash - if networkID == 0 { + switch { + case networkID == 0: proofLocalExitRoot, err = b.bridgeL1.GetProof(ctx, depositCount, info.MainnetExitRoot) if err != nil { return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get local exit proof, error: %s", err)) } - } else if networkID == b.networkID { + + case networkID == b.networkID: localExitRoot, err := b.l1InfoTree.GetLocalExitRoot(ctx, networkID, info.RollupExitRoot) if err != nil { return zeroHex, rpc.NewRPCError( @@ -190,12 +192,14 @@ func (b *BridgeEndpoints) ClaimProof( fmt.Sprintf("failed to get local exit proof, error: %s", err), ) } - } else { + + default: return zeroHex, rpc.NewRPCError( rpc.DefaultErrorCode, fmt.Sprintf("this client does not support network %d", networkID), ) } + return ClaimProof{ ProofLocalExitRoot: proofLocalExitRoot, ProofRollupExitRoot: proofRollupExitRoot, diff --git a/sequencesender/seqsendertypes/types.go b/sequencesender/seqsendertypes/types.go index 21b5834e..5d903dc5 100644 --- a/sequencesender/seqsendertypes/types.go +++ b/sequencesender/seqsendertypes/types.go @@ -5,7 +5,7 @@ import ( ) type Batch interface { - //underlyingType *ethmantypes.Batch + // underlyingType *ethmantypes.Batch DeepCopy() Batch LastCoinbase() common.Address ForcedBatchTimestamp() uint64 @@ -40,7 +40,4 @@ type Sequence interface { String() string // WRITE SetLastVirtualBatchNumber(batchNumber uint64) - //SetL1InfoRoot(hash common.Hash) - //SetOldAccInputHash(hash common.Hash) - //SetAccInputHash(hash common.Hash) } diff --git a/sequencesender/sequencesender.go b/sequencesender/sequencesender.go index 8390c818..5cbef442 100644 --- a/sequencesender/sequencesender.go +++ b/sequencesender/sequencesender.go @@ -425,7 +425,8 @@ func (s *SequenceSender) getResultAndUpdateEthTx(ctx context.Context, txHash com } txResult, err := s.ethTxManager.Result(ctx, txHash) - if errors.Is(err, ethtxmanager.ErrNotFound) { + switch { + case errors.Is(err, ethtxmanager.ErrNotFound): log.Infof("transaction %v does not exist in ethtxmanager. Marking it", txHash) txData.OnMonitor = false // Resend tx @@ -433,10 +434,12 @@ func (s *SequenceSender) getResultAndUpdateEthTx(ctx context.Context, txHash com if errSend == nil { txData.OnMonitor = false } - } else if err != nil { + + case err != nil: log.Errorf("error getting result for tx %v: %v", txHash, err) return err - } else { + + default: s.updateEthTxResult(txData, txResult) } @@ -879,21 +882,22 @@ func (s *SequenceSender) handleReceivedDataStream( } } - // Already virtualized - if l2Block.BatchNumber <= s.fromStreamBatch { + switch { + case l2Block.BatchNumber <= s.fromStreamBatch: + // Already virtualized if l2Block.BatchNumber != s.latestStreamBatch { log.Infof("skipped! batch already virtualized, number %d", l2Block.BatchNumber) } - } else if !s.validStream && l2Block.BatchNumber == s.fromStreamBatch+1 { + + case !s.validStream && l2Block.BatchNumber == s.fromStreamBatch+1: // Initial case after startup s.addNewSequenceBatch(l2Block) s.validStream = true - } else { + + case l2Block.BatchNumber > s.wipBatch: // Handle whether it's only a new block or also a new batch - if l2Block.BatchNumber > s.wipBatch { - // Create new sequential batch - s.addNewSequenceBatch(l2Block) - } + // Create new sequential batch + s.addNewSequenceBatch(l2Block) } // Latest stream batch @@ -1023,28 +1027,27 @@ func (s *SequenceSender) closeSequenceBatch() error { data.batch.SetL2Data(batchL2Data) } else { - log.Fatalf("wipBatch %d not found in sequenceData slice", s.wipBatch) + return fmt.Errorf("pending batch %d not found in sequence data", s.wipBatch) } // Sanity Check if s.cfg.SanityCheckRPCURL != "" { rpcNumberOfBlocks, batchL2Data, err := s.getBatchFromRPC(s.wipBatch) if err != nil { - log.Fatalf("error getting batch number from RPC while trying to perform sanity check: %v", err) + return fmt.Errorf("error getting batch number from RPC while trying to perform sanity check: %w", err) } else { dsNumberOfBlocks := len(s.sequenceData[s.wipBatch].batchRaw.Blocks) if rpcNumberOfBlocks != dsNumberOfBlocks { - log.Fatalf( - "number of blocks in batch %d (%d) does not match the number of blocks in the batch from the RPC (%d)", - s.wipBatch, dsNumberOfBlocks, rpcNumberOfBlocks, - ) + return fmt.Errorf("number of blocks in batch %d (%d) does not match "+ + "the number of blocks in the batch from the RPC (%d)", + s.wipBatch, dsNumberOfBlocks, rpcNumberOfBlocks) } if data.batchType == datastream.BatchType_BATCH_TYPE_REGULAR && common.Bytes2Hex(data.batch.L2Data()) != batchL2Data { log.Infof("datastream batchL2Data: %s", common.Bytes2Hex(data.batch.L2Data())) log.Infof("RPC batchL2Data: %s", batchL2Data) - log.Fatalf("batchL2Data in batch %d does not match batchL2Data from the RPC (%d)", s.wipBatch) + return fmt.Errorf("batchL2Data in batch %d does not match batchL2Data from the RPC ", s.wipBatch) } log.Infof("sanity check of batch %d against RPC successful", s.wipBatch) @@ -1268,7 +1271,7 @@ func (s *SequenceSender) marginTimeElapsed( // Check the time difference between L2 block and currentTime var timeDiff int64 if l2BlockTimestamp >= currentTime { - //L2 block timestamp is above currentTime, negative timeDiff. We do in this way to avoid uint64 overflow + // L2 block timestamp is above currentTime, negative timeDiff. We do in this way to avoid uint64 overflow timeDiff = int64(-(l2BlockTimestamp - currentTime)) } else { timeDiff = int64(currentTime - l2BlockTimestamp) @@ -1277,7 +1280,7 @@ func (s *SequenceSender) marginTimeElapsed( // Check if the time difference is less than timeMargin (L1BlockTimestampMargin) if timeDiff < timeMargin { var waitTime int64 - if timeDiff < 0 { //L2 block timestamp is above currentTime + if timeDiff < 0 { // L2 block timestamp is above currentTime waitTime = timeMargin + (-timeDiff) } else { waitTime = timeMargin - timeDiff diff --git a/sequencesender/txbuilder/banana_base.go b/sequencesender/txbuilder/banana_base.go index 871d02be..ea25fec1 100644 --- a/sequencesender/txbuilder/banana_base.go +++ b/sequencesender/txbuilder/banana_base.go @@ -111,7 +111,7 @@ func (t *TxBuilderBananaBase) NewSequence( return nil, err } - oldAccInputHash := common.BytesToHash(accInputHash[:]) //copy it + oldAccInputHash := common.BytesToHash(accInputHash[:]) // copy it for _, batch := range sequence.Batches { infoRootHash := sequence.L1InfoRoot diff --git a/sequencesender/txbuilder/banana_base_test.go b/sequencesender/txbuilder/banana_base_test.go index 71313191..a948d20d 100644 --- a/sequencesender/txbuilder/banana_base_test.go +++ b/sequencesender/txbuilder/banana_base_test.go @@ -31,7 +31,7 @@ func TestBananaBaseNewSequenceEmpty(t *testing.T) { require.NotNil(t, seq) require.NoError(t, err) // TODO check values - //require.Equal(t, lastAcc, seq.LastAccInputHash()) + // require.Equal(t, lastAcc, seq.LastAccInputHash()) } func TestBananaBaseNewBatchFromL2Block(t *testing.T) { diff --git a/sequencesender/txbuilder/interface.go b/sequencesender/txbuilder/interface.go index 1a16dbba..77ebf00e 100644 --- a/sequencesender/txbuilder/interface.go +++ b/sequencesender/txbuilder/interface.go @@ -22,13 +22,13 @@ type TxBuilder interface { ) (seqsendertypes.Sequence, error) // NewBatchFromL2Block Creates a new batch from the L2 block from a datastream NewBatchFromL2Block(l2Block *datastream.L2Block) seqsendertypes.Batch - //SetCondNewSeq Allows to override the condition to send a new sequence, returns previous one + // SetCondNewSeq Allows to override the condition to send a new sequence, returns previous one SetCondNewSeq(cond CondNewSequence) CondNewSequence String() string } type CondNewSequence interface { - //NewSequenceIfWorthToSend Return nil, nil if the sequence is not worth sending + // NewSequenceIfWorthToSend Return nil, nil if the sequence is not worth sending NewSequenceIfWorthToSend( ctx context.Context, txBuilder TxBuilder, sequenceBatches []seqsendertypes.Batch, l2Coinbase common.Address, ) (seqsendertypes.Sequence, error) diff --git a/sequencesender/txbuilder/validium_cond_num_batches.go b/sequencesender/txbuilder/validium_cond_num_batches.go index 14a0bddf..35173d8e 100644 --- a/sequencesender/txbuilder/validium_cond_num_batches.go +++ b/sequencesender/txbuilder/validium_cond_num_batches.go @@ -23,7 +23,7 @@ func NewConditionalNewSequenceNumBatches(maxBatchesForL1 uint64) *ConditionalNew func (c *ConditionalNewSequenceNumBatches) NewSequenceIfWorthToSend( ctx context.Context, txBuilder TxBuilder, sequenceBatches []seqsendertypes.Batch, l2Coinbase common.Address, ) (seqsendertypes.Sequence, error) { - if c.maxBatchesForL1 != MaxBatchesForL1Disabled && len(sequenceBatches) >= int(c.maxBatchesForL1) { + if c.maxBatchesForL1 != MaxBatchesForL1Disabled && uint64(len(sequenceBatches)) >= c.maxBatchesForL1 { log.Infof( "sequence should be sent to L1, because MaxBatchesForL1 (%d) has been reached", c.maxBatchesForL1, diff --git a/sequencesender/txbuilder/zkevm_cond_max_size.go b/sequencesender/txbuilder/zkevm_cond_max_size.go index dff4636e..66eb9446 100644 --- a/sequencesender/txbuilder/zkevm_cond_max_size.go +++ b/sequencesender/txbuilder/zkevm_cond_max_size.go @@ -61,7 +61,6 @@ func (c *ConditionalNewSequenceMaxSize) NewSequenceIfWorthToSend( sequenceBatches, err = handleEstimateGasSendSequenceErr(sequence.Batches(), err) if sequenceBatches != nil { // Handling the error gracefully, re-processing the sequence as a sanity check - //sequence, err = s.newSequenceBanana(sequenceBatches, s.cfg.L2Coinbase) sequence, err = txBuilder.NewSequence(ctx, sequenceBatches, l2Coinbase) if err != nil { return nil, err diff --git a/state/encoding_batch_v2_test.go b/state/encoding_batch_v2_test.go index 30b16d23..d263b5c7 100644 --- a/state/encoding_batch_v2_test.go +++ b/state/encoding_batch_v2_test.go @@ -117,8 +117,8 @@ func TestDecodeBatchV2(t *testing.T) { require.NoError(t, err) batchL2Data2, err := hex.DecodeString(codedL2Block2) require.NoError(t, err) - batch := append(batchL2Data, batchL2Data2...) - decodedBatch, err := DecodeBatchV2(batch) + batchL2Data = append(batchL2Data, batchL2Data2...) + decodedBatch, err := DecodeBatchV2(batchL2Data) require.NoError(t, err) require.Equal(t, 2, len(decodedBatch.Blocks)) require.Equal(t, uint32(0x73e6af6f), decodedBatch.Blocks[0].DeltaTimestamp) diff --git a/state/helper.go b/state/helper.go index aeedb8fe..7f2b64be 100644 --- a/state/helper.go +++ b/state/helper.go @@ -63,7 +63,7 @@ func prepareRLPTxData(tx *types.Transaction) ([]byte, error) { return nil, err } - newV := new(big.Int).Add(big.NewInt(ether155V), big.NewInt(int64(sign))) + newV := new(big.Int).Add(big.NewInt(ether155V), new(big.Int).SetUint64(sign)) newRPadded := fmt.Sprintf("%064s", r.Text(hex.Base)) newSPadded := fmt.Sprintf("%064s", s.Text(hex.Base)) newVPadded := fmt.Sprintf("%02s", newV.Text(hex.Base)) diff --git a/state/pgstatestorage/proof.go b/state/pgstatestorage/proof.go index a5ae6331..fa32fc99 100644 --- a/state/pgstatestorage/proof.go +++ b/state/pgstatestorage/proof.go @@ -257,9 +257,9 @@ func toPostgresInterval(duration string) (string, error) { return "", state.ErrUnsupportedDuration } - isMoreThanOne := duration[0] != '1' || len(duration) > 2 //nolint:gomnd + isMoreThanOne := duration[0] != '1' || len(duration) > 2 //nolint:mnd if isMoreThanOne { - pgUnit = pgUnit + "s" + pgUnit += "s" } return fmt.Sprintf("%s %s", duration[:len(duration)-1], pgUnit), nil diff --git a/sync/evmdownloader.go b/sync/evmdownloader.go index 1e70d12f..c9c4e661 100644 --- a/sync/evmdownloader.go +++ b/sync/evmdownloader.go @@ -246,7 +246,7 @@ func (d *EVMDownloaderImplementation) GetLogs(ctx context.Context, fromBlock, to func (d *EVMDownloaderImplementation) GetBlockHeader(ctx context.Context, blockNum uint64) EVMBlockHeader { attempts := 0 for { - header, err := d.ethClient.HeaderByNumber(ctx, big.NewInt(int64(blockNum))) + header, err := d.ethClient.HeaderByNumber(ctx, new(big.Int).SetUint64(blockNum)) if err != nil { attempts++ d.log.Errorf("error getting block header for block %d, err: %v", blockNum, err) diff --git a/test/helpers/aggoracle_e2e.go b/test/helpers/aggoracle_e2e.go index 311ba189..5f0f7b85 100644 --- a/test/helpers/aggoracle_e2e.go +++ b/test/helpers/aggoracle_e2e.go @@ -59,7 +59,7 @@ func SetupAggoracleWithEVMChain(t *testing.T) *AggoracleWithEVMChainEnv { ctx := context.Background() l1Client, syncer, gerL1Contract, gerL1Addr, bridgeL1Contract, bridgeL1Addr, authL1, rd := CommonSetup(t) sender, l2Client, gerL2Contract, gerL2Addr, bridgeL2Contract, bridgeL2Addr, authL2, ethTxManMockL2 := EVMSetup(t) - oracle, err := aggoracle.New(sender, l1Client.Client(), syncer, etherman.LatestBlock, time.Millisecond*20) //nolint:gomnd + oracle, err := aggoracle.New(sender, l1Client.Client(), syncer, etherman.LatestBlock, time.Millisecond*20) //nolint:mnd require.NoError(t, err) go oracle.Start(ctx) @@ -112,7 +112,7 @@ func CommonSetup(t *testing.T) ( require.NoError(t, err) // Syncer dbPathSyncer := t.TempDir() - syncer, err := l1infotreesync.New(ctx, dbPathSyncer, gerL1Addr, common.Address{}, 10, etherman.LatestBlock, reorg, l1Client.Client(), time.Millisecond, 0, 100*time.Millisecond, 3) //nolint:gomnd + syncer, err := l1infotreesync.New(ctx, dbPathSyncer, gerL1Addr, common.Address{}, 10, etherman.LatestBlock, reorg, l1Client.Client(), time.Millisecond, 0, 100*time.Millisecond, 3) //nolint:mnd require.NoError(t, err) go syncer.Start(ctx) @@ -138,7 +138,7 @@ func EVMSetup(t *testing.T) ( l2Client, gerL2Addr, gerL2Sc, bridgeL2Addr, bridgeL2Sc, err := newSimulatedEVMAggSovereignChain(authL2) require.NoError(t, err) ethTxManMock := NewEthTxManMock(t, l2Client, authL2) - sender, err := chaingersender.NewEVMChainGERSender(gerL2Addr, authL2.From, l2Client.Client(), ethTxManMock, 0, time.Millisecond*50) //nolint:gomnd + sender, err := chaingersender.NewEVMChainGERSender(gerL2Addr, authL2.From, l2Client.Client(), ethTxManMock, 0, time.Millisecond*50) //nolint:mnd require.NoError(t, err) return sender, l2Client, gerL2Sc, gerL2Addr, bridgeL2Sc, bridgeL2Addr, authL2, ethTxManMock @@ -164,7 +164,7 @@ func newSimulatedL1(auth *bind.TransactOpts) ( return nil, common.Address{}, nil, common.Address{}, nil, fmt.Errorf("failed to create transactor: %w", err) } - balance, _ := new(big.Int).SetString(initialBalance, 10) //nolint:gomnd + balance, _ := new(big.Int).SetString(initialBalance, 10) //nolint:mnd address := auth.From genesisAlloc := map[common.Address]types.Account{ address: { @@ -273,7 +273,7 @@ func newSimulatedEVMAggSovereignChain(auth *bind.TransactOpts) ( return nil, common.Address{}, nil, common.Address{}, nil, fmt.Errorf("failed to create transactor: %w", err) } - balance, _ := new(big.Int).SetString(initialBalance, 10) //nolint:gomnd + balance, _ := new(big.Int).SetString(initialBalance, 10) //nolint:mnd address := auth.From precalculatedBridgeAddr := crypto.CreateAddress(authDeployer.From, 1) diff --git a/tree/appendonlytree.go b/tree/appendonlytree.go index 67a1a8f8..a283f63e 100644 --- a/tree/appendonlytree.go +++ b/tree/appendonlytree.go @@ -112,6 +112,7 @@ func (t *AppendOnlyTree) GetIndexByRoot(ctx context.Context, root common.Hash) ( return 0, err } defer tx.Rollback() + index, err := t.getIndexByRoot(tx, root) return uint32(index), err } diff --git a/tree/testvectors/types.go b/tree/testvectors/types.go index af3c7519..27bc1abb 100644 --- a/tree/testvectors/types.go +++ b/tree/testvectors/types.go @@ -21,9 +21,9 @@ type DepositVectorRaw struct { } func (d *DepositVectorRaw) Hash() common.Hash { - origNet := make([]byte, 4) //nolint:gomnd + origNet := make([]byte, 4) //nolint:mnd binary.BigEndian.PutUint32(origNet, d.OriginNetwork) - destNet := make([]byte, 4) //nolint:gomnd + destNet := make([]byte, 4) //nolint:mnd binary.BigEndian.PutUint32(destNet, d.DestinationNetwork) metaHash := keccak256.Hash(common.FromHex(d.Metadata))