Browse Source

Merge pull request #444 from hermeznetwork/feature/txsel-coordidxs-upd

Update TxSelector to return CoordIdxs used & other
feature/sql-semaphore1
Eduard S 3 years ago
committed by GitHub
parent
commit
6c1c1fa80c
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 133 additions and 167 deletions
  1. +5
    -1
      coordinator/coordinator_test.go
  2. +6
    -1
      db/kvdb/kvdb.go
  3. +4
    -3
      db/statedb/statedb.go
  4. +16
    -7
      db/statedb/utils.go
  5. +1
    -3
      db/statedb/utils_test.go
  6. +1
    -1
      go.mod
  7. +2
    -2
      go.sum
  8. +0
    -2
      txprocessor/txprocessor.go
  9. +98
    -127
      txselector/txselector.go
  10. +0
    -20
      txselector/txselector_test.go

+ 5
- 1
coordinator/coordinator_test.go

@ -29,6 +29,7 @@ import (
"github.com/hermeznetwork/hermez-node/txprocessor" "github.com/hermeznetwork/hermez-node/txprocessor"
"github.com/hermeznetwork/hermez-node/txselector" "github.com/hermeznetwork/hermez-node/txselector"
"github.com/hermeznetwork/tracerr" "github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-merkletree" "github.com/iden3/go-merkletree"
"github.com/iden3/go-merkletree/db/pebble" "github.com/iden3/go-merkletree/db/pebble"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -115,9 +116,12 @@ func newTestModules(t *testing.T) modules {
require.NoError(t, err) require.NoError(t, err)
deleteme = append(deleteme, txSelDBPath) deleteme = append(deleteme, txSelDBPath)
var bjj babyjub.PublicKeyComp
err = bjj.UnmarshalText([]byte("c433f7a696b7aa3a5224efb3993baf0ccd9e92eecee0c29a3f6c8208a9e81d9e"))
require.NoError(t, err)
coordAccount := &txselector.CoordAccount{ // TODO TMP coordAccount := &txselector.CoordAccount{ // TODO TMP
Addr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"), Addr: ethCommon.HexToAddress("0xc58d29fA6e86E4FAe04DDcEd660d45BCf3Cb2370"),
BJJ: common.EmptyBJJComp,
BJJ: bjj,
AccountCreationAuth: nil, AccountCreationAuth: nil,
} }
txSelector, err := txselector.NewTxSelector(coordAccount, txSelDBPath, syncStateDB, l2DB) txSelector, err := txselector.NewTxSelector(coordAccount, txSelDBPath, syncStateDB, l2DB)

+ 6
- 1
db/kvdb/kvdb.go

@ -123,7 +123,7 @@ func (kvdb *KVDB) reset(batchNum common.BatchNum, closeCurrent bool) error {
} }
kvdb.db = sto kvdb.db = sto
kvdb.CurrentIdx = 255 kvdb.CurrentIdx = 255
kvdb.CurrentBatch = batchNum
kvdb.CurrentBatch = 0
return nil return nil
} }
@ -210,6 +210,11 @@ func (kvdb *KVDB) ResetFromSynchronizer(batchNum common.BatchNum, synchronizerKV
if err != nil { if err != nil {
return tracerr.Wrap(err) return tracerr.Wrap(err)
} }
// get currentIdx
kvdb.CurrentIdx, err = kvdb.GetCurrentIdx()
if err != nil {
return tracerr.Wrap(err)
}
return nil return nil
} }

+ 4
- 3
db/statedb/statedb.go

@ -22,9 +22,9 @@ var (
// Account already exists // Account already exists
ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists") ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
// ErrToIdxNotFound is used when trying to get the ToIdx from ToEthAddr
// or ToEthAddr&ToBJJ
ErrToIdxNotFound = errors.New("ToIdx can not be found")
// ErrIdxNotFound is used when trying to get the Idx from EthAddr or
// EthAddr&ToBJJ
ErrIdxNotFound = errors.New("Idx can not be found")
// ErrGetIdxNoCase is used when trying to get the Idx from EthAddr & // ErrGetIdxNoCase is used when trying to get the Idx from EthAddr &
// BJJ with not compatible combination // BJJ with not compatible combination
ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey") ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey")
@ -148,6 +148,7 @@ func (s *StateDB) Reset(batchNum common.BatchNum) error {
} }
s.MT = mt s.MT = mt
} }
log.Debugw("Making StateDB Reset", "batch", batchNum)
return nil return nil
} }

