diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 174e4cf..06539c9 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -13,4 +13,4 @@ jobs: - 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 diff --git a/common/account.go b/common/account.go index e7550bc..193a4ba 100644 --- a/common/account.go +++ b/common/account.go @@ -13,6 +13,7 @@ import ( ) 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 diff --git a/common/exittree.go b/common/exittree.go index 4f6dfcf..e657c73 100644 --- a/common/exittree.go +++ b/common/exittree.go @@ -6,6 +6,7 @@ import ( "github.com/iden3/go-merkletree" ) +// ExitInfo represents the ExitTree Leaf data type ExitInfo struct { AccountIdx Idx MerkleProof *merkletree.CircomVerifierProof diff --git a/common/fee.go b/common/fee.go index 1c9e185..4319636 100644 --- a/common/fee.go +++ b/common/fee.go @@ -4,8 +4,9 @@ package common // 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 @@ type RecommendedFee struct { // 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{} diff --git a/common/l1tx.go b/common/l1tx.go index 49ee142..9c62728 100644 --- a/common/l1tx.go +++ b/common/l1tx.go @@ -25,6 +25,7 @@ type L1Tx struct { Type TxType `meddler:"tx_type"` } +// Tx returns a *Tx from the L1Tx func (tx *L1Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID, diff --git a/common/l2tx.go b/common/l2tx.go index 5690a2c..44a0283 100644 --- a/common/l2tx.go +++ b/common/l2tx.go @@ -18,6 +18,7 @@ type L2Tx struct { Type TxType `meddler:"tx_type"` } +// Tx returns a *Tx from the L2Tx func (tx *L2Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID, diff --git a/common/pooll2tx.go b/common/pooll2tx.go index d2fa9c1..92009b6 100644 --- a/common/pooll2tx.go +++ b/common/pooll2tx.go @@ -172,6 +172,7 @@ func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool { 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 @@ func (tx *PoolL2Tx) L2Tx() *L2Tx { } } +// Tx returns a *Tx from the PoolL2Tx func (tx *PoolL2Tx) Tx() *Tx { return &Tx{ TxID: tx.TxID, @@ -197,6 +199,7 @@ func (tx *PoolL2Tx) Tx() *Tx { } } +// PoolL2TxsToL2Txs returns an array of []*L2Tx from an array of []*PoolL2Tx func PoolL2TxsToL2Txs(txs []*PoolL2Tx) []*L2Tx { var r []*L2Tx for _, tx := range txs { diff --git a/common/scvars.go b/common/scvars.go index 415de48..bf7f537 100644 --- a/common/scvars.go +++ b/common/scvars.go @@ -6,6 +6,7 @@ import ( 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 @@ type RollupVars struct { Governance eth.Address } +// AuctionVars contain the Auction smart contract variables type AuctionVars struct { EthBlockNum uint64 SlotDeadline uint @@ -28,8 +30,10 @@ type AuctionVars struct { AllocationRatio AllocationRatio } +// MinBidSlots TODO type MinBidSlots [6]uint +// AllocationRatio TODO type AllocationRatio struct { Donation uint Burn uint diff --git a/common/zk.go b/common/zk.go index 6eb8237..5e065f9 100644 --- a/common/zk.go +++ b/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 @@ type ZKInputs struct { TxData []*big.Int FromIdx []uint64 - ToIdX []uint64 + ToIdX []uint64 //nolint:golint ToAx []*big.Int ToAy []*big.Int ToEthAddr []*big.Int @@ -55,10 +57,7 @@ type ZKInputs struct { OldValue2 []*big.Int } +// CallDataForge TBD type CallDataForge struct { // TBD } - -type ExitTreeLeaf struct { - // TBD -} diff --git a/coordinator/batch.go b/coordinator/batch.go index 6eacbde..6afd5c1 100644 --- a/coordinator/batch.go +++ b/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{}, diff --git a/coordinator/coordinator.go b/coordinator/coordinator.go index 963f95c..12a86cd 100644 --- a/coordinator/coordinator.go +++ b/coordinator/coordinator.go @@ -14,8 +14,8 @@ import ( "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 @@ type Coordinator struct { forging bool isForgeSeq bool // WIP just for testing while implementing - config CoordinatorConfig + config Config batchNum common.BatchNum batchQueue *BatchQueue @@ -45,7 +45,7 @@ type Coordinator struct { } // 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 @@ func NewCoordinator(conf CoordinatorConfig, return &c } +// Stop stops the Coordinator func (c *Coordinator) Stop() { log.Info("Stopping Coordinator") c.stopch <- true diff --git a/coordinator/coordinator_test.go b/coordinator/coordinator_test.go index 33c9191..e2b2172 100644 --- a/coordinator/coordinator_test.go +++ b/coordinator/coordinator_test.go @@ -46,7 +46,7 @@ func newTestModules(t *testing.T) (*txselector.TxSelector, *batchbuilder.BatchBu func TestCoordinator(t *testing.T) { txsel, bb := newTestModules(t) - conf := CoordinatorConfig{ + conf := Config{ LoopInterval: 100 * time.Millisecond, } hdb := &historydb.HistoryDB{} diff --git a/coordinator/proofpool.go b/coordinator/proofpool.go index 5b70aec..7cb244e 100644 --- a/coordinator/proofpool.go +++ b/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 } diff --git a/db/statedb/statedb.go b/db/statedb/statedb.go index 7f4c231..1cfb27a 100644 --- a/db/statedb/statedb.go +++ b/db/statedb/statedb.go @@ -13,10 +13,12 @@ import ( "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 @@ func (s *StateDB) Reset(batchNum common.BatchNum) error { 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 @@ func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) er 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 diff --git a/eth/client.go b/eth/client.go index 8158a7d..93e8cc2 100644 --- a/eth/client.go +++ b/eth/client.go @@ -17,10 +17,11 @@ import ( ) 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 @@ const ( defaultIntervalReceiptLoop = 200 ) +// Config defines the configuration parameters of the Client type Config struct { CallGasLimit uint64 DeployGasLimit uint64 @@ -115,6 +117,7 @@ func (c *Client) CallAuth(gasLimit uint64, return tx, err } +// ContractData contains the contract data type ContractData struct { Address ethCommon.Address Tx *types.Transaction @@ -161,7 +164,7 @@ func (c *Client) Call(fn func(*ethclient.Client) error) error { // 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 @@ func (c *Client) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) { 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 @@ func (c *Client) BlockByNumber(ctx context.Context, number *big.Int) (*common.Bl 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 diff --git a/log/log.go b/log/log.go index 53fe7e1..0ed8eea 100644 --- a/log/log.go +++ b/log/log.go @@ -62,7 +62,7 @@ func Init(levelStr, errorsPath string) { 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 @@ func writeToErrorsFile(msg string) { 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 diff --git a/test/lang.go b/test/lang.go index d5dace5..5ff92bd 100644 --- a/test/lang.go +++ b/test/lang.go @@ -13,10 +13,14 @@ import ( 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 @@ const ( IDENT // val ) +// Instruction is the data structure that represents one line of code type Instruction struct { Literal string From string @@ -35,6 +40,7 @@ type Instruction struct { 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 @@ func (i Instruction) String() string { 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 @@ type Parser struct { // 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 @@ func (p *Parser) parseLine() (*Instruction, error) { 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 @@ func (p *Parser) Parse() (Instructions, error) { 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) diff --git a/test/sets.go b/test/sets.go index 8521c2d..29ab651 100644 --- a/test/sets.go +++ b/test/sets.go @@ -15,7 +15,7 @@ package test // > 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 diff --git a/test/txs.go b/test/txs.go index 9b4d3bb..c32b552 100644 --- a/test/txs.go +++ b/test/txs.go @@ -15,6 +15,7 @@ import ( "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 @@ func GenerateTestTxs(t *testing.T, instructions Instructions) ([][]*common.L1Tx, 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() diff --git a/utils/utils.go b/utils/utils.go index c7645a2..bb1e638 100644 --- a/utils/utils.go +++ b/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 @@ func (f16 Float16) Bytes() []byte { } // 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) diff --git a/utils/utils_test.go b/utils/utils_test.go index 9670e55..28b2c7b 100644 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -101,17 +101,17 @@ func BenchmarkFloat16(b *testing.B) { 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 @@ func BenchmarkFloat16(b *testing.B) { }) 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) {