Browse Source

Merge pull request #89 from hermeznetwork/feature/golint

Add lint checks: gofmt, goimports, golint
feature/sql-semaphore1
Eduard S 4 years ago
committed by GitHub
parent
commit
ddb5604629
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 98 additions and 51 deletions
  1. +1
    -1
      .github/workflows/lint.yml
  2. +1
    -0
      common/account.go
  3. +1
    -0
      common/exittree.go
  4. +6
    -3
      common/fee.go
  5. +1
    -0
      common/l1tx.go
  6. +1
    -0
      common/l2tx.go
  7. +3
    -0
      common/pooll2tx.go
  8. +4
    -0
      common/scvars.go
  9. +4
    -5
      common/zk.go
  10. +2
    -1
      coordinator/batch.go
  11. +5
    -4
      coordinator/coordinator.go
  12. +1
    -1
      coordinator/coordinator_test.go
  13. +6
    -0
      coordinator/proofpool.go
  14. +13
    -5
      db/statedb/statedb.go
  15. +9
    -5
      eth/client.go
  16. +2
    -2
      log/log.go
  17. +16
    -9
      test/lang.go
  18. +1
    -1
      test/sets.go
  19. +3
    -0
      test/txs.go
  20. +6
    -2
      utils/utils.go
  21. +12
    -12
      utils/utils_test.go

+ 1
- 1
.github/workflows/lint.yml

@ -13,4 +13,4 @@ jobs:
- name: Lint - name: Lint
run: | run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.30.0 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

+ 1
- 0
common/account.go

