arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/txselector/txselector.go
txselector/txselector.goRaw
  1package txselector
  2
  3// current: very simple version of TxSelector
  4
  5import (
  6	"bytes"
  7	"math/big"
  8	"sort"
  9
 10	ethCommon "github.com/ethereum/go-ethereum/common"
 11	"github.com/hermeznetwork/hermez-node/common"
 12	"github.com/hermeznetwork/hermez-node/db/l2db"
 13	"github.com/hermeznetwork/hermez-node/db/statedb"
 14	"github.com/hermeznetwork/hermez-node/log"
 15	"github.com/iden3/go-iden3-crypto/babyjub"
 16)
 17
 18// txs implements the interface Sort for an array of Tx
 19type txs []*common.PoolL2Tx
 20
 21func (t txs) Len() int {
 22	return len(t)
 23}
 24func (t txs) Swap(i, j int) {
 25	t[i], t[j] = t[j], t[i]
 26}
 27func (t txs) Less(i, j int) bool {
 28	return *t[i].AbsoluteFee > *t[j].AbsoluteFee
 29}
 30
 31// TxSelector implements all the functionalities to select the txs for the next batch
 32type TxSelector struct {
 33	// MaxL1UserTxs is the maximum L1-user-tx for a batch
 34	MaxL1UserTxs uint64
 35	// MaxL1OperatorTxs is the maximum L1-operator-tx for a batch
 36	MaxL1OperatorTxs uint64
 37	// MaxTxs is the maximum txs for a batch
 38	MaxTxs uint64
 39
 40	l2db            *l2db.L2DB
 41	localAccountsDB *statedb.LocalStateDB
 42}
 43
 44// NewTxSelector returns a *TxSelector
 45func NewTxSelector(dbpath string, synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB, maxL1UserTxs, maxL1OperatorTxs, maxTxs uint64) (*TxSelector, error) {
 46	localAccountsDB, err := statedb.NewLocalStateDB(dbpath, synchronizerStateDB, statedb.TypeTxSelector, 0) // without merkletree
 47	if err != nil {
 48		return nil, err
 49	}
 50
 51	return &TxSelector{
 52		MaxL1UserTxs:     maxL1UserTxs,
 53		MaxL1OperatorTxs: maxL1OperatorTxs,
 54		MaxTxs:           maxTxs,
 55		l2db:             l2,
 56		localAccountsDB:  localAccountsDB,
 57	}, nil
 58}
 59
 60// Reset tells the TxSelector to get it's internal AccountsDB
 61// from the required `batchNum`
 62func (txsel *TxSelector) Reset(batchNum common.BatchNum) error {
 63	err := txsel.localAccountsDB.Reset(batchNum, true)
 64	if err != nil {
 65		return err
 66	}
 67	return nil
 68}
 69
 70// GetL2TxSelection returns a selection of the L2Txs for the next batch, from the L2DB pool
 71func (txsel *TxSelector) GetL2TxSelection(batchNum common.BatchNum) ([]*common.PoolL2Tx, error) {
 72	// get pending l2-tx from tx-pool
 73	l2TxsRaw, err := txsel.l2db.GetPendingTxs() // once l2db ready, maybe use parameter 'batchNum'
 74	if err != nil {
 75		return nil, err
 76	}
 77
 78	// discard the txs that don't have an Account in the AccountDB
 79	var validTxs txs
 80	for _, tx := range l2TxsRaw {
 81		_, err = txsel.localAccountsDB.GetAccount(&tx.FromIdx)
 82		if err == nil {
 83			// if FromIdx has an account into the AccountsDB
 84			validTxs = append(validTxs, tx)
 85		}
 86	}
 87
 88	// get most profitable L2-tx
 89	txs := txsel.getL2Profitable(validTxs, txsel.MaxTxs)
 90
 91	// process the txs in the local AccountsDB
 92	_, _, err = txsel.localAccountsDB.ProcessTxs(nil, nil, txs)
 93	if err != nil {
 94		return nil, err
 95	}
 96	err = txsel.localAccountsDB.MakeCheckpoint()
 97	return txs, err
 98}
 99