+ 16
- 7
db/statedb/utils.go

@ -9,6 +9,7 @@ import (
"github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/log"
"github.com/hermeznetwork/tracerr" "github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-merkletree/db"
) )
func concatEthAddrTokenID(addr ethCommon.Address, tokenID common.TokenID) []byte { func concatEthAddrTokenID(addr ethCommon.Address, tokenID common.TokenID) []byte {
@ -84,7 +85,7 @@ func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID
b, err := s.db.DB().Get(append(PrefixKeyAddr, k...)) b, err := s.db.DB().Get(append(PrefixKeyAddr, k...))
if err != nil { if err != nil {
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d",
ErrToIdxNotFound, addr.Hex(), tokenID))
ErrIdxNotFound, addr.Hex(), tokenID))
} }
idx, err := common.IdxFromBytes(b) idx, err := common.IdxFromBytes(b)
if err != nil { if err != nil {
@ -99,26 +100,34 @@ func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID
// address, it's ignored in the query. If `pk` is nil, it's ignored in the // address, it's ignored in the query. If `pk` is nil, it's ignored in the
// query. Will return common.Idx(0) and error in case that Idx is not found in // query. Will return common.Idx(0) and error in case that Idx is not found in
// the StateDB. // the StateDB.
func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk babyjub.PublicKeyComp, tokenID common.TokenID) (common.Idx, error) {
func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk babyjub.PublicKeyComp,
tokenID common.TokenID) (common.Idx, error) {
if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == common.EmptyBJJComp { if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == common.EmptyBJJComp {
// ToEthAddr // ToEthAddr
// case ToEthAddr!=0 && ToBJJ=0 // case ToEthAddr!=0 && ToBJJ=0
return s.GetIdxByEthAddr(addr, tokenID) return s.GetIdxByEthAddr(addr, tokenID)
} else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk != common.EmptyBJJComp {
} else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) &&
pk != common.EmptyBJJComp {
// case ToEthAddr!=0 && ToBJJ!=0 // case ToEthAddr!=0 && ToBJJ!=0
k := concatEthAddrBJJTokenID(addr, pk, tokenID) k := concatEthAddrBJJTokenID(addr, pk, tokenID)
b, err := s.db.DB().Get(append(PrefixKeyAddrBJJ, k...)) b, err := s.db.DB().Get(append(PrefixKeyAddrBJJ, k...))
if err != nil {
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), pk, tokenID))
if tracerr.Unwrap(err) == db.ErrNotFound {
// return the error (ErrNotFound), so can be traced at upper layers
return common.Idx(0), tracerr.Wrap(ErrIdxNotFound)
} else if err != nil {
return common.Idx(0),
tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrIdxNotFound, addr.Hex(), pk, tokenID))
} }
idx, err := common.IdxFromBytes(b) idx, err := common.IdxFromBytes(b)
if err != nil { if err != nil {
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID))
return common.Idx(0),
tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID))
} }
return idx, nil return idx, nil
} }
// rest of cases (included case ToEthAddr==0) are not possible // rest of cases (included case ToEthAddr==0) are not possible
return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID))
return common.Idx(0),
tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID))
} }
// GetTokenIDsFromIdxs returns a map containing the common.TokenID with its // GetTokenIDsFromIdxs returns a map containing the common.TokenID with its

+ 1
- 3
db/statedb/utils_test.go

