/
txpool.go
437 lines (369 loc) · 10.3 KB
/
txpool.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package protocol
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/golang/groupcache/lru"
log "github.com/sirupsen/logrus"
"github.com/bytom/vapor/consensus"
"github.com/bytom/vapor/event"
"github.com/bytom/vapor/protocol/bc"
"github.com/bytom/vapor/protocol/bc/types"
"github.com/bytom/vapor/protocol/state"
)
// msg type
const (
MsgNewTx = iota
MsgRemoveTx
logModule = "protocol"
)
var (
maxCachedErrTxs = 1000
maxMsgChSize = 1000
maxNewTxNum = 65536
maxOrphanNum = 32768
orphanTTL = 60 * time.Second
orphanExpireScanInterval = 30 * time.Second
txTTL = 1 * time.Hour
txExpireScanInterval = 20 * time.Minute
// ErrTransactionNotExist is the pre-defined error message
ErrTransactionNotExist = errors.New("transaction are not existed in the mempool")
// ErrPoolIsFull indicates the pool is full
ErrPoolIsFull = errors.New("transaction pool reach the max number")
// ErrDustTx indicates transaction is dust tx
ErrDustTx = errors.New("transaction is dust tx")
)
// DustFilterer is inerface for dust transaction filter rule
type DustFilterer interface {
IsDust(tx *types.Tx) bool
}
// TxMsgEvent is message wrap for subscribe event
type TxMsgEvent struct{ TxMsg *TxPoolMsg }
// TxDesc store tx and related info for mining strategy
type TxDesc struct {
Tx *types.Tx `json:"transaction"`
Added time.Time `json:"-"`
StatusFail bool `json:"status_fail"`
Height uint64 `json:"-"`
Weight uint64 `json:"-"`
Fee uint64 `json:"-"`
}
// TxPoolMsg is use for notify pool changes
type TxPoolMsg struct {
*TxDesc
MsgType int
}
type orphanTx struct {
*TxDesc
expiration time.Time
}
// TxPool is use for store the unconfirmed transaction
type TxPool struct {
lastUpdated int64
mtx sync.RWMutex
store Store
pool map[bc.Hash]*TxDesc
utxo map[bc.Hash]*types.Tx
orphans map[bc.Hash]*orphanTx
orphansByPrev map[bc.Hash]map[bc.Hash]*orphanTx
errCache *lru.Cache
filters []DustFilterer
eventDispatcher *event.Dispatcher
}
// NewTxPool init a new TxPool
func NewTxPool(store Store, filters []DustFilterer, dispatcher *event.Dispatcher) *TxPool {
tp := &TxPool{
lastUpdated: time.Now().Unix(),
store: store,
pool: make(map[bc.Hash]*TxDesc),
utxo: make(map[bc.Hash]*types.Tx),
orphans: make(map[bc.Hash]*orphanTx),
orphansByPrev: make(map[bc.Hash]map[bc.Hash]*orphanTx),
errCache: lru.New(maxCachedErrTxs),
filters: filters,
eventDispatcher: dispatcher,
}
go tp.orphanExpireWorker()
go tp.txExpireWorker()
return tp
}
// AddErrCache add a failed transaction record to lru cache
func (tp *TxPool) AddErrCache(txHash *bc.Hash, err error) {
tp.mtx.Lock()
defer tp.mtx.Unlock()
tp.errCache.Add(txHash, err)
}
// expireOrphan expire all the orphans that before the input time range
func (tp *TxPool) expireOrphan(now time.Time) {
tp.mtx.Lock()
defer tp.mtx.Unlock()
for hash, orphan := range tp.orphans {
if orphan.expiration.Before(now) {
tp.removeOrphan(&hash)
}
}
}
// GetErrCache return the error of the transaction
func (tp *TxPool) GetErrCache(txHash *bc.Hash) error {
tp.mtx.Lock()
defer tp.mtx.Unlock()
v, ok := tp.errCache.Get(txHash)
if !ok {
return nil
}
return v.(error)
}
// RemoveTransaction remove a transaction from the pool
func (tp *TxPool) RemoveTransaction(txHash *bc.Hash) {
tp.mtx.Lock()
defer tp.mtx.Unlock()
if txD := tp.removeTransaction(txHash); txD != nil {
atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgRemoveTx}})
log.WithFields(log.Fields{"module": logModule, "tx_id": txHash}).Debug("remove tx from mempool")
}
}
func (tp *TxPool) removeTransaction(txHash *bc.Hash) *TxDesc {
txD, ok := tp.pool[*txHash]
if !ok {
return nil
}
for _, output := range txD.Tx.ResultIds {
delete(tp.utxo, *output)
}
delete(tp.pool, *txHash)
return txD
}
// GetTransaction return the TxDesc by hash
func (tp *TxPool) GetTransaction(txHash *bc.Hash) (*TxDesc, error) {
tp.mtx.RLock()
defer tp.mtx.RUnlock()
if txD, ok := tp.pool[*txHash]; ok {
return txD, nil
}
return nil, ErrTransactionNotExist
}
// GetTransactions return all the transactions in the pool
func (tp *TxPool) GetTransactions() []*TxDesc {
tp.mtx.RLock()
defer tp.mtx.RUnlock()
txDs := make([]*TxDesc, len(tp.pool))
i := 0
for _, desc := range tp.pool {
txDs[i] = desc
i++
}
return txDs
}
// IsTransactionInPool check wheather a transaction in pool or not
func (tp *TxPool) IsTransactionInPool(txHash *bc.Hash) bool {
tp.mtx.RLock()
defer tp.mtx.RUnlock()
_, ok := tp.pool[*txHash]
return ok
}
// IsTransactionInErrCache check wheather a transaction in errCache or not
func (tp *TxPool) IsTransactionInErrCache(txHash *bc.Hash) bool {
tp.mtx.RLock()
defer tp.mtx.RUnlock()
_, ok := tp.errCache.Get(txHash)
return ok
}
// HaveTransaction IsTransactionInErrCache check is transaction in errCache or pool
func (tp *TxPool) HaveTransaction(txHash *bc.Hash) bool {
return tp.IsTransactionInPool(txHash) || tp.IsTransactionInErrCache(txHash)
}
func isTransactionZeroOutput(tx *types.Tx) bool {
for _, output := range tx.TxData.Outputs {
if value := output.AssetAmount(); value.Amount == uint64(0) {
return true
}
}
return false
}
func isNoGasStatusFail(tx *types.Tx, statusFail bool) bool {
if !statusFail {
return false
}
for _, input := range tx.TxData.Inputs {
if *consensus.BTMAssetID == input.AssetID() {
return false
}
}
return true
}
//IsDust checks if a tx has zero output
func (tp *TxPool) IsDust(tx *types.Tx) bool {
if ok := isTransactionZeroOutput(tx); ok {
return ok
}
for _, filter := range tp.filters {
if ok := filter.IsDust(tx); ok {
return ok
}
}
return false
}
func (tp *TxPool) processTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
tp.mtx.Lock()
defer tp.mtx.Unlock()
txD := &TxDesc{
Tx: tx,
StatusFail: statusFail,
Weight: tx.SerializedSize,
Height: height,
Fee: fee,
}
requireParents, err := tp.checkOrphanUtxos(tx)
if err != nil {
return false, err
}
if len(requireParents) > 0 {
return true, tp.addOrphan(txD, requireParents)
}
if err := tp.addTransaction(txD); err != nil {
return false, err
}
tp.processOrphans(txD)
return false, nil
}
// ProcessTransaction is the main entry for txpool handle new tx, ignore dust tx.
func (tp *TxPool) ProcessTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
if tp.IsDust(tx) {
log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Warn("dust tx")
return false, nil
}
if isNoGasStatusFail(tx, statusFail) {
log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Warn("drop no gas status fail tx")
return false, nil
}
return tp.processTransaction(tx, statusFail, height, fee)
}
func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
if len(tp.orphans) >= maxOrphanNum {
return ErrPoolIsFull
}
orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
tp.orphans[txD.Tx.ID] = orphan
for _, hash := range requireParents {
if _, ok := tp.orphansByPrev[*hash]; !ok {
tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
}
tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
}
return nil
}
func (tp *TxPool) addTransaction(txD *TxDesc) error {
if len(tp.pool) >= maxNewTxNum {
return ErrPoolIsFull
}
tx := txD.Tx
txD.Added = time.Now()
tp.pool[tx.ID] = txD
for _, id := range tx.ResultIds {
outputEntry, err := tx.Entry(*id)
if err != nil {
return err
}
var assetID bc.AssetID
switch output := outputEntry.(type) {
case *bc.IntraChainOutput:
assetID = *output.Source.Value.AssetId
case *bc.VoteOutput:
assetID = *output.Source.Value.AssetId
default:
continue
}
if !txD.StatusFail || assetID == *consensus.BTMAssetID {
tp.utxo[*id] = tx
}
}
atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}})
log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Debug("Add tx to mempool")
return nil
}
func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
view := state.NewUtxoViewpoint()
if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
return nil, err
}
hashes := []*bc.Hash{}
for _, hash := range tx.SpentOutputIDs {
if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
hashes = append(hashes, &hash)
}
}
return hashes, nil
}
func (tp *TxPool) orphanExpireWorker() {
ticker := time.NewTicker(orphanExpireScanInterval)
defer ticker.Stop()
for now := range ticker.C {
tp.expireOrphan(now)
}
}
func (tp *TxPool) processOrphans(txD *TxDesc) {
processOrphans := []*orphanTx{}
addRely := func(tx *types.Tx) {
for _, outHash := range tx.ResultIds {
orphans, ok := tp.orphansByPrev[*outHash]
if !ok {
continue
}
for _, orphan := range orphans {
processOrphans = append(processOrphans, orphan)
}
delete(tp.orphansByPrev, *outHash)
}
}
addRely(txD.Tx)
for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
processOrphan := processOrphans[0]
requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
if err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("processOrphans got unexpect error")
continue
}
if len(requireParents) == 0 {
addRely(processOrphan.Tx)
tp.removeOrphan(&processOrphan.Tx.ID)
tp.addTransaction(processOrphan.TxDesc)
}
}
}
func (tp *TxPool) removeOrphan(hash *bc.Hash) {
orphan, ok := tp.orphans[*hash]
if !ok {
return
}
for _, spend := range orphan.Tx.SpentOutputIDs {
orphans, ok := tp.orphansByPrev[spend]
if !ok {
continue
}
if delete(orphans, *hash); len(orphans) == 0 {
delete(tp.orphansByPrev, spend)
}
}
delete(tp.orphans, *hash)
}
func (tp *TxPool) txExpireWorker() {
ticker := time.NewTicker(txExpireScanInterval)
defer ticker.Stop()
for now := range ticker.C {
tp.expireTx(now)
}
}
// expireTx expires all the Txs that before the input time range
func (tp *TxPool) expireTx(now time.Time) {
tp.mtx.Lock()
defer tp.mtx.Unlock()
cutOff := now.Add(-txTTL)
for hash, txD := range tp.pool {
if txD.Added.Before(cutOff) {
tp.removeTransaction(&hash)
}
}
}