100// GetL1L2TxSelection returns the selection of L1 + L2 txs
101func (txsel *TxSelector) GetL1L2TxSelection(batchNum common.BatchNum, l1Txs []*common.L1Tx) ([]*common.L1Tx, []*common.L1Tx, []*common.PoolL2Tx, error) {
102	// apply l1-user-tx to localAccountDB
103	//     create new leaves
104	//     update balances
105	//     update nonces
106
107	// get pending l2-tx from tx-pool
108	l2TxsRaw, err := txsel.l2db.GetPendingTxs() // (batchID)
109	if err != nil {
110		return nil, nil, nil, err
111	}
112
113	var validTxs txs
114	var l1CoordinatorTxs []*common.L1Tx
115	positionL1 := len(l1Txs)
116
117	// if tx.ToIdx>=256, tx.ToIdx should exist to localAccountsDB, if so,
118	// tx is used.  if tx.ToIdx==0, check if tx.ToEthAddr/tx.ToBJJ exist in
119	// localAccountsDB, if yes tx is used; if not, check if tx.ToEthAddr is
120	// in AccountCreationAuthDB, if so, tx is used and L1CoordinatorTx of
121	// CreateAccountAndDeposit is created.
122	for i := 0; i < len(l2TxsRaw); i++ {
123		if l2TxsRaw[i].ToIdx == nil {
124			if checkAlreadyPendingToCreate(l1CoordinatorTxs, l2TxsRaw[i].ToEthAddr, l2TxsRaw[i].ToBJJ) {
125				// if L2Tx needs a new L1CoordinatorTx of CreateAccount type,
126				// and a previous L2Tx in the current process already created
127				// a L1CoordinatorTx of this type, in the DB there still seem
128				// that needs to create a new L1CoordinatorTx, but as is already
129				// created, the tx is valid
130				validTxs = append(validTxs, l2TxsRaw[i])
131				continue
132			}
133
134			if !bytes.Equal(l2TxsRaw[i].ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) &&
135				!bytes.Equal(l2TxsRaw[i].ToEthAddr.Bytes(), common.FFAddr.Bytes()) {
136				// case: ToEthAddr != 0x00 neither 0xff
137				var accAuth *common.AccountCreationAuth
138				if l2TxsRaw[i].ToBJJ != nil {
139					// case: ToBJJ!=0:
140					// if idx exist for EthAddr&BJJ use it
141					_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2TxsRaw[i].ToEthAddr, l2TxsRaw[i].ToBJJ)
142					if err == nil {
143						// account for ToEthAddr&ToBJJ already exist,
144						// there is no need to create a new one.
145						// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
146						validTxs = append(validTxs, l2TxsRaw[i])
147						continue
148					}
149					// if not, check if AccountCreationAuth exist for that ToEthAddr&BJJ
150					// accAuth, err = txsel.l2db.GetAccountCreationAuthBJJ(l2TxsRaw[i].ToEthAddr, l2TxsRaw[i].ToBJJ)
151					accAuth, err = txsel.l2db.GetAccountCreationAuth(l2TxsRaw[i].ToEthAddr)
152					if err != nil {
153						// not found, l2Tx will not be added in the selection
154						log.Debugw("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB", "ToIdx", l2TxsRaw[i].ToIdx, "ToEthAddr", l2TxsRaw[i].ToEthAddr)
155						continue
156					}
157					if accAuth.BJJ != l2TxsRaw[i].ToBJJ {
158						// if AccountCreationAuth.BJJ is not the same than in the tx, tx is not accepted
159						log.Debugw("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr & ToBJJ found in AccountCreationAuths L2DB", "ToIdx", l2TxsRaw[i].ToIdx, "ToEthAddr", l2TxsRaw[i].ToEthAddr, "ToBJJ", l2TxsRaw[i].ToBJJ)
160						continue
161					}
162					validTxs = append(validTxs, l2TxsRaw[i])
163				} else {
164					// case: ToBJJ==0:
165					// if idx exist for EthAddr use it
166					_, err := txsel.localAccountsDB.GetIdxByEthAddr(l2TxsRaw[i].ToEthAddr)
167					if err == nil {
168						// account for ToEthAddr already exist,
169						// there is no need to create a new one.
170						// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
171						validTxs = append(validTxs, l2TxsRaw[i])
172						continue
173					}
174					// if not, check if AccountCreationAuth exist for that ToEthAddr
175					accAuth, err = txsel.l2db.GetAccountCreationAuth(l2TxsRaw[i].ToEthAddr)
176					if err != nil {
177						// not found, l2Tx will not be added in the selection
178						log.Debugw("invalid L2Tx: ToIdx not found in StateDB, neither ToEthAddr found in AccountCreationAuths L2DB", "ToIdx", l2TxsRaw[i].ToIdx, "ToEthAddr", l2TxsRaw[i].ToEthAddr)
179						continue
180					}
181					validTxs = append(validTxs, l2TxsRaw[i])
182				}
183				// create L1CoordinatorTx for the accountCreation
184				l1CoordinatorTx := &common.L1Tx{
185					Position:    positionL1,
186					UserOrigin:  false,
187					FromEthAddr: accAuth.EthAddr,
188					FromBJJ:     accAuth.BJJ,
189					TokenID:     l2TxsRaw[i].TokenID,
190					LoadAmount:  big.NewInt(0),
191					Type:        common.TxTypeCreateAccountDeposit,
192				}
193				positionL1++
194				l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
195			} else if bytes.Equal(l2TxsRaw[i].ToEthAddr.Bytes(), common.FFAddr.Bytes()) && l2TxsRaw[i].ToBJJ != nil {
196				// if idx exist for EthAddr&BJJ use it
197				_, err := txsel.localAccountsDB.GetIdxByEthAddrBJJ(l2TxsRaw[i].ToEthAddr, l2TxsRaw[i].ToBJJ)
198				if err == nil {
199					// account for ToEthAddr&ToBJJ already exist, (where ToEthAddr==0xff)
200					// there is no need to create a new one.
201					// tx valid, StateDB will use the ToIdx==0 to define the AuxToIdx
202					validTxs = append(validTxs, l2TxsRaw[i])
203					continue
204				}
205				// if idx don't exist for EthAddr&BJJ,
206				// coordinator can create a new account without
207				// L1Authorization, as ToEthAddr==0xff
208				// create L1CoordinatorTx for the accountCreation
209				if l2TxsRaw[i].ToEthAddr == nil {
210					log.Warn("l2TxsRaw[i].ToEthAddr should not be nil")
211					continue
212				}
213				l1CoordinatorTx := &common.L1Tx{
214					Position:    positionL1,
215					UserOrigin:  false,
216					FromEthAddr: *l2TxsRaw[i].ToEthAddr,
217					FromBJJ:     l2TxsRaw[i].ToBJJ,
218					TokenID:     l2TxsRaw[i].TokenID,
219					LoadAmount:  big.NewInt(0),
220					Type:        common.TxTypeCreateAccountDeposit,
221				}
222				positionL1++
223				l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
224			}
225		} else if *l2TxsRaw[i].ToIdx >= common.IdxUserThreshold {
226			_, err = txsel.localAccountsDB.GetAccount(l2TxsRaw[i].ToIdx)
227			if err != nil {
228				// tx not valid
229				log.Debugw("invalid L2Tx: ToIdx not found in StateDB", "ToIdx", l2TxsRaw[i].ToIdx)
230				continue
231			}
232			// Account found in the DB, include the l2Tx in the selection
233			validTxs = append(validTxs, l2TxsRaw[i])
234		} else if *l2TxsRaw[i].ToIdx == common.Idx(1) { // nil already checked before
235			// valid txs (of Exit type)
236			validTxs = append(validTxs, l2TxsRaw[i])
237		}
238	}
239
240	// get most profitable L2-tx
241	maxL2Txs := txsel.MaxTxs - uint64(len(l1CoordinatorTxs)) // - len(l1UserTxs)
242	l2Txs := txsel.getL2Profitable(validTxs, maxL2Txs)
243
244	// process the txs in the local AccountsDB
245	_, _, err = txsel.localAccountsDB.ProcessTxs(l1Txs, l1CoordinatorTxs, l2Txs)
246	if err != nil {
247		return nil, nil, nil, err
248	}
249	err = txsel.localAccountsDB.MakeCheckpoint()
250	if err != nil {
251		return nil, nil, nil, err
252	}
253
254	return l1Txs, l1CoordinatorTxs, l2Txs, nil
255}
256
257func checkAlreadyPendingToCreate(l1CoordinatorTxs []*common.L1Tx, addr *ethCommon.Address, bjj *babyjub.PublicKey) bool {
258	if addr == nil {
259		log.Warn("The provided addr is nil")
260		return false
261	}
262	for i := 0; i < len(l1CoordinatorTxs); i++ {
263		if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) {
264			if bjj == nil {
265				return true
266			}
267			if l1CoordinatorTxs[i].FromBJJ == bjj {
268				return true
269			}
270		}
271	}
272	return false
273}
274
275func (txsel *TxSelector) getL2Profitable(txs txs, max uint64) txs {
276	sort.Sort(txs)
277	if len(txs) < int(max) {
278		return txs
279	}
280	return txs[:max]
281}