@ -1,7 +1,6 @@
package statedb package statedb
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
"testing" "testing"
@ -83,8 +82,7 @@ func TestGetIdx(t *testing.T) {
// expect error when trying to get Idx by addr2 & pk2 // expect error when trying to get Idx by addr2 & pk2
idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk2.Compress(), tokenID0) idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk2.Compress(), tokenID0)
assert.NotNil(t, err) assert.NotNil(t, err)
expectedErr := fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr2.Hex(), pk2, tokenID0)
assert.Equal(t, expectedErr, tracerr.Unwrap(err))
assert.Equal(t, ErrIdxNotFound, tracerr.Unwrap(err))
assert.Equal(t, common.Idx(0), idxR) assert.Equal(t, common.Idx(0), idxR)
// expect error when trying to get Idx by addr with not used TokenID // expect error when trying to get Idx by addr with not used TokenID
_, err = sdb.GetIdxByEthAddr(addr, tokenID1) _, err = sdb.GetIdxByEthAddr(addr, tokenID1)

+ 1
- 1
go.mod

@ -13,7 +13,7 @@ require (
github.com/gobuffalo/packr/v2 v2.8.1 github.com/gobuffalo/packr/v2 v2.8.1
github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29 github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c
github.com/iden3/go-merkletree v0.0.0-20201230093451-4280a9914f51
github.com/iden3/go-merkletree v0.0.0-20201231091158-d73b96c55fbb
github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
github.com/jmoiron/sqlx v1.2.1-0.20200615141059-0794cb1f47ee github.com/jmoiron/sqlx v1.2.1-0.20200615141059-0794cb1f47ee
github.com/joho/godotenv v1.3.0 github.com/joho/godotenv v1.3.0

+ 2
- 2
go.sum

@ -309,8 +309,8 @@ github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3
github.com/iden3/go-iden3-crypto v0.0.6-0.20201218111145-a2015adb2f1b/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg= github.com/iden3/go-iden3-crypto v0.0.6-0.20201218111145-a2015adb2f1b/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c h1:D2u8FFYey6iFXLsqqJZ8R7ch8gZum+/b98whvoSDbyg= github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c h1:D2u8FFYey6iFXLsqqJZ8R7ch8gZum+/b98whvoSDbyg=
github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg= github.com/iden3/go-iden3-crypto v0.0.6-0.20201221160344-58e589b6eb4c/go.mod h1:oBgthFLboAWi9feaBUFy7OxEcyn9vA1khHSL/WwWFyg=
github.com/iden3/go-merkletree v0.0.0-20201230093451-4280a9914f51 h1:EqkLnC+JlOdX3hQnjq0u2JKcMMmmaQcpmG1udG6BTXw=
github.com/iden3/go-merkletree v0.0.0-20201230093451-4280a9914f51/go.mod h1:MCXbnyoFRwt+7aYHtzVSB3sZZcHLjDf7VZZ2Zqrhqrc=
github.com/iden3/go-merkletree v0.0.0-20201231091158-d73b96c55fbb h1:nwjQVe4nYNC6lwF4gAtSdmQ3vMkm0NpJzJVhoWpfSBc=
github.com/iden3/go-merkletree v0.0.0-20201231091158-d73b96c55fbb/go.mod h1:MCXbnyoFRwt+7aYHtzVSB3sZZcHLjDf7VZZ2Zqrhqrc=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY=
github.com/influxdata/influxdb1-client v0.0.0-20190809212627-fc22c7df067e/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/influxdata/influxdb1-client v0.0.0-20190809212627-fc22c7df067e/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=

+ 0
- 2
txprocessor/txprocessor.go

@ -99,8 +99,6 @@ func (tp *TxProcessor) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinat
return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), tp.config.MaxFeeTx)) return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), tp.config.MaxFeeTx))
} }
tp.AccumulatedFees = make(map[common.Idx]*big.Int)
nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs) nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
if nTx > int(tp.config.MaxTx) { if nTx > int(tp.config.MaxTx) {

+ 98
- 127
txselector/txselector.go

@ -17,7 +17,6 @@ import (
"github.com/hermeznetwork/tracerr" "github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-iden3-crypto/babyjub"
"github.com/iden3/go-merkletree/db" "github.com/iden3/go-merkletree/db"
"github.com/iden3/go-merkletree/db/pebble"
) )
const ( const (
@ -67,7 +66,6 @@ type TxSelector struct {
localAccountsDB *statedb.LocalStateDB localAccountsDB *statedb.LocalStateDB
coordAccount *CoordAccount coordAccount *CoordAccount
coordIdxsDB *pebble.Storage
} }
// NewTxSelector returns a *TxSelector // NewTxSelector returns a *TxSelector
@ -79,16 +77,10 @@ func NewTxSelector(coordAccount *CoordAccount, dbpath string,
return nil, tracerr.Wrap(err) return nil, tracerr.Wrap(err)
} }
coordIdxsDB, err := pebble.NewPebbleStorage(dbpath+PathCoordIdxsDB, false)
if err != nil {
return nil, tracerr.Wrap(err)
}
return &TxSelector{ return &TxSelector{
l2db: l2, l2db: l2,
localAccountsDB: localAccountsDB, localAccountsDB: localAccountsDB,
coordAccount: coordAccount, coordAccount: coordAccount,
coordIdxsDB: coordIdxsDB,
}, nil }, nil
} }
@ -107,65 +99,35 @@ func (txsel *TxSelector) Reset(batchNum common.BatchNum) error {
return nil return nil
} }
// AddCoordIdxs stores the given TokenID with the correspondent Idx to the
// CoordIdxsDB
func (txsel *TxSelector) AddCoordIdxs(idxs map[common.TokenID]common.Idx) error {
tx, err := txsel.coordIdxsDB.NewTx()
if err != nil {
return tracerr.Wrap(err)
}
for tokenID, idx := range idxs {
idxBytes, err := idx.Bytes()
if err != nil {
return tracerr.Wrap(err)
}
err = tx.Put(tokenID.Bytes(), idxBytes[:])
if err != nil {
return tracerr.Wrap(err)
}
}
if err := tx.Commit(); err != nil {
return tracerr.Wrap(err)
}
return nil
}
// GetCoordIdxs returns a map with the stored TokenID with the correspondent
// Coordinator Idx
func (txsel *TxSelector) GetCoordIdxs() (map[common.TokenID]common.Idx, error) {
r := make(map[common.TokenID]common.Idx)
err := txsel.coordIdxsDB.Iterate(func(tokenIDBytes []byte, idxBytes []byte) (bool, error) {
idx, err := common.IdxFromBytes(idxBytes)
if err != nil {
return false, tracerr.Wrap(err)
}
tokenID, err := common.TokenIDFromBytes(tokenIDBytes)
if err != nil {
return false, tracerr.Wrap(err)
}
r[tokenID] = idx
return true, nil
})
return r, tracerr.Wrap(err)
func (txsel *TxSelector) getCoordIdx(tokenID common.TokenID) (common.Idx, error) {
return txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr, txsel.coordAccount.BJJ, tokenID)
} }
// coordAccountForTokenID creates a new L1CoordinatorTx to create a new
// Coordinator account for the given TokenID in the case that the account does
// not exist yet in the db, and does not exist a L1CoordinatorTx to creat that
// account in the given array of L1CoordinatorTxs. If a new Coordinator account
// needs to be created, a new L1CoordinatorTx will be returned from this
// function.
//nolint:unused //nolint:unused
func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx, tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
tokenID common.TokenID, positionL1 int) (*common.L1Tx, int, error) {
// check if CoordinatorAccount for TokenID is already pending to create // check if CoordinatorAccount for TokenID is already pending to create
if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID, txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
if checkAlreadyPendingToCreate(l1CoordinatorTxs, tokenID,
txsel.coordAccount.Addr, txsel.coordAccount.BJJ) {
return nil, positionL1, nil return nil, positionL1, nil
} }
_, err := txsel.coordIdxsDB.Get(tokenID.Bytes())
if tracerr.Unwrap(err) == db.ErrNotFound {
// create L1CoordinatorTx to create new CoordAccount for TokenID
_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(txsel.coordAccount.Addr, txsel.coordAccount.BJJ, tokenID)
if tracerr.Unwrap(err) == statedb.ErrIdxNotFound {
// create L1CoordinatorTx to create new CoordAccount for
// TokenID
l1CoordinatorTx := common.L1Tx{ l1CoordinatorTx := common.L1Tx{
Position: positionL1, Position: positionL1,
UserOrigin: false, UserOrigin: false,
FromEthAddr: txsel.coordAccount.Addr, FromEthAddr: txsel.coordAccount.Addr,
FromBJJ: txsel.coordAccount.BJJ, FromBJJ: txsel.coordAccount.BJJ,
TokenID: tokenID, TokenID: tokenID,
Amount: big.NewInt(0),
DepositAmount: big.NewInt(0), DepositAmount: big.NewInt(0),
Type: common.TxTypeCreateAccountDeposit, Type: common.TxTypeCreateAccountDeposit,
} }
@ -191,8 +153,8 @@ func (txsel *TxSelector) coordAccountForTokenID(l1CoordinatorTxs []common.L1Tx,
// included in the next batch. // included in the next batch.
func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig, func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig,
batchNum common.BatchNum) ([]common.Idx, [][]byte, []common.L1Tx, []common.PoolL2Tx, error) { batchNum common.BatchNum) ([]common.Idx, [][]byte, []common.L1Tx, []common.PoolL2Tx, error) {
coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, err := txsel.GetL1L2TxSelection(selectionConfig, batchNum,
[]common.L1Tx{})
coordIdxs, accCreationAuths, _, l1CoordinatorTxs, l2Txs, err :=
txsel.GetL1L2TxSelection(selectionConfig, batchNum, []common.L1Tx{})
return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, tracerr.Wrap(err) return coordIdxs, accCreationAuths, l1CoordinatorTxs, l2Txs, tracerr.Wrap(err)
} }
@ -205,30 +167,15 @@ func (txsel *TxSelector) GetL2TxSelection(selectionConfig *SelectionConfig,
// creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be // creation exists. The L1UserTxs, L1CoordinatorTxs, PoolL2Txs that will be
// included in the next batch. // included in the next batch.
func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig, func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
batchNum common.BatchNum, l1Txs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx, []common.L1Tx,
[]common.PoolL2Tx, error) {
batchNum common.BatchNum, l1Txs []common.L1Tx) ([]common.Idx, [][]byte, []common.L1Tx,
[]common.L1Tx, []common.PoolL2Tx, error) {
// TODO WIP this method uses a 'cherry-pick' of internal calls of the // TODO WIP this method uses a 'cherry-pick' of internal calls of the
// StateDB, a refactor of the StateDB to reorganize it internally is // StateDB, a refactor of the StateDB to reorganize it internally is
// planned once the main functionallities are covered, with that // planned once the main functionallities are covered, with that
// refactor the TxSelector will be updated also // refactor the TxSelector will be updated also
// apply l1-user-tx to localAccountDB
// create new leaves
// update balances
// update nonces
// get existing CoordIdxs
coordIdxsMap, err := txsel.GetCoordIdxs()
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
var coordIdxs []common.Idx
for tokenID := range coordIdxsMap {
coordIdxs = append(coordIdxs, coordIdxsMap[tokenID])
}
// get pending l2-tx from tx-pool // get pending l2-tx from tx-pool
l2TxsRaw, err := txsel.l2db.GetPendingTxs() // (batchID)
l2TxsRaw, err := txsel.l2db.GetPendingTxs()
if err != nil { if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err) return nil, nil, nil, nil, nil, tracerr.Wrap(err)
} }
@ -236,10 +183,6 @@ func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
txselStateDB := txsel.localAccountsDB.StateDB txselStateDB := txsel.localAccountsDB.StateDB
tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig.TxProcessorConfig) tp := txprocessor.NewTxProcessor(txselStateDB, selectionConfig.TxProcessorConfig)
var validTxs txs
var l1CoordinatorTxs []common.L1Tx
positionL1 := len(l1Txs)
// Process L1UserTxs // Process L1UserTxs
for i := 0; i < len(l1Txs); i++ { for i := 0; i < len(l1Txs); i++ {
// assumption: l1usertx are sorted by L1Tx.Position // assumption: l1usertx are sorted by L1Tx.Position
@ -249,12 +192,51 @@ func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
} }
} }
// get last idx from LocalStateDB
// lastIdx := txsel.localStateDB.idx
// update lastIdx with the L1UserTxs (of account creation)
var l1CoordinatorTxs []common.L1Tx
positionL1 := len(l1Txs)
var accAuths [][]byte var accAuths [][]byte
for i := 0; i < len(l2TxsRaw); i++ {
// sort l2TxsRaw (cropping at MaxTx at this point)
l2Txs := txsel.getL2Profitable(l2TxsRaw, selectionConfig.TxProcessorConfig.MaxTx)
// TODO for L1CoordinatorTxs check that always len(l1UserTxs)+len(l1CoordinatorTxs)<MaxL1Txs
// iterate over l2Txs
// - if tx.TokenID does not exist at CoordsIdxDB
// - create new L1CoordinatorTx, for Coordinator to receive the fee of the new TokenID
for i := 0; i < len(l2Txs); i++ {
// check if l2Tx.TokenID does not exist at CoordsIdxDB
_, err = txsel.getCoordIdx(l2Txs[i].TokenID) // TODO already used inside coordAccountForTokenID, this will be removed
if tracerr.Unwrap(err) != db.ErrNotFound {
// if TokenID does not exist yet, create new
// L1CoordinatorTx to create the CoordinatorAccount for
// that TokenID, to receive the fees. Only in the case
// that there does not exist yet a pending
// L1CoordinatorTx to create the account for the
// Coordinator for that TokenID
// TODO TMP
// var newL1CoordTx *common.L1Tx
// newL1CoordTx, positionL1, err =
// txsel.coordAccountForTokenID(l1CoordinatorTxs,
// l2TxsRaw[i].TokenID, positionL1)
// if err != nil {
// return nil, nil, nil, nil, nil, tracerr.Wrap(err)
// }
// if newL1CoordTx != nil {
// l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
// }
} else if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
}
var validTxs txs
// iterate over l2TxsRaw
// - if needed, create new L1CoordinatorTxs for unexisting ToIdx
// - keep used accAuths
// - put the valid txs into validTxs array
for i := 0; i < len(l2Txs); i++ {
// If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB, // If tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB,
// if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the // if so, tx is used. If tx.ToIdx==0, for an L2Tx will be the
// case of TxToEthAddr or TxToBJJ, check if // case of TxToEthAddr or TxToBJJ, check if
@ -263,11 +245,11 @@ func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
// AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx // AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx
// of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a // of CreateAccountAndDeposit is created. If tx.ToIdx==1, is a
// Exit type and is used. // Exit type and is used.
if l2TxsRaw[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
if l2Txs[i].ToIdx == 0 { // ToEthAddr/ToBJJ case
var accAuth *common.AccountCreationAuth var accAuth *common.AccountCreationAuth
validTxs, l1CoordinatorTxs, accAuth, positionL1, err = validTxs, l1CoordinatorTxs, accAuth, positionL1, err =
txsel.processTxToEthAddrBJJ(validTxs, l1CoordinatorTxs, txsel.processTxToEthAddrBJJ(validTxs, l1CoordinatorTxs,
positionL1, l2TxsRaw[i])
positionL1, l2Txs[i])
if err != nil { if err != nil {
log.Debug(err) log.Debug(err)
continue continue
@ -275,33 +257,22 @@ func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
if accAuth != nil { if accAuth != nil {
accAuths = append(accAuths, accAuth.Signature) accAuths = append(accAuths, accAuth.Signature)
} }
} else if l2TxsRaw[i].ToIdx >= common.IdxUserThreshold {
_, err = txsel.localAccountsDB.GetAccount(l2TxsRaw[i].ToIdx)
} else if l2Txs[i].ToIdx >= common.IdxUserThreshold {
_, err = txsel.localAccountsDB.GetAccount(l2Txs[i].ToIdx)
if err != nil { if err != nil {
// tx not valid // tx not valid
log.Debugw("invalid L2Tx: ToIdx not found in StateDB", log.Debugw("invalid L2Tx: ToIdx not found in StateDB",
"ToIdx", l2TxsRaw[i].ToIdx)
"ToIdx", l2Txs[i].ToIdx)
continue continue
} }
// TODO if EthAddr!=0 or BJJ!=0, check that ToIdxAccount.EthAddr or BJJ // TODO if EthAddr!=0 or BJJ!=0, check that ToIdxAccount.EthAddr or BJJ
// Account found in the DB, include the l2Tx in the selection // Account found in the DB, include the l2Tx in the selection
validTxs = append(validTxs, l2TxsRaw[i])
} else if l2TxsRaw[i].ToIdx == common.Idx(1) {
validTxs = append(validTxs, l2Txs[i])
} else if l2Txs[i].ToIdx == common.Idx(1) {
// valid txs (of Exit type) // valid txs (of Exit type)
validTxs = append(validTxs, l2TxsRaw[i])
validTxs = append(validTxs, l2Txs[i])
} }
// TODO if needed add L1CoordinatorTx to create a Coordinator
// account for the new TokenID
// var newL1CoordTx *common.L1Tx
// newL1CoordTx, positionL1, err = txsel.coordAccountForTokenID(l1CoordinatorTxs, l2TxsRaw[i].TokenID, positionL1)
// if err != nil {
// return nil, nil, nil, nil, nil, tracerr.Wrap(err)
// }
// if newL1CoordTx != nil {
// l1CoordinatorTxs = append(l1CoordinatorTxs, *newL1CoordTx)
// }
} }
// Process L1CoordinatorTxs // Process L1CoordinatorTxs
@ -311,41 +282,39 @@ func (txsel *TxSelector) GetL1L2TxSelection(selectionConfig *SelectionConfig,
return nil, nil, nil, nil, nil, tracerr.Wrap(err) return nil, nil, nil, nil, nil, tracerr.Wrap(err)
} }
} }
// get CoordIdxsMap for the TokenIDs
coordIdxsMap := make(map[common.TokenID]common.Idx)
// TODO TMP (related to L#260
// for i := 0; i < len(l2Txs); i++ {
// coordIdx, err := txsel.getCoordIdx(l2Txs[i].TokenID)
// if err != nil {
// // if err is db.ErrNotFound, should not happen, as all
// // the l2Txs.TokenID should have a CoordinatorIdx
// // created in the DB at this point
// return nil, nil, nil, nil, nil, tracerr.Wrap(err)
// }
// coordIdxsMap[l2Txs[i].TokenID] = coordIdx
// }
var coordIdxs []common.Idx
tp.AccumulatedFees = make(map[common.Idx]*big.Int) tp.AccumulatedFees = make(map[common.Idx]*big.Int)
for _, idx := range coordIdxs {
for _, idx := range coordIdxsMap {
tp.AccumulatedFees[idx] = big.NewInt(0) tp.AccumulatedFees[idx] = big.NewInt(0)
}
// once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
// coordIdxs. In this way, if a coordIdx uses an Idx that is being
// created in the current batch, at this point the Idx will be created
coordIdxsMap, err = txsel.localAccountsDB.GetTokenIDsFromIdxs(coordIdxs)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
coordIdxs = append(coordIdxs, idx)
} }
// get most profitable L2-tx // get most profitable L2-tx
maxL2Txs := selectionConfig.TxProcessorConfig.MaxTx - uint32(len(l1CoordinatorTxs)) // - len(l1UserTxs) // TODO if there are L1UserTxs take them in to account maxL2Txs := selectionConfig.TxProcessorConfig.MaxTx - uint32(len(l1CoordinatorTxs)) // - len(l1UserTxs) // TODO if there are L1UserTxs take them in to account
l2Txs := txsel.getL2Profitable(validTxs, maxL2Txs)
// Process L2Txs
for i := 0; i < len(l2Txs); i++ {
_, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &l2Txs[i])
selectedL2Txs := txsel.getL2Profitable(l2Txs, maxL2Txs) // TODO this will only need to crop the lasts, as are already sorted
for i := 0; i < len(selectedL2Txs); i++ {
_, _, _, err = tp.ProcessL2Tx(coordIdxsMap, nil, nil, &selectedL2Txs[i])
if err != nil { if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err) return nil, nil, nil, nil, nil, tracerr.Wrap(err)
} }
} }
err = txsel.AddCoordIdxs(coordIdxsMap)
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
err = txsel.localAccountsDB.MakeCheckpoint()
if err != nil {
return nil, nil, nil, nil, nil, tracerr.Wrap(err)
}
return nil, accAuths, l1Txs, l1CoordinatorTxs, l2Txs, nil
return coordIdxs, accAuths, l1Txs, l1CoordinatorTxs, selectedL2Txs, nil
} }
// processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where // processTxsToEthAddrBJJ process the common.PoolL2Tx in the case where
@ -424,6 +393,7 @@ func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []
FromEthAddr: accAuth.EthAddr, FromEthAddr: accAuth.EthAddr,
FromBJJ: accAuth.BJJ, FromBJJ: accAuth.BJJ,
TokenID: l2Tx.TokenID, TokenID: l2Tx.TokenID,
Amount: big.NewInt(0),
DepositAmount: big.NewInt(0), DepositAmount: big.NewInt(0),
Type: common.TxTypeCreateAccountDeposit, Type: common.TxTypeCreateAccountDeposit,
} }
@ -450,6 +420,7 @@ func (txsel *TxSelector) processTxToEthAddrBJJ(validTxs txs, l1CoordinatorTxs []
FromEthAddr: l2Tx.ToEthAddr, FromEthAddr: l2Tx.ToEthAddr,
FromBJJ: l2Tx.ToBJJ, FromBJJ: l2Tx.ToBJJ,
TokenID: l2Tx.TokenID, TokenID: l2Tx.TokenID,
Amount: big.NewInt(0),
DepositAmount: big.NewInt(0), DepositAmount: big.NewInt(0),
Type: common.TxTypeCreateAccountDeposit, Type: common.TxTypeCreateAccountDeposit,
} }

