/
tx_pool.go
371 lines (329 loc) · 11.3 KB
/
tx_pool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package eth
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
rpctypes "github.com/FiboChain/fbc/app/rpc/types"
ethermint "github.com/FiboChain/fbc/app/types"
clientcontext "github.com/FiboChain/fbc/libs/cosmos-sdk/client/context"
sdk "github.com/FiboChain/fbc/libs/cosmos-sdk/types"
sdkerrors "github.com/FiboChain/fbc/libs/cosmos-sdk/types/errors"
authclient "github.com/FiboChain/fbc/libs/cosmos-sdk/x/auth/client/utils"
authtypes "github.com/FiboChain/fbc/libs/cosmos-sdk/x/auth/types"
"github.com/FiboChain/fbc/libs/tendermint/libs/log"
"github.com/FiboChain/fbc/libs/tendermint/types"
tmdb "github.com/FiboChain/fbc/libs/tm-db"
evmtypes "github.com/FiboChain/fbc/x/evm/types"
"github.com/spf13/viper"
)
const (
FlagEnableTxPool = "enable-tx-pool"
TxPoolCap = "tx-pool-cap"
BroadcastPeriodSecond = "broadcast-period-second"
txPoolDb = "tx_pool"
)
var broadcastErrors = map[uint32]*sdkerrors.Error{
sdkerrors.ErrTxInMempoolCache.ABCICode(): sdkerrors.ErrTxInMempoolCache,
sdkerrors.ErrMempoolIsFull.ABCICode(): sdkerrors.ErrMempoolIsFull,
sdkerrors.ErrTxTooLarge.ABCICode(): sdkerrors.ErrTxTooLarge,
sdkerrors.ErrInvalidSequence.ABCICode(): sdkerrors.ErrInvalidSequence,
}
type TxPool struct {
addressTxsPool map[common.Address][]*evmtypes.MsgEthereumTx // All currently processable transactions
clientCtx clientcontext.CLIContext
db tmdb.DB
mu sync.Mutex
cap uint64
broadcastInterval time.Duration
logger log.Logger
}
func NewTxPool(clientCtx clientcontext.CLIContext, api *PublicEthereumAPI) *TxPool {
db, err := openDB()
if err != nil {
panic(err)
}
interval := time.Second * time.Duration(viper.GetInt(BroadcastPeriodSecond))
pool := &TxPool{
addressTxsPool: make(map[common.Address][]*evmtypes.MsgEthereumTx),
clientCtx: clientCtx,
db: db,
cap: viper.GetUint64(TxPoolCap),
broadcastInterval: interval,
logger: api.logger.With("module", "tx_pool", "namespace", "eth"),
}
if err = pool.initDB(api); err != nil {
panic(err)
}
return pool
}
func openDB() (tmdb.DB, error) {
rootDir := viper.GetString("home")
dataDir := filepath.Join(rootDir, "data")
return sdk.NewDB(txPoolDb, dataDir)
}
func (pool *TxPool) initDB(api *PublicEthereumAPI) error {
itr, err := pool.db.Iterator(nil, nil)
if err != nil {
return err
}
defer itr.Close()
for ; itr.Valid(); itr.Next() {
key := string(itr.Key())
txBytes := itr.Value()
tmp := strings.Split(key, "|")
if len(tmp) != 2 {
continue
}
address := common.HexToAddress(tmp[0])
txNonce, err := strconv.Atoi(tmp[1])
if err != nil {
return err
}
tx := new(evmtypes.MsgEthereumTx)
if err = authtypes.EthereumTxDecode(txBytes, tx); err != nil {
return err
}
if int(tx.Data.AccountNonce) != txNonce {
return fmt.Errorf("nonce[%d] in key is not equal to nonce[%d] in value", tx.Data.AccountNonce, txNonce)
}
blockNrOrHash := rpctypes.BlockNumberOrHashWithNumber(rpctypes.PendingBlockNumber)
pCurrentNonce, err := api.GetTransactionCount(address, blockNrOrHash)
if err != nil {
return err
}
currentNonce := int(*pCurrentNonce)
if txNonce < currentNonce {
continue
}
if err = pool.insertTx(address, tx); err != nil {
return err
}
}
return nil
}
func broadcastTxByTxPool(api *PublicEthereumAPI, tx *evmtypes.MsgEthereumTx, txBytes []byte) (common.Hash, error) {
//TODO: to delete after venus height
lastHeight, err := api.clientCtx.Client.LatestBlockNumber()
if err != nil {
return common.Hash{}, err
}
// Get sender address
chainIDEpoch, err := ethermint.ParseChainID(api.clientCtx.ChainID)
if err != nil {
return common.Hash{}, err
}
err = tx.VerifySig(chainIDEpoch, api.clientCtx.Height)
if err != nil {
return common.Hash{}, err
}
txHash := common.BytesToHash(types.Tx(txBytes).Hash(lastHeight))
tx.Data.Hash = &txHash
from := common.HexToAddress(tx.GetFrom())
api.txPool.mu.Lock()
defer api.txPool.mu.Unlock()
if err = api.txPool.CacheAndBroadcastTx(api, from, tx); err != nil {
api.txPool.logger.Error("eth_sendRawTransaction txPool err:", err.Error())
return common.Hash{}, err
}
return txHash, nil
}
func (pool *TxPool) CacheAndBroadcastTx(api *PublicEthereumAPI, address common.Address, tx *evmtypes.MsgEthereumTx) error {
// get currentNonce
blockNrOrHash := rpctypes.BlockNumberOrHashWithNumber(rpctypes.PendingBlockNumber)
pCurrentNonce, err := api.GetTransactionCount(address, blockNrOrHash)
if err != nil {
return err
}
currentNonce := uint64(*pCurrentNonce)
if tx.Data.AccountNonce < currentNonce {
return fmt.Errorf("AccountNonce of tx is less than currentNonce in memPool: AccountNonce[%d], currentNonce[%d]", tx.Data.AccountNonce, currentNonce)
}
if tx.Data.AccountNonce > currentNonce+pool.cap {
return fmt.Errorf("AccountNonce of tx is bigger than txPool capacity, please try later: AccountNonce[%d]", tx.Data.AccountNonce)
}
if err = pool.insertTx(address, tx); err != nil {
return err
}
// update DB
if err = pool.writeTxInDB(address, tx); err != nil {
return err
}
_ = pool.continueBroadcast(api, currentNonce, address)
return nil
}
func (pool *TxPool) update(index int, address common.Address, tx *evmtypes.MsgEthereumTx) error {
txsLen := len(pool.addressTxsPool[address])
if index >= txsLen {
pool.addressTxsPool[address] = append(pool.addressTxsPool[address], tx)
} else {
tmpTx := make([]*evmtypes.MsgEthereumTx, len(pool.addressTxsPool[address][index:]))
copy(tmpTx, pool.addressTxsPool[address][index:])
pool.addressTxsPool[address] =
append(append(pool.addressTxsPool[address][:index], tx), tmpTx...)
}
return nil
}
// insert the tx into the txPool
func (pool *TxPool) insertTx(address common.Address, tx *evmtypes.MsgEthereumTx) error {
// if this is the first time to insertTx, make the cap of txPool be TxPoolSliceMaxLen
if _, ok := pool.addressTxsPool[address]; !ok {
pool.addressTxsPool[address] = make([]*evmtypes.MsgEthereumTx, 0, pool.cap)
}
index := 0
for index < len(pool.addressTxsPool[address]) {
// the tx nonce has in txPool, drop duplicate tx
if tx.Data.AccountNonce == pool.addressTxsPool[address][index].Data.AccountNonce {
return fmt.Errorf("duplicate tx, this AccountNonce of tx has been in txPool. AccountNonce[%d]", tx.Data.AccountNonce)
}
// find the index to insert
if tx.Data.AccountNonce < pool.addressTxsPool[address][index].Data.AccountNonce {
break
}
index++
}
// update txPool
return pool.update(index, address, tx)
}
// iterate through the txPool map, check if need to continue broadcast tx and do it
func (pool *TxPool) continueBroadcast(api *PublicEthereumAPI, currentNonce uint64, address common.Address) error {
i := 0
txsLen := len(pool.addressTxsPool[address])
var err error
for ; i < txsLen; i++ {
if pool.addressTxsPool[address][i].Data.AccountNonce == currentNonce {
// do broadcast
if err = pool.broadcast(pool.addressTxsPool[address][i]); err != nil {
pool.logger.Error(err.Error())
// delete the tx when broadcast failed
if err := pool.delTxInDB(address, pool.addressTxsPool[address][i].Data.AccountNonce); err != nil {
pool.logger.Error(err.Error())
}
break
}
// update currentNonce
currentNonce++
} else if pool.addressTxsPool[address][i].Data.AccountNonce < currentNonce {
continue
} else {
break
}
}
// i is the start index of txs that don't need to be dropped
if err != nil {
if !strings.Contains(err.Error(), sdkerrors.ErrMempoolIsFull.Error()) &&
!strings.Contains(err.Error(), sdkerrors.ErrInvalidSequence.Error()) {
// tx has err, and err is not mempoolfull, the tx should be dropped
err = fmt.Errorf("broadcast failed and tx dropped. err:%s; nonce:%d; tx_hash:%s; address:%s\n",
err.Error(), pool.addressTxsPool[address][i].Data.AccountNonce, pool.addressTxsPool[address][i].Data.Hash.String(), address.String())
pool.dropTxs(i+1, address)
} else {
err = fmt.Errorf("broadcast failed. err:%s; nonce:%d; tx_hash:%s; address:%s\n",
err.Error(), pool.addressTxsPool[address][i].Data.AccountNonce, pool.addressTxsPool[address][i].Data.Hash.String(), address.String())
pool.dropTxs(i, address)
}
pool.logger.Error(err.Error())
} else {
pool.dropTxs(i, address)
}
return err
}
// drop [0:index) txs in txpool
func (pool *TxPool) dropTxs(index int, address common.Address) {
tmp := make([]*evmtypes.MsgEthereumTx, len(pool.addressTxsPool[address][index:]), pool.cap)
copy(tmp, pool.addressTxsPool[address][index:])
pool.addressTxsPool[address] = tmp
}
func (pool *TxPool) broadcast(tx *evmtypes.MsgEthereumTx) error {
// TODO: to delete after venus height
lastHeight, err := pool.clientCtx.Client.LatestBlockNumber()
if err != nil {
return err
}
var txEncoder sdk.TxEncoder
if types.HigherThanVenus(lastHeight) {
txEncoder = authclient.GetTxEncoder(nil, authclient.WithEthereumTx())
} else {
txEncoder = authclient.GetTxEncoder(pool.clientCtx.Codec)
}
txBytes, err := txEncoder(tx)
if err != nil {
return err
}
res, err := pool.clientCtx.BroadcastTx(txBytes)
if err != nil {
pool.logger.Error(err.Error())
}
if res.Code != sdk.CodeOK {
if broadcastErrors[res.Code] == nil {
return fmt.Errorf("broadcast tx failed, code: %d, rawLog: %s", res.Code, res.RawLog)
} else {
return fmt.Errorf("broadcast tx failed, err: %s", broadcastErrors[res.Code].Error())
}
}
return nil
}
func (pool *TxPool) writeTxInDB(address common.Address, tx *evmtypes.MsgEthereumTx) error {
key := []byte(address.Hex() + "|" + strconv.Itoa(int(tx.Data.AccountNonce)))
txEncoder := authclient.GetTxEncoder(nil, authclient.WithEthereumTx())
// Encode transaction by RLP encoder
txBytes, err := txEncoder(tx)
if err != nil {
return err
}
ok, err := pool.db.Has(key)
if err != nil {
return err
}
if ok {
return fmt.Errorf("this AccountNonce of tx has been in DB. AccountNonce[%d]", tx.Data.AccountNonce)
}
return pool.db.Set(key, txBytes)
}
func (pool *TxPool) delTxInDB(address common.Address, txNonce uint64) error {
key := []byte(address.Hex() + "|" + strconv.Itoa(int(txNonce)))
ok, err := pool.db.Has(key)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("this AccontNonce is not found in DB. AccountNonce[%d]", txNonce)
}
return pool.db.Delete(key)
}
func (pool *TxPool) broadcastPeriod(api *PublicEthereumAPI) {
for {
time.Sleep(pool.broadcastInterval)
pool.broadcastPeriodCore(api)
}
}
func (pool *TxPool) broadcastPeriodCore(api *PublicEthereumAPI) {
pool.mu.Lock()
defer pool.mu.Unlock()
blockNrOrHash := rpctypes.BlockNumberOrHashWithNumber(rpctypes.PendingBlockNumber)
for address, _ := range pool.addressTxsPool {
pCurrentNonce, err := api.GetTransactionCount(address, blockNrOrHash)
if err != nil {
pool.logger.Error(err.Error())
continue
}
currentNonce := uint64(*pCurrentNonce)
pool.continueBroadcast(api, currentNonce, address)
}
}
func (pool *TxPool) broadcastOnce(api *PublicEthereumAPI) {
pool.mu.Lock()
defer pool.mu.Unlock()
blockNrOrHash := rpctypes.BlockNumberOrHashWithNumber(rpctypes.PendingBlockNumber)
for address, _ := range pool.addressTxsPool {
pCurrentNonce, err := api.GetTransactionCount(address, blockNrOrHash)
if err != nil {
continue
}
currentNonce := uint64(*pCurrentNonce)
pool.continueBroadcast(api, currentNonce, address)
}
}