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