arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
Merge pull request #89 from hermeznetwork/feature/golint

Add lint checks: gofmt, goimports, golint
Eduard S eduard@iden3.io
Mon, 31 Aug 2020 13:26:33 +0200
commit

ddb5604629f8657d55fc45a0c794522e3f26be94

parent

3bd91ec7364b21bfb345b70abd63a8048de1ac22

M .github/workflows/lint.yml → .github/workflows/lint.yml

@@ -13,4 +13,4 @@ uses: actions/checkout@v2

- name: Lint run: | curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.30.0 - $(go env GOPATH)/bin/golangci-lint run --timeout=5m -E whitespace -E gosec -E gci -E misspell -E gomnd --max-same-issues 0 + $(go env GOPATH)/bin/golangci-lint run --timeout=5m -E whitespace -E gosec -E gci -E misspell -E gomnd -E gofmt -E goimports -E golint --exclude-use-default=false --max-same-issues 0
M common/account.go → common/account.go

@@ -13,6 +13,7 @@ cryptoUtils "github.com/iden3/go-iden3-crypto/utils"

) const ( + // NLEAFELEMS is the number of elements for a leaf NLEAFELEMS = 4 // maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1) maxNonceValue = 0xffffffffff
M common/exittree.go → common/exittree.go

@@ -6,6 +6,7 @@

"github.com/iden3/go-merkletree" ) +// ExitInfo represents the ExitTree Leaf data type ExitInfo struct { AccountIdx Idx MerkleProof *merkletree.CircomVerifierProof
M common/fee.go → common/fee.go

@@ -4,8 +4,9 @@ // Fee is a type that represents the percentage of tokens that will be paid in a transaction

// to incentivaise the materialization of it type Fee float64 -// RecommendedFee is the recommended fee to pay in USD per transaction set by the coordinator -// according to the tx type (if the tx requires to create an account and register, only register or he account already esists) +// RecommendedFee is the recommended fee to pay in USD per transaction set by +// the coordinator according to the tx type (if the tx requires to create an +// account and register, only register or he account already esists) type RecommendedFee struct { ExistingAccount float64 CreatesAccount float64

@@ -15,7 +16,9 @@

// FeeSelector is used to select a percentage from the FeePlan. type FeeSelector uint8 +// MAXFEEPLAN is the maximum value of the FeePlan const MAXFEEPLAN = 256 -// FeePlan represents the fee model, a position in the array indicates the percentage of tokens paid in concept of fee for a transaction +// FeePlan represents the fee model, a position in the array indicates the +// percentage of tokens paid in concept of fee for a transaction var FeePlan = [MAXFEEPLAN]float64{}
M common/l1tx.go → common/l1tx.go

@@ -25,6 +25,7 @@ EthBlockNum uint64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue

Type TxType `meddler:"tx_type"` } +// Tx returns a *Tx from the L1Tx func (tx *L1Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID,
M common/l2tx.go → common/l2tx.go

@@ -18,6 +18,7 @@ Nonce Nonce `meddler:"nonce"`

Type TxType `meddler:"tx_type"` } +// Tx returns a *Tx from the L2Tx func (tx *L2Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID,
M common/pooll2tx.go → common/pooll2tx.go

@@ -172,6 +172,7 @@ }

return pk.VerifyPoseidon(h, tx.Signature) } +// L2Tx returns a *L2Tx from the PoolL2Tx func (tx *PoolL2Tx) L2Tx() *L2Tx { return &L2Tx{ TxID: tx.TxID,

@@ -185,6 +186,7 @@ Type: tx.Type,

} } +// Tx returns a *Tx from the PoolL2Tx func (tx *PoolL2Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID,

@@ -197,6 +199,7 @@ Type: tx.Type,

} } +// PoolL2TxsToL2Txs returns an array of []*L2Tx from an array of []*PoolL2Tx func PoolL2TxsToL2Txs(txs []*PoolL2Tx) []*L2Tx { var r []*L2Tx for _, tx := range txs {
M common/scvars.go → common/scvars.go