@ -13,6 +13,7 @@ import (
) )
const ( const (
// NLEAFELEMS is the number of elements for a leaf
NLEAFELEMS = 4 NLEAFELEMS = 4
// maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1) // maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
maxNonceValue = 0xffffffffff maxNonceValue = 0xffffffffff

+ 1
- 0
common/exittree.go

@ -6,6 +6,7 @@ import (
"github.com/iden3/go-merkletree" "github.com/iden3/go-merkletree"
) )
// ExitInfo represents the ExitTree Leaf data
type ExitInfo struct { type ExitInfo struct {
AccountIdx Idx AccountIdx Idx
MerkleProof *merkletree.CircomVerifierProof MerkleProof *merkletree.CircomVerifierProof

+ 6
- 3
common/fee.go

@ -4,8 +4,9 @@ package common
// to incentivaise the materialization of it // to incentivaise the materialization of it
type Fee float64 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 { type RecommendedFee struct {
ExistingAccount float64 ExistingAccount float64
CreatesAccount float64 CreatesAccount float64
@ -15,7 +16,9 @@ type RecommendedFee struct {
// FeeSelector is used to select a percentage from the FeePlan. // FeeSelector is used to select a percentage from the FeePlan.
type FeeSelector uint8 type FeeSelector uint8
// MAXFEEPLAN is the maximum value of the FeePlan
const MAXFEEPLAN = 256 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{} var FeePlan = [MAXFEEPLAN]float64{}

+ 1
- 0
common/l1tx.go

@ -25,6 +25,7 @@ type L1Tx struct {
Type TxType `meddler:"tx_type"` Type TxType `meddler:"tx_type"`
} }
// Tx returns a *Tx from the L1Tx
func (tx *L1Tx) Tx() *Tx { func (tx *L1Tx) Tx() *Tx {
return &Tx{ return &Tx{
TxID: tx.TxID, TxID: tx.TxID,

+ 1
- 0
common/l2tx.go

@ -18,6 +18,7 @@ type L2Tx struct {
Type TxType `meddler:"tx_type"` Type TxType `meddler:"tx_type"`
} }
// Tx returns a *Tx from the L2Tx
func (tx *L2Tx) Tx() *Tx { func (tx *L2Tx) Tx() *Tx {
return &Tx{ return &Tx{
TxID: tx.TxID, TxID: tx.TxID,

+ 3
- 0
common/pooll2tx.go

@ -172,6 +172,7 @@ func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
return pk.VerifyPoseidon(h, tx.Signature) return pk.VerifyPoseidon(h, tx.Signature)
} }
// L2Tx returns a *L2Tx from the PoolL2Tx
func (tx *PoolL2Tx) L2Tx() *L2Tx { func (tx *PoolL2Tx) L2Tx() *L2Tx {
return &L2Tx{ return &L2Tx{
TxID: tx.TxID, TxID: tx.TxID,
@ -185,6 +186,7 @@ func (tx *PoolL2Tx) L2Tx() *L2Tx {
} }
} }
// Tx returns a *Tx from the PoolL2Tx
func (tx *PoolL2Tx) Tx() *Tx { func (tx *PoolL2Tx) Tx() *Tx {
return &Tx{ return &Tx{
TxID: tx.TxID, 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 { func PoolL2TxsToL2Txs(txs []*PoolL2Tx) []*L2Tx {
var r []*L2Tx var r []*L2Tx
for _, tx := range txs { for _, tx := range txs {

+ 4
- 0
common/scvars.go

@ -6,6 +6,7 @@ import (
eth "github.com/ethereum/go-ethereum/common" eth "github.com/ethereum/go-ethereum/common"
) )
// RollupVars contain the Rollup smart contract variables
type RollupVars struct { type RollupVars struct {
EthBlockNum uint64 EthBlockNum uint64
ForgeL1Timeout *big.Int ForgeL1Timeout *big.Int
@ -15,6 +16,7 @@ type RollupVars struct {
Governance eth.Address Governance eth.Address
} }
// AuctionVars contain the Auction smart contract variables
type AuctionVars struct { type AuctionVars struct {
EthBlockNum uint64 EthBlockNum uint64
SlotDeadline uint SlotDeadline uint
@ -28,8 +30,10 @@ type AuctionVars struct {
AllocationRatio AllocationRatio AllocationRatio AllocationRatio
} }
// MinBidSlots TODO
type MinBidSlots [6]uint type MinBidSlots [6]uint
// AllocationRatio TODO
type AllocationRatio struct { type AllocationRatio struct {
Donation uint Donation uint
Burn uint Burn uint

+ 4
- 5
common/zk.go

@ -4,6 +4,8 @@ import (
"math/big" "math/big"
) )
// ZKInputs represents the inputs that will be used to generate the zkSNARK
// proof
type ZKInputs struct { type ZKInputs struct {
InitialIdx uint64 InitialIdx uint64
OldStRoot Hash OldStRoot Hash
@ -19,7 +21,7 @@ type ZKInputs struct {
TxData []*big.Int TxData []*big.Int
FromIdx []uint64 FromIdx []uint64
ToIdX []uint64
ToIdX []uint64 //nolint:golint
ToAx []*big.Int ToAx []*big.Int
ToAy []*big.Int ToAy []*big.Int
ToEthAddr []*big.Int ToEthAddr []*big.Int
@ -55,10 +57,7 @@ type ZKInputs struct {
OldValue2 []*big.Int OldValue2 []*big.Int
} }
// CallDataForge TBD
type CallDataForge struct { type CallDataForge struct {
// TBD // TBD
} }
type ExitTreeLeaf struct {
// TBD
}

+ 2
- 1
coordinator/batch.go

@ -4,8 +4,8 @@ import (
"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/common"
) )
// Proof TBD this type will be got from the proof server
type Proof struct { type Proof struct {
// TBD this type will be got from the proof server
} }
// BatchInfo contans the Batch information // BatchInfo contans the Batch information
@ -58,6 +58,7 @@ type BatchQueue struct {
queue []*BatchInfo queue []*BatchInfo
} }
// NewBatchQueue returns a new *BatchQueue
func NewBatchQueue() *BatchQueue { func NewBatchQueue() *BatchQueue {
return &BatchQueue{ return &BatchQueue{
queue: []*BatchInfo{}, queue: []*BatchInfo{},

+ 5
- 4
coordinator/coordinator.go

@ -14,8 +14,8 @@ import (
"github.com/iden3/go-merkletree/db/memory" "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 ForgerAddress ethCommon.Address
LoopInterval time.Duration LoopInterval time.Duration
} }
@ -29,7 +29,7 @@ type Coordinator struct {
forging bool forging bool
isForgeSeq bool // WIP just for testing while implementing isForgeSeq bool // WIP just for testing while implementing
config CoordinatorConfig
config Config
batchNum common.BatchNum batchNum common.BatchNum
batchQueue *BatchQueue batchQueue *BatchQueue
@ -45,7 +45,7 @@ type Coordinator struct {
} }
// NewCoordinator creates a new Coordinator // NewCoordinator creates a new Coordinator
func NewCoordinator(conf CoordinatorConfig,
func NewCoordinator(conf Config,
hdb *historydb.HistoryDB, hdb *historydb.HistoryDB,
txsel *txselector.TxSelector, txsel *txselector.TxSelector,
bb *batchbuilder.BatchBuilder, bb *batchbuilder.BatchBuilder,
@ -61,6 +61,7 @@ func NewCoordinator(conf CoordinatorConfig,
return &c return &c
} }
// Stop stops the Coordinator
func (c *Coordinator) Stop() { func (c *Coordinator) Stop() {
log.Info("Stopping Coordinator") log.Info("Stopping Coordinator")
c.stopch <- true c.stopch <- true

+ 1
- 1
coordinator/coordinator_test.go

@ -46,7 +46,7 @@ func newTestModules(t *testing.T) (*txselector.TxSelector, *batchbuilder.BatchBu
func TestCoordinator(t *testing.T) { func TestCoordinator(t *testing.T) {
txsel, bb := newTestModules(t) txsel, bb := newTestModules(t)
conf := CoordinatorConfig{
conf := Config{
LoopInterval: 100 * time.Millisecond, LoopInterval: 100 * time.Millisecond,
} }
hdb := &historydb.HistoryDB{} hdb := &historydb.HistoryDB{}

+ 6
- 0
coordinator/proofpool.go

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

+ 13
- 5
db/statedb/statedb.go

@ -13,10 +13,12 @@ import (
"github.com/iden3/go-merkletree/db/pebble" "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") 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") var ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
// KEYCURRENTBATCH is used as key in the db to store the current BatchNum // 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 // PATHSTATEDB defines the subpath of the StateDB
const PATHSTATEDB = "/statedb" const PATHSTATEDB = "/statedb"
// PATHBATCHNUM defines the subpath of the Batch Checkpoint in the subpath of
// the StateDB
const PATHBATCHNUM = "/BatchNum" const PATHBATCHNUM = "/BatchNum"
// PATHCURRENT defines the subpath of the current Batch in the subpath of the
// StateDB
const PATHCURRENT = "/current" const PATHCURRENT = "/current"
// StateDB represents the StateDB object // StateDB represents the StateDB object
@ -159,7 +167,7 @@ func (s *StateDB) Reset(batchNum common.BatchNum) error {
return err return err
} }
// copy 'BatchNumX' to 'current' // copy 'BatchNumX' to 'current'
cmd := exec.Command("cp", "-r", checkpointPath, currentPath)
cmd := exec.Command("cp", "-r", checkpointPath, currentPath) //nolint:gosec
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
return err return err
@ -354,13 +362,13 @@ func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) er
return err return err
} }
// copy synchronizer'BatchNumX' to 'current' // copy synchronizer'BatchNumX' to 'current'
cmd := exec.Command("cp", "-r", synchronizerCheckpointPath, currentPath)
cmd := exec.Command("cp", "-r", synchronizerCheckpointPath, currentPath) //nolint:gosec
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
return err return err
} }
// copy synchronizer-'BatchNumX' to 'BatchNumX' // copy synchronizer-'BatchNumX' to 'BatchNumX'
cmd = exec.Command("cp", "-r", synchronizerCheckpointPath, checkpointPath)
cmd = exec.Command("cp", "-r", synchronizerCheckpointPath, checkpointPath) //nolint:gosec
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
return err return err

+ 9
- 5
eth/client.go

@ -17,10 +17,11 @@ import (
) )
var ( 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") 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") 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") ErrReceiptNotReceived = fmt.Errorf("receipt not available")
) )
@ -36,6 +37,7 @@ const (
defaultIntervalReceiptLoop = 200 defaultIntervalReceiptLoop = 200
) )
// Config defines the configuration parameters of the Client
type Config struct { type Config struct {
CallGasLimit uint64 CallGasLimit uint64
DeployGasLimit uint64 DeployGasLimit uint64
@ -115,6 +117,7 @@ func (c *Client) CallAuth(gasLimit uint64,
return tx, err return tx, err
} }
// ContractData contains the contract data
type ContractData struct { type ContractData struct {
Address ethCommon.Address Address ethCommon.Address
Tx *types.Transaction 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 // WaitReceipt will block until a transaction is confirmed. Internally it
// polls the state every 200 milliseconds. // polls the state every 200 milliseconds.
func (c *Client) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) { 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 // 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) { func (c *Client) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second) ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
defer cancel() 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 err error
var receipt *types.Receipt var receipt *types.Receipt
@ -233,6 +236,7 @@ func (c *Client) BlockByNumber(ctx context.Context, number *big.Int) (*common.Bl
return b, nil 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) { func (c *Client) ForgeCall(callData *common.CallDataForge) ([]byte, error) {
// TODO this depends on the smart contracts, once are ready this will be updated // TODO this depends on the smart contracts, once are ready this will be updated
return nil, nil return nil, nil

+ 2
- 2
log/log.go

@ -62,7 +62,7 @@ func Init(levelStr, errorsPath string) {
if errorsPath != "" { if errorsPath != "" {
log.Infof("file where errors will be written: %s", 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 { if err != nil {
panic(err) panic(err)
} }
@ -76,7 +76,7 @@ func writeToErrorsFile(msg string) {
return return
} }
//nolint:errcheck //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 // Debug calls log.Debug

+ 16
- 9
test/lang.go

@ -13,10 +13,14 @@ import (
var eof = rune(0) var eof = rune(0)
var errof = fmt.Errorf("eof in parseline") 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" var TypeNewBatch common.TxType = "TxTypeNewBatch"
//nolint
const ( const (
ILLEGAL token = iota ILLEGAL token = iota
WS WS
@ -25,6 +29,7 @@ const (
IDENT // val IDENT // val
) )
// Instruction is the data structure that represents one line of code
type Instruction struct { type Instruction struct {
Literal string Literal string
From string From string
@ -35,6 +40,7 @@ type Instruction struct {
Type common.TxType // D: Deposit, T: Transfer, E: ForceExit Type common.TxType // D: Deposit, T: Transfer, E: ForceExit
} }
// Instructions contains the full Set of Instructions representing a full code
type Instructions struct { type Instructions struct {
Instructions []*Instruction Instructions []*Instruction
Accounts []string Accounts []string
@ -64,6 +70,7 @@ func (i Instruction) String() string {
return buf.String() return buf.String()
} }
// Raw returns a string with the raw representation of the Instruction
func (i Instruction) Raw() string { func (i Instruction) Raw() string {
buf := bytes.NewBufferString("") buf := bytes.NewBufferString("")
fmt.Fprintf(buf, "%s", i.From) fmt.Fprintf(buf, "%s", i.From)
@ -104,8 +111,8 @@ func isDigit(ch rune) bool {
return (ch >= '0' && ch <= '9') 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)} return &scanner{r: bufio.NewReader(r)}
} }
@ -196,7 +203,7 @@ type Parser struct {
// NewParser creates a new parser from a io.Reader // NewParser creates a new parser from a io.Reader
func NewParser(r io.Reader) *Parser { func NewParser(r io.Reader) *Parser {
return &Parser{s: NewScanner(r)}
return &Parser{s: newScanner(r)}
} }
func (p *Parser) scan() (tok token, lit string) { func (p *Parser) scan() (tok token, lit string) {
@ -239,10 +246,10 @@ func (p *Parser) parseLine() (*Instruction, error) {
c.Literal += lit c.Literal += lit
if lit == "/" { if lit == "/" {
_, _ = p.s.r.ReadString('\n') _, _ = p.s.r.ReadString('\n')
return nil, ecomment
return nil, errComment
} else if lit == ">" { } else if lit == ">" {
_, _ = p.s.r.ReadString('\n') _, _ = p.s.r.ReadString('\n')
return nil, enewbatch
return nil, errNewBatch
} }
c.From = lit c.From = lit
@ -342,11 +349,11 @@ func (p *Parser) Parse() (Instructions, error) {
if err == errof { if err == errof {
break break
} }
if err == ecomment {
if err == errComment {
i++ i++
continue continue
} }
if err == enewbatch {
if err == errNewBatch {
i++ i++
inst := &Instruction{Type: TypeNewBatch} inst := &Instruction{Type: TypeNewBatch}
instructions.Instructions = append(instructions.Instructions, inst) instructions.Instructions = append(instructions.Instructions, inst)

+ 1
- 1
test/sets.go

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

+ 3
- 0
test/txs.go

@ -15,6 +15,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
// Account contains the data related to a testing account
type Account struct { type Account struct {
BJJ *babyjub.PrivateKey BJJ *babyjub.PrivateKey
Addr ethCommon.Address Addr ethCommon.Address
@ -151,6 +152,8 @@ func GenerateTestTxs(t *testing.T, instructions Instructions) ([][]*common.L1Tx,
return l1Txs, coordinatorL1Txs, poolL2Txs 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) { func GenerateTestTxsFromSet(t *testing.T, set string) ([][]*common.L1Tx, [][]*common.L1Tx, [][]*common.PoolL2Tx) {
parser := NewParser(strings.NewReader(set)) parser := NewParser(strings.NewReader(set))
instructions, err := parser.Parse() instructions, err := parser.Parse()

+ 6
- 2
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 //nolint:gomnd
package utils package utils
@ -23,8 +27,8 @@ func (f16 Float16) Bytes() []byte {
} }
// BigInt converts the Float16 to a *big.Int integer // 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) m := big.NewInt(fl & 0x3FF)
e := big.NewInt(fl >> 11) e := big.NewInt(fl >> 11)

+ 12
- 12
utils/utils_test.go

@ -101,17 +101,17 @@ func BenchmarkFloat16(b *testing.B) {
BigInt *big.Int BigInt *big.Int
} }
testVector := []pair{ 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) { b.Run("floorFix2Float()", func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -120,7 +120,7 @@ func BenchmarkFloat16(b *testing.B) {
}) })
b.Run("NewFloat16()", func(b *testing.B) { b.Run("NewFloat16()", func(b *testing.B) {
for i := 0; i < b.N; i++ { 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) { b.Run("Float16.BigInt()", func(b *testing.B) {

Loading…
Cancel
Save