+ 0
- 20
txselector/txselector_test.go

@ -64,24 +64,6 @@ func addTokens(t *testing.T, tokens []common.Token, db *sqlx.DB) {
assert.NoError(t, hdb.AddTokens(tokens)) assert.NoError(t, hdb.AddTokens(tokens))
} }
func TestCoordIdxsDB(t *testing.T) {
chainID := uint16(0)
txsel := initTest(t, chainID, til.SetPool0)
test.WipeDB(txsel.l2db.DB())
coordIdxs := make(map[common.TokenID]common.Idx)
coordIdxs[common.TokenID(0)] = common.Idx(256)
coordIdxs[common.TokenID(1)] = common.Idx(257)
coordIdxs[common.TokenID(2)] = common.Idx(258)
err := txsel.AddCoordIdxs(coordIdxs)
assert.NoError(t, err)
r, err := txsel.GetCoordIdxs()
assert.NoError(t, err)
assert.Equal(t, coordIdxs, r)
}
func TestGetL2TxSelection(t *testing.T) { func TestGetL2TxSelection(t *testing.T) {
chainID := uint16(0) chainID := uint16(0)
txsel := initTest(t, chainID, til.SetPool0) txsel := initTest(t, chainID, til.SetPool0)
@ -99,8 +81,6 @@ func TestGetL2TxSelection(t *testing.T) {
coordIdxs[common.TokenID(1)] = common.Idx(257) coordIdxs[common.TokenID(1)] = common.Idx(257)
coordIdxs[common.TokenID(2)] = common.Idx(258) coordIdxs[common.TokenID(2)] = common.Idx(258)
coordIdxs[common.TokenID(3)] = common.Idx(259) coordIdxs[common.TokenID(3)] = common.Idx(259)
err = txsel.AddCoordIdxs(coordIdxs)
assert.NoError(t, err)
// add tokens to HistoryDB to avoid breaking FK constrains // add tokens to HistoryDB to avoid breaking FK constrains
var tokens []common.Token var tokens []common.Token

Loading…
Cancel
Save