@@ -6,6 +6,7 @@

eth "github.com/ethereum/go-ethereum/common" ) +// RollupVars contain the Rollup smart contract variables type RollupVars struct { EthBlockNum uint64 ForgeL1Timeout *big.Int

@@ -15,6 +16,7 @@ TokensHEZ eth.Address

Governance eth.Address } +// AuctionVars contain the Auction smart contract variables type AuctionVars struct { EthBlockNum uint64 SlotDeadline uint

@@ -28,8 +30,10 @@ GovernanceAddress eth.Address

AllocationRatio AllocationRatio } +// MinBidSlots TODO type MinBidSlots [6]uint +// AllocationRatio TODO type AllocationRatio struct { Donation uint Burn uint
M common/zk.go → common/zk.go

@@ -4,6 +4,8 @@ import (

"math/big" ) +// ZKInputs represents the inputs that will be used to generate the zkSNARK +// proof type ZKInputs struct { InitialIdx uint64 OldStRoot Hash

@@ -19,7 +21,7 @@ ImOnChain []*big.Int

TxData []*big.Int FromIdx []uint64 - ToIdX []uint64 + ToIdX []uint64 //nolint:golint ToAx []*big.Int ToAy []*big.Int ToEthAddr []*big.Int

@@ -55,10 +57,7 @@ OldKey2 []*big.Int

OldValue2 []*big.Int } +// CallDataForge TBD type CallDataForge struct { // TBD } - -type ExitTreeLeaf struct { - // TBD -}
M coordinator/batch.go → coordinator/batch.go

@@ -4,8 +4,8 @@ import (

"github.com/hermeznetwork/hermez-node/common" ) +// Proof TBD this type will be got from the proof server type Proof struct { - // TBD this type will be got from the proof server } // BatchInfo contans the Batch information

@@ -58,6 +58,7 @@ type BatchQueue struct {

queue []*BatchInfo } +// NewBatchQueue returns a new *BatchQueue func NewBatchQueue() *BatchQueue { return &BatchQueue{ queue: []*BatchInfo{},
M coordinator/coordinator.go → coordinator/coordinator.go

@@ -14,8 +14,8 @@ kvdb "github.com/iden3/go-merkletree/db"

"github.com/iden3/go-merkletree/db/memory" ) -// CoordinatorConfig contains the Coordinator configuration -type CoordinatorConfig struct { +// Config contains the Coordinator configuration +type Config struct { ForgerAddress ethCommon.Address LoopInterval time.Duration }

@@ -29,7 +29,7 @@

forging bool isForgeSeq bool // WIP just for testing while implementing - config CoordinatorConfig + config Config batchNum common.BatchNum batchQueue *BatchQueue

@@ -45,7 +45,7 @@ ethTxStore kvdb.Storage

} // NewCoordinator creates a new Coordinator -func NewCoordinator(conf CoordinatorConfig, +func NewCoordinator(conf Config, hdb *historydb.HistoryDB, txsel *txselector.TxSelector, bb *batchbuilder.BatchBuilder,

@@ -61,6 +61,7 @@ }

return &c } +// Stop stops the Coordinator func (c *Coordinator) Stop() { log.Info("Stopping Coordinator") c.stopch <- true
M coordinator/coordinator_test.go → coordinator/coordinator_test.go

@@ -46,7 +46,7 @@

func TestCoordinator(t *testing.T) { txsel, bb := newTestModules(t) - conf := CoordinatorConfig{ + conf := Config{ LoopInterval: 100 * time.Millisecond, } hdb := &historydb.HistoryDB{}
M coordinator/proofpool.go → coordinator/proofpool.go

@@ -2,23 +2,29 @@ package coordinator

import "github.com/hermeznetwork/hermez-node/common" +// ServerProofInfo contains the data related to a ServerProof type ServerProofInfo struct { // TODO Available bool } +// CalculateProof sends the *common.ZKInputs to the ServerProof to compute the +// Proof func (p *ServerProofInfo) CalculateProof(zkInputs *common.ZKInputs) error { return nil } +// GetProof retreives the Proof from the ServerProof func (p *ServerProofInfo) GetProof() (*Proof, error) { return nil, nil } +// ServerProofPool contains the multiple ServerProofInfo type ServerProofPool struct { // pool []ServerProofInfo } +// GetNextAvailable returns the available ServerProofInfo func (p *ServerProofPool) GetNextAvailable() (*ServerProofInfo, error) { return nil, nil }
M db/statedb/statedb.go → db/statedb/statedb.go

@@ -13,10 +13,12 @@ "github.com/iden3/go-merkletree/db"

"github.com/iden3/go-merkletree/db/pebble" ) -// ErrStateDBWithoutMT is used when a method that requires a MerkleTree is called in a StateDB that does not have a MerkleTree defined +// ErrStateDBWithoutMT is used when a method that requires a MerkleTree is +// called in a StateDB that does not have a MerkleTree defined var ErrStateDBWithoutMT = errors.New("Can not call method to use MerkleTree in a StateDB without MerkleTree") -// ErrAccountAlreadyExists is used when CreateAccount is called and the Account already exists +// ErrAccountAlreadyExists is used when CreateAccount is called and the Account +// already exists var ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists") // KEYCURRENTBATCH is used as key in the db to store the current BatchNum

@@ -24,7 +26,13 @@ var KEYCURRENTBATCH = []byte("currentbatch")

// PATHSTATEDB defines the subpath of the StateDB const PATHSTATEDB = "/statedb" + +// PATHBATCHNUM defines the subpath of the Batch Checkpoint in the subpath of +// the StateDB const PATHBATCHNUM = "/BatchNum" + +// PATHCURRENT defines the subpath of the current Batch in the subpath of the +// StateDB const PATHCURRENT = "/current" // StateDB represents the StateDB object

@@ -159,7 +167,7 @@ if err != nil {

return err } // copy 'BatchNumX' to 'current' - cmd := exec.Command("cp", "-r", checkpointPath, currentPath) + cmd := exec.Command("cp", "-r", checkpointPath, currentPath) //nolint:gosec err = cmd.Run() if err != nil { return err

@@ -354,13 +362,13 @@ if err != nil {

return err } // copy synchronizer'BatchNumX' to 'current' - cmd := exec.Command("cp", "-r", synchronizerCheckpointPath, currentPath) + cmd := exec.Command("cp", "-r", synchronizerCheckpointPath, currentPath) //nolint:gosec err = cmd.Run() if err != nil { return err } // copy synchronizer-'BatchNumX' to 'BatchNumX' - cmd = exec.Command("cp", "-r", synchronizerCheckpointPath, checkpointPath) + cmd = exec.Command("cp", "-r", synchronizerCheckpointPath, checkpointPath) //nolint:gosec err = cmd.Run() if err != nil { return err
M eth/client.go → eth/client.go

@@ -17,10 +17,11 @@ "github.com/hermeznetwork/hermez-node/log"

) var ( + // ErrAccountNil is used when the calls can not be made because the account is nil ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil") - // ErrReceiptStatusFailed when receiving a failed transaction + // ErrReceiptStatusFailed is used when receiving a failed transaction ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed") - // ErrReceiptNotRecieved when unable to retrieve a transaction + // ErrReceiptNotReceived is used when unable to retrieve a transaction ErrReceiptNotReceived = fmt.Errorf("receipt not available") )

@@ -36,6 +37,7 @@ defaultReceiptTimeout = 60

defaultIntervalReceiptLoop = 200 ) +// Config defines the configuration parameters of the Client type Config struct { CallGasLimit uint64 DeployGasLimit uint64

@@ -115,6 +117,7 @@ }

return tx, err } +// ContractData contains the contract data type ContractData struct { Address ethCommon.Address Tx *types.Transaction

@@ -161,7 +164,7 @@

// WaitReceipt will block until a transaction is confirmed. Internally it // polls the state every 200 milliseconds. func (c *Client) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) { - return c.waitReceipt(tx, context.TODO(), c.ReceiptTimeout) + return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout) } // GetReceipt will check if a transaction is confirmed and return

@@ -170,10 +173,10 @@ // is still pending.

func (c *Client) GetReceipt(tx *types.Transaction) (*types.Receipt, error) { ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second) defer cancel() - return c.waitReceipt(tx, ctx, 0) + return c.waitReceipt(ctx, tx, 0) } -func (c *Client) waitReceipt(tx *types.Transaction, ctx context.Context, timeout time.Duration) (*types.Receipt, error) { +func (c *Client) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) { var err error var receipt *types.Receipt

@@ -233,6 +236,7 @@ }

return b, nil } +// ForgeCall send the *common.CallDataForge to the Forge method of the smart contract func (c *Client) ForgeCall(callData *common.CallDataForge) ([]byte, error) { // TODO this depends on the smart contracts, once are ready this will be updated return nil, nil
M log/log.go → log/log.go

@@ -62,7 +62,7 @@ log = withOptions.Sugar()

if errorsPath != "" { log.Infof("file where errors will be written: %s", errorsPath) - errorsFile, err = os.OpenFile(errorsPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + errorsFile, err = os.OpenFile(errorsPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) //nolint:gosec if err != nil { panic(err) }

@@ -76,7 +76,7 @@ if errorsFile == nil {

return } //nolint:errcheck - errorsFile.WriteString(fmt.Sprintf("%s %s\n", time.Now().Format(time.RFC3339), msg)) + errorsFile.WriteString(fmt.Sprintf("%s %s\n", time.Now().Format(time.RFC3339), msg)) //nolint:gosec } // Debug calls log.Debug
M test/lang.go → test/lang.go

@@ -13,10 +13,14 @@ )

var eof = rune(0) var errof = fmt.Errorf("eof in parseline") -var ecomment = fmt.Errorf("comment in parseline") -var enewbatch = fmt.Errorf("newbatch") +var errComment = fmt.Errorf("comment in parseline") +var errNewBatch = fmt.Errorf("newbatch") + +// TypeNewBatch is used for testing purposes only, and represents the +// common.TxType of a new batch var TypeNewBatch common.TxType = "TxTypeNewBatch" +//nolint const ( ILLEGAL token = iota WS

@@ -25,6 +29,7 @@

IDENT // val ) +// Instruction is the data structure that represents one line of code type Instruction struct { Literal string From string

@@ -35,6 +40,7 @@ TokenID common.TokenID

Type common.TxType // D: Deposit, T: Transfer, E: ForceExit } +// Instructions contains the full Set of Instructions representing a full code type Instructions struct { Instructions []*Instruction Accounts []string

@@ -64,6 +70,7 @@ fmt.Fprintf(buf, "TokenID: %d,\n", i.TokenID)

return buf.String() } +// Raw returns a string with the raw representation of the Instruction func (i Instruction) Raw() string { buf := bytes.NewBufferString("") fmt.Fprintf(buf, "%s", i.From)

@@ -104,8 +111,8 @@ func isDigit(ch rune) bool {

return (ch >= '0' && ch <= '9') } -// NewScanner creates a new scanner with the given io.Reader -func NewScanner(r io.Reader) *scanner { +// newScanner creates a new scanner with the given io.Reader +func newScanner(r io.Reader) *scanner { return &scanner{r: bufio.NewReader(r)} }

@@ -196,7 +203,7 @@ }

// NewParser creates a new parser from a io.Reader func NewParser(r io.Reader) *Parser { - return &Parser{s: NewScanner(r)} + return &Parser{s: newScanner(r)} } func (p *Parser) scan() (tok token, lit string) {

@@ -239,10 +246,10 @@ }

c.Literal += lit if lit == "/" { _, _ = p.s.r.ReadString('\n') - return nil, ecomment + return nil, errComment } else if lit == ">" { _, _ = p.s.r.ReadString('\n') - return nil, enewbatch + return nil, errNewBatch } c.From = lit

@@ -342,11 +349,11 @@ instruction, err := p.parseLine()

if err == errof { break } - if err == ecomment { + if err == errComment { i++ continue } - if err == enewbatch { + if err == errNewBatch { i++ inst := &Instruction{Type: TypeNewBatch} instructions.Instructions = append(instructions.Instructions, inst)
M test/sets.go → test/sets.go

@@ -15,7 +15,7 @@ // or NextBatch:

// > and here the comment // move one batch forward -// Set0 has 3 batches, 29 different accounts, with: +// SetTest0 has 3 batches, 29 different accounts, with: // - 3 TokenIDs // - 29+5+10 L1 txs (deposits & exits) // - 21+53+7 L2 transactions
M test/txs.go → test/txs.go

@@ -15,6 +15,7 @@ "github.com/iden3/go-iden3-crypto/babyjub"

"github.com/stretchr/testify/require" ) +// Account contains the data related to a testing account type Account struct { BJJ *babyjub.PrivateKey Addr ethCommon.Address

@@ -151,6 +152,8 @@

return l1Txs, coordinatorL1Txs, poolL2Txs } +// GenerateTestTxsFromSet reurns the L1 & L2 transactions for a given Set of +// Instructions code func GenerateTestTxsFromSet(t *testing.T, set string) ([][]*common.L1Tx, [][]*common.L1Tx, [][]*common.PoolL2Tx) { parser := NewParser(strings.NewReader(set)) instructions, err := parser.Parse()
M utils/utils.go → utils/utils.go

@@ -1,3 +1,7 @@

+// Package utils provides methods to work with Hermez custom half float +// precision, 16 bits, codification internally called Float16 has been adopted +// to encode large integers. This is done in order to save bits when L2 +// transactions are published. //nolint:gomnd package utils

@@ -23,8 +27,8 @@ return b[:]

} // BigInt converts the Float16 to a *big.Int integer -func (fl16 *Float16) BigInt() *big.Int { - fl := int64(*fl16) +func (f16 *Float16) BigInt() *big.Int { + fl := int64(*f16) m := big.NewInt(fl & 0x3FF) e := big.NewInt(fl >> 11)
M utils/utils_test.go → utils/utils_test.go

@@ -101,17 +101,17 @@ Float16 Float16

BigInt *big.Int } testVector := []pair{ - pair{0x307B, newBigInt("123000000")}, - pair{0x1DC6, newBigInt("454500")}, - pair{0xFFFF, newBigInt("10235000000000000000000000000000000")}, - pair{0x0000, newBigInt("0")}, - pair{0x0400, newBigInt("0")}, - pair{0x0001, newBigInt("1")}, - pair{0x0401, newBigInt("1")}, - pair{0x0800, newBigInt("0")}, - pair{0x0c00, newBigInt("5")}, - pair{0x0801, newBigInt("10")}, - pair{0x0c01, newBigInt("15")}, + {0x307B, newBigInt("123000000")}, + {0x1DC6, newBigInt("454500")}, + {0xFFFF, newBigInt("10235000000000000000000000000000000")}, + {0x0000, newBigInt("0")}, + {0x0400, newBigInt("0")}, + {0x0001, newBigInt("1")}, + {0x0401, newBigInt("1")}, + {0x0800, newBigInt("0")}, + {0x0c00, newBigInt("5")}, + {0x0801, newBigInt("10")}, + {0x0c01, newBigInt("15")}, } b.Run("floorFix2Float()", func(b *testing.B) { for i := 0; i < b.N; i++ {

@@ -120,7 +120,7 @@ }

}) b.Run("NewFloat16()", func(b *testing.B) { for i := 0; i < b.N; i++ { - NewFloat16(testVector[i%len(testVector)].BigInt) //nolint:errcheck + _, _ = NewFloat16(testVector[i%len(testVector)].BigInt) } }) b.Run("Float16.BigInt()", func(b *testing.B) {