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(coordIdxs []common.Idx, 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(coordIdxs, 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(coordIdxs []common.Idx, 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 == 0 {
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 l1CoordinatorTx := common.L1Tx{
210 Position: positionL1,
211 UserOrigin: false,
212 FromEthAddr: l2TxsRaw[i].ToEthAddr,
213 FromBJJ: l2TxsRaw[i].ToBJJ,
214 TokenID: l2TxsRaw[i].TokenID,
215 LoadAmount: big.NewInt(0),
216 Type: common.TxTypeCreateAccountDeposit,
217 }
218 positionL1++
219 l1CoordinatorTxs = append(l1CoordinatorTxs, l1CoordinatorTx)
220 }
221 } else if l2TxsRaw[i].ToIdx >= common.IdxUserThreshold {
222 _, err = txsel.localAccountsDB.GetAccount(l2TxsRaw[i].ToIdx)
223 if err != nil {
224 // tx not valid
225 log.Debugw("invalid L2Tx: ToIdx not found in StateDB", "ToIdx", l2TxsRaw[i].ToIdx)
226 continue
227 }
228 // Account found in the DB, include the l2Tx in the selection
229 validTxs = append(validTxs, l2TxsRaw[i])
230 } else if l2TxsRaw[i].ToIdx == common.Idx(1) {
231 // valid txs (of Exit type)
232 validTxs = append(validTxs, l2TxsRaw[i])
233 }
234 }
235
236 // get most profitable L2-tx
237 maxL2Txs := txsel.MaxTxs - uint64(len(l1CoordinatorTxs)) // - len(l1UserTxs)
238 l2Txs := txsel.getL2Profitable(validTxs, maxL2Txs)
239
240 // process the txs in the local AccountsDB
241 _, _, _, err = txsel.localAccountsDB.ProcessTxs(coordIdxs, l1Txs, l1CoordinatorTxs, l2Txs)
242 if err != nil {
243 return nil, nil, nil, err
244 }
245 err = txsel.localAccountsDB.MakeCheckpoint()
246 if err != nil {
247 return nil, nil, nil, err
248 }
249
250 return l1Txs, l1CoordinatorTxs, l2Txs, nil
251}
252
253func checkAlreadyPendingToCreate(l1CoordinatorTxs []common.L1Tx, addr ethCommon.Address, bjj *babyjub.PublicKey) bool {
254 for i := 0; i < len(l1CoordinatorTxs); i++ {
255 if bytes.Equal(l1CoordinatorTxs[i].FromEthAddr.Bytes(), addr.Bytes()) {
256 if bjj == nil {
257 return true
258 }
259 if l1CoordinatorTxs[i].FromBJJ == bjj {
260 return true
261 }
262 }
263 }
264 return false
265}
266
267// getL2Profitable returns the profitable selection of L2Txssorted by Nonce
268func (txsel *TxSelector) getL2Profitable(txs txs, max uint64) txs {
269 sort.Sort(txs)
270 if len(txs) < int(max) {
271 return txs
272 }
273 txs = txs[:max]
274
275 // sort l2Txs by Nonce. This can be done in many different ways, what
276 // is needed is to output the txs where the Nonce of txs for each
277 // Account is sorted, but the txs can not be grouped by sender Account
278 // neither by Fee. This is because later on the Nonces will need to be
279 // sequential for the zkproof generation.
280 sort.SliceStable(txs, func(i, j int) bool {
281 return txs[i].Nonce < txs[j].Nonce
282 })
283
284 return txs
285}