From 0c64d39530e6b45ed4d2d80d14da17c218c2b67a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Negovanovi=C4=87?= Date: Fri, 13 Sep 2024 13:49:16 +0200 Subject: [PATCH] fix: linter warnings --- aggregator/aggregator.go | 22 ++++++++++--------- aggregator/profitabilitychecker.go | 12 +++++----- aggregator/prover/prover.go | 14 ++++++------ bridgesync/processor.go | 2 +- config/types/duration_test.go | 2 +- .../datacommittee/datacommittee.go | 7 +++--- etherman/errors.go | 4 ++-- hex/hex.go | 6 ++--- l1infotree/hash.go | 2 +- l1infotree/tree.go | 15 ++++++------- l1infotreesync/processor.go | 18 ++++++++------- log/log.go | 2 +- log/log_test.go | 2 +- merkletree/key.go | 6 ++--- merkletree/split.go | 20 ++++++++--------- reorgdetector/reorgdetector.go | 2 +- sequencesender/seqsendertypes/types.go | 5 +---- sequencesender/sequencesender.go | 22 +++++++++---------- 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.go | 2 +- 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 | 7 +++--- tree/testvectors/types.go | 4 ++-- tree/tree.go | 2 +- 32 files changed, 105 insertions(+), 106 deletions(-) diff --git a/aggregator/aggregator.go b/aggregator/aggregator.go index 0ba92c25..2f5bd147 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 } } @@ -403,7 +403,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 } } } @@ -638,7 +638,7 @@ func (a *Aggregator) handleReceivedDataStream( } l2TxRaw := state.L2TxRaw{ - EfficiencyPercentage: uint8(l2Tx.EffectiveGasPricePercentage), + EfficiencyPercentage: uint8(l2Tx.EffectiveGasPricePercentage), //nolint:gosec TxAlreadyEncoded: false, Tx: tx, } @@ -1765,7 +1765,7 @@ func (a *Aggregator) buildInputProver( forcedBlockhashL1 := common.Hash{} l1InfoRoot := batchToVerify.L1InfoRoot.Bytes() 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 } @@ -1818,7 +1818,7 @@ func (a *Aggregator) buildInputProver( l1InfoTreeData[l2blockRaw.IndexL1InfoTree] = &prover.L1Data{ GlobalExitRoot: l1InfoTreeLeaf.GlobalExitRoot.Bytes(), BlockhashL1: l1InfoTreeLeaf.PreviousBlockHash.Bytes(), - MinTimestamp: uint32(l1InfoTreeLeaf.Timestamp.Unix()), + MinTimestamp: uint32(l1InfoTreeLeaf.Timestamp.Unix()), //nolint:gosec SmtProof: protoProof, } } @@ -1877,10 +1877,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 +1891,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/bridgesync/processor.go b/bridgesync/processor.go index 824d4afd..ea134f97 100644 --- a/bridgesync/processor.go +++ b/bridgesync/processor.go @@ -255,7 +255,7 @@ func (p *processor) Reorg(ctx context.Context, firstReorgedBlock uint64) error { } exitTreeRollback := func() {} if firstDepositCountReorged != -1 { - if exitTreeRollback, err = p.exitTree.Reorg(tx, uint32(firstDepositCountReorged)); err != nil { + if exitTreeRollback, err = p.exitTree.Reorg(tx, uint32(firstDepositCountReorged)); err != nil { //nolint:gosec tx.Rollback() exitTreeRollback() 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..1b473a16 100644 --- a/dataavailability/datacommittee/datacommittee.go +++ b/dataavailability/datacommittee/datacommittee.go @@ -263,14 +263,15 @@ func collectSignatures( var ( msgs = make(signatureMsgs, 0, len(committee.Members)) collectedSignatures uint64 - failedToCollect uint64 + failedToCollect int ) for collectedSignatures < committee.RequiredSignatures { msg := <-ch if msg.err != nil { log.Errorf("error when trying to get signature from %s: %s", msg.addr, msg.err) failedToCollect++ - if len(committee.Members)-int(failedToCollect) < int(committee.RequiredSignatures) { + if len(committee.Members) < failedToCollect || + uint64(len(committee.Members)-failedToCollect) < committee.RequiredSignatures { cancelSignatureCollection() return nil, errors.New("too many members failed to send their signature") @@ -304,7 +305,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..68140bde 100644 --- a/l1infotree/tree.go +++ b/l1infotree/tree.go @@ -21,7 +21,7 @@ func NewL1InfoTree(height uint8, initialLeaves [][32]byte) (*L1InfoTree, error) mt := &L1InfoTree{ zeroHashes: generateZeroHashes(height), height: height, - count: uint32(len(initialLeaves)), + count: uint32(len(initialLeaves)), //nolint:gosec } var err error mt.siblings, mt.currentRoot, err = mt.initSiblings(initialLeaves) @@ -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 } @@ -43,7 +42,7 @@ func (mt *L1InfoTree) ResetL1InfoTree(initialLeaves [][32]byte) (*L1InfoTree, er newMT := &L1InfoTree{ zeroHashes: generateZeroHashes(defaultTreeHeight), height: defaultTreeHeight, - count: uint32(len(initialLeaves)), + count: uint32(len(initialLeaves)), //nolint:gosec } var err error newMT.siblings, newMT.currentRoot, err = newMT.initSiblings(initialLeaves) @@ -109,10 +108,10 @@ func (mt *L1InfoTree) ComputeMerkleProof(gerIndex uint32, leaves [][32]byte) ([] if len(leaves)%2 == 1 { leaves = append(leaves, mt.zeroHashes[h]) } - if index >= uint32(len(leaves)) { + if index >= uint32(len(leaves)) { //nolint:gosec 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 } @@ -178,7 +177,7 @@ func (mt *L1InfoTree) AddLeaf(index uint32, leaf [32]byte) (common.Hash, error) // initSiblings returns the siblings of the node at the given index. // it is used to initialize the siblings array in the beginning. func (mt *L1InfoTree) initSiblings(initialLeaves [][32]byte) ([][32]byte, common.Hash, error) { - if mt.count != uint32(len(initialLeaves)) { + if mt.count != uint32(len(initialLeaves)) { //nolint:gosec return nil, [32]byte{}, fmt.Errorf("error: mt.count and initialLeaves length mismatch") } if mt.count == 0 { diff --git a/l1infotreesync/processor.go b/l1infotreesync/processor.go index a6fa28a1..4953d1d8 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)) @@ -333,7 +333,7 @@ func (p *processor) Reorg(ctx context.Context, firstReorgedBlock uint64) error { } var rollbackL1InfoTree func() if firstReorgedL1InfoTreeIndex != -1 { - rollbackL1InfoTree, err = p.l1InfoTree.Reorg(tx, uint32(firstReorgedL1InfoTreeIndex)) + rollbackL1InfoTree, err = p.l1InfoTree.Reorg(tx, uint32(firstReorgedL1InfoTreeIndex)) //nolint:gosec if err != nil { tx.Rollback() rollbackL1InfoTree() @@ -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/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/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..2f799eb3 100644 --- a/sequencesender/sequencesender.go +++ b/sequencesender/sequencesender.go @@ -831,11 +831,11 @@ func (s *SequenceSender) entryTypeToString(entryType datastream.EntryType) strin func (s *SequenceSender) handleReceivedDataStream( entry *datastreamer.FileEntry, client *datastreamer.StreamClient, server *datastreamer.StreamServer, ) error { - dsType := datastream.EntryType(entry.Type) + dsType := datastream.EntryType(entry.Type) //nolint:gosec var prevEntryType datastream.EntryType if s.prevStreamEntry != nil { - prevEntryType = datastream.EntryType(s.prevStreamEntry.Type) + prevEntryType = datastream.EntryType(s.prevStreamEntry.Type) //nolint:gosec } switch dsType { @@ -888,12 +888,10 @@ func (s *SequenceSender) handleReceivedDataStream( // Initial case after startup s.addNewSequenceBatch(l2Block) s.validStream = true - } else { + } else if 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 @@ -1215,7 +1213,7 @@ func (s *SequenceSender) addNewBlockTx(l2Tx *datastream.Transaction) { } l2TxRaw := state.L2TxRaw{ - EfficiencyPercentage: uint8(l2Tx.EffectiveGasPricePercentage), + EfficiencyPercentage: uint8(l2Tx.EffectiveGasPricePercentage), //nolint:gosec TxAlreadyEncoded: false, Tx: tx, } @@ -1268,16 +1266,16 @@ 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 - timeDiff = int64(-(l2BlockTimestamp - currentTime)) + // L2 block timestamp is above currentTime, negative timeDiff. We do in this way to avoid uint64 overflow + timeDiff = int64(-(l2BlockTimestamp - currentTime)) //nolint:gosec } else { - timeDiff = int64(currentTime - l2BlockTimestamp) + timeDiff = int64(currentTime - l2BlockTimestamp) //nolint:gosec } // 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.go b/state/encoding_batch_v2.go index f058f072..9d7d76c6 100644 --- a/state/encoding_batch_v2.go +++ b/state/encoding_batch_v2.go @@ -344,7 +344,7 @@ func DecodeTxRLP(txsData []byte, offset int) (int, *L2TxRaw, error) { EfficiencyPercentage: efficiencyPercentage, } - return int(endPos), l2Tx, err + return int(endPos), l2Tx, err //nolint:gosec } // It returns the length of data from the param offset 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..d202e8cf 100644 --- a/tree/appendonlytree.go +++ b/tree/appendonlytree.go @@ -112,8 +112,9 @@ 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 + return uint32(index), err //nolint:gosec } // GetLastIndexAndRoot returns the last index and root added to the tree @@ -130,7 +131,7 @@ func (t *AppendOnlyTree) GetLastIndexAndRoot(ctx context.Context) (uint32, commo if i == -1 { return 0, common.Hash{}, ErrNotFound } - return uint32(i), root, nil + return uint32(i), root, nil //nolint:gosec } func (t *AppendOnlyTree) initLastLeftCacheAndLastDepositCount(ctx context.Context) error { @@ -202,7 +203,7 @@ func (t *AppendOnlyTree) Reorg(tx kv.RwTx, firstReorgedIndex uint32) (func(), er return func() {}, nil } // Clean root table - for i := firstReorgedIndex; i <= uint32(t.lastIndex); i++ { + for i := firstReorgedIndex; i <= uint32(t.lastIndex); i++ { //nolint:gosec if err := tx.Delete(t.rootTable, dbCommon.Uint64ToBytes(uint64(i))); err != nil { return func() {}, 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)) diff --git a/tree/tree.go b/tree/tree.go index 5756df10..734540ea 100644 --- a/tree/tree.go +++ b/tree/tree.go @@ -275,7 +275,7 @@ func (t *Tree) getLastIndexAndRootWithTx(tx kv.Tx) (int64, common.Hash, error) { if lastIndexBytes == nil { return -1, common.Hash{}, nil } - return int64(dbCommon.BytesToUint64(lastIndexBytes)), common.Hash(rootBytes), nil + return int64(dbCommon.BytesToUint64(lastIndexBytes)), common.Hash(rootBytes), nil //nolint:gosec } func (t *Tree) GetLeaf(ctx context.Context, index uint32, root common.Hash) (common.Hash, error) {