OSDN Git Service

feat: add cross-chain output (#56)
[bytom/vapor.git] / protocol / txpool.go
1 package protocol
2
3 import (
4         "errors"
5         "sync"
6         "sync/atomic"
7         "time"
8
9         "github.com/golang/groupcache/lru"
10         log "github.com/sirupsen/logrus"
11
12         "github.com/vapor/consensus"
13         "github.com/vapor/event"
14         "github.com/vapor/protocol/bc"
15         "github.com/vapor/protocol/bc/types"
16         "github.com/vapor/protocol/state"
17 )
18
19 // msg type
20 const (
21         MsgNewTx = iota
22         MsgRemoveTx
23         logModule = "protocol"
24 )
25
26 var (
27         maxCachedErrTxs = 1000
28         maxMsgChSize    = 1000
29         maxNewTxNum     = 10000
30         maxOrphanNum    = 2000
31
32         orphanTTL                = 10 * time.Minute
33         orphanExpireScanInterval = 3 * time.Minute
34
35         // ErrTransactionNotExist is the pre-defined error message
36         ErrTransactionNotExist = errors.New("transaction are not existed in the mempool")
37         // ErrPoolIsFull indicates the pool is full
38         ErrPoolIsFull = errors.New("transaction pool reach the max number")
39         // ErrDustTx indicates transaction is dust tx
40         ErrDustTx = errors.New("transaction is dust tx")
41 )
42
43 type TxMsgEvent struct{ TxMsg *TxPoolMsg }
44
45 // TxDesc store tx and related info for mining strategy
46 type TxDesc struct {
47         Tx         *types.Tx `json:"transaction"`
48         Added      time.Time `json:"-"`
49         StatusFail bool      `json:"status_fail"`
50         Height     uint64    `json:"-"`
51         Weight     uint64    `json:"-"`
52         Fee        uint64    `json:"-"`
53 }
54
55 // TxPoolMsg is use for notify pool changes
56 type TxPoolMsg struct {
57         *TxDesc
58         MsgType int
59 }
60
61 type orphanTx struct {
62         *TxDesc
63         expiration time.Time
64 }
65
66 // TxPool is use for store the unconfirmed transaction
67 type TxPool struct {
68         lastUpdated     int64
69         mtx             sync.RWMutex
70         store           Store
71         pool            map[bc.Hash]*TxDesc
72         utxo            map[bc.Hash]*types.Tx
73         orphans         map[bc.Hash]*orphanTx
74         orphansByPrev   map[bc.Hash]map[bc.Hash]*orphanTx
75         errCache        *lru.Cache
76         eventDispatcher *event.Dispatcher
77 }
78
79 // NewTxPool init a new TxPool
80 func NewTxPool(store Store, dispatcher *event.Dispatcher) *TxPool {
81         tp := &TxPool{
82                 lastUpdated:     time.Now().Unix(),
83                 store:           store,
84                 pool:            make(map[bc.Hash]*TxDesc),
85                 utxo:            make(map[bc.Hash]*types.Tx),
86                 orphans:         make(map[bc.Hash]*orphanTx),
87                 orphansByPrev:   make(map[bc.Hash]map[bc.Hash]*orphanTx),
88                 errCache:        lru.New(maxCachedErrTxs),
89                 eventDispatcher: dispatcher,
90         }
91         go tp.orphanExpireWorker()
92         return tp
93 }
94
95 // AddErrCache add a failed transaction record to lru cache
96 func (tp *TxPool) AddErrCache(txHash *bc.Hash, err error) {
97         tp.mtx.Lock()
98         defer tp.mtx.Unlock()
99
100         tp.errCache.Add(txHash, err)
101 }
102
103 // ExpireOrphan expire all the orphans that before the input time range
104 func (tp *TxPool) ExpireOrphan(now time.Time) {
105         tp.mtx.Lock()
106         defer tp.mtx.Unlock()
107
108         for hash, orphan := range tp.orphans {
109                 if orphan.expiration.Before(now) {
110                         tp.removeOrphan(&hash)
111                 }
112         }
113 }
114
115 // GetErrCache return the error of the transaction
116 func (tp *TxPool) GetErrCache(txHash *bc.Hash) error {
117         tp.mtx.Lock()
118         defer tp.mtx.Unlock()
119
120         v, ok := tp.errCache.Get(txHash)
121         if !ok {
122                 return nil
123         }
124         return v.(error)
125 }
126
127 // RemoveTransaction remove a transaction from the pool
128 func (tp *TxPool) RemoveTransaction(txHash *bc.Hash) {
129         tp.mtx.Lock()
130         defer tp.mtx.Unlock()
131
132         txD, ok := tp.pool[*txHash]
133         if !ok {
134                 return
135         }
136
137         for _, output := range txD.Tx.ResultIds {
138                 delete(tp.utxo, *output)
139         }
140         delete(tp.pool, *txHash)
141
142         atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
143         tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgRemoveTx}})
144         log.WithFields(log.Fields{"module": logModule, "tx_id": txHash}).Debug("remove tx from mempool")
145 }
146
147 // GetTransaction return the TxDesc by hash
148 func (tp *TxPool) GetTransaction(txHash *bc.Hash) (*TxDesc, error) {
149         tp.mtx.RLock()
150         defer tp.mtx.RUnlock()
151
152         if txD, ok := tp.pool[*txHash]; ok {
153                 return txD, nil
154         }
155         return nil, ErrTransactionNotExist
156 }
157
158 // GetTransactions return all the transactions in the pool
159 func (tp *TxPool) GetTransactions() []*TxDesc {
160         tp.mtx.RLock()
161         defer tp.mtx.RUnlock()
162
163         txDs := make([]*TxDesc, len(tp.pool))
164         i := 0
165         for _, desc := range tp.pool {
166                 txDs[i] = desc
167                 i++
168         }
169         return txDs
170 }
171
172 // IsTransactionInPool check wheather a transaction in pool or not
173 func (tp *TxPool) IsTransactionInPool(txHash *bc.Hash) bool {
174         tp.mtx.RLock()
175         defer tp.mtx.RUnlock()
176
177         _, ok := tp.pool[*txHash]
178         return ok
179 }
180
181 // IsTransactionInErrCache check wheather a transaction in errCache or not
182 func (tp *TxPool) IsTransactionInErrCache(txHash *bc.Hash) bool {
183         tp.mtx.RLock()
184         defer tp.mtx.RUnlock()
185
186         _, ok := tp.errCache.Get(txHash)
187         return ok
188 }
189
190 // HaveTransaction IsTransactionInErrCache check is  transaction in errCache or pool
191 func (tp *TxPool) HaveTransaction(txHash *bc.Hash) bool {
192         return tp.IsTransactionInPool(txHash) || tp.IsTransactionInErrCache(txHash)
193 }
194
195 func isTransactionNoBtmInput(tx *types.Tx) bool {
196         for _, input := range tx.TxData.Inputs {
197                 if input.AssetID() == *consensus.BTMAssetID {
198                         return false
199                 }
200         }
201         return true
202 }
203
204 func isTransactionZeroOutput(tx *types.Tx) bool {
205         for _, output := range tx.TxData.Outputs {
206                 value := output.AssetAmount()
207                 if value.Amount == uint64(0) {
208                         return true
209                 }
210         }
211         return false
212 }
213
214 func (tp *TxPool) IsDust(tx *types.Tx) bool {
215         return isTransactionNoBtmInput(tx) || isTransactionZeroOutput(tx)
216 }
217
218 func (tp *TxPool) processTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
219         tp.mtx.Lock()
220         defer tp.mtx.Unlock()
221
222         txD := &TxDesc{
223                 Tx:         tx,
224                 StatusFail: statusFail,
225                 Weight:     tx.SerializedSize,
226                 Height:     height,
227                 Fee:        fee,
228         }
229         requireParents, err := tp.checkOrphanUtxos(tx)
230         if err != nil {
231                 return false, err
232         }
233
234         if len(requireParents) > 0 {
235                 return true, tp.addOrphan(txD, requireParents)
236         }
237
238         if err := tp.addTransaction(txD); err != nil {
239                 return false, err
240         }
241
242         tp.processOrphans(txD)
243         return false, nil
244 }
245
246 // ProcessTransaction is the main entry for txpool handle new tx, ignore dust tx.
247 func (tp *TxPool) ProcessTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
248         if tp.IsDust(tx) {
249                 log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Warn("dust tx")
250                 return false, nil
251         }
252         return tp.processTransaction(tx, statusFail, height, fee)
253 }
254
255 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
256         if len(tp.orphans) >= maxOrphanNum {
257                 return ErrPoolIsFull
258         }
259
260         orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
261         tp.orphans[txD.Tx.ID] = orphan
262         for _, hash := range requireParents {
263                 if _, ok := tp.orphansByPrev[*hash]; !ok {
264                         tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
265                 }
266                 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
267         }
268         return nil
269 }
270
271 func (tp *TxPool) addTransaction(txD *TxDesc) error {
272         if len(tp.pool) >= maxNewTxNum {
273                 return ErrPoolIsFull
274         }
275
276         tx := txD.Tx
277         txD.Added = time.Now()
278         tp.pool[tx.ID] = txD
279         for _, id := range tx.ResultIds {
280                 output, err := tx.IntraChainOutput(*id)
281                 if err != nil {
282                         // error due to it's a retirement, utxo doesn't care this output type so skip it
283                         continue
284                 }
285                 if !txD.StatusFail || *output.Source.Value.AssetId == *consensus.BTMAssetID {
286                         tp.utxo[*id] = tx
287                 }
288         }
289
290         atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
291         tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}})
292         log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Debug("Add tx to mempool")
293         return nil
294 }
295
296 func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
297         view := state.NewUtxoViewpoint()
298         if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
299                 return nil, err
300         }
301
302         hashes := []*bc.Hash{}
303         for _, hash := range tx.SpentOutputIDs {
304                 if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
305                         hashes = append(hashes, &hash)
306                 }
307         }
308         return hashes, nil
309 }
310
311 func (tp *TxPool) orphanExpireWorker() {
312         ticker := time.NewTicker(orphanExpireScanInterval)
313         defer ticker.Stop()
314
315         for now := range ticker.C {
316                 tp.ExpireOrphan(now)
317         }
318 }
319
320 func (tp *TxPool) processOrphans(txD *TxDesc) {
321         processOrphans := []*orphanTx{}
322         addRely := func(tx *types.Tx) {
323                 for _, outHash := range tx.ResultIds {
324                         orphans, ok := tp.orphansByPrev[*outHash]
325                         if !ok {
326                                 continue
327                         }
328
329                         for _, orphan := range orphans {
330                                 processOrphans = append(processOrphans, orphan)
331                         }
332                         delete(tp.orphansByPrev, *outHash)
333                 }
334         }
335
336         addRely(txD.Tx)
337         for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
338                 processOrphan := processOrphans[0]
339                 requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
340                 if err != nil {
341                         log.WithFields(log.Fields{"module": logModule, "err": err}).Error("processOrphans got unexpect error")
342                         continue
343                 }
344
345                 if len(requireParents) == 0 {
346                         addRely(processOrphan.Tx)
347                         tp.removeOrphan(&processOrphan.Tx.ID)
348                         tp.addTransaction(processOrphan.TxDesc)
349                 }
350         }
351 }
352
353 func (tp *TxPool) removeOrphan(hash *bc.Hash) {
354         orphan, ok := tp.orphans[*hash]
355         if !ok {
356                 return
357         }
358
359         for _, spend := range orphan.Tx.SpentOutputIDs {
360                 orphans, ok := tp.orphansByPrev[spend]
361                 if !ok {
362                         continue
363                 }
364
365                 if delete(orphans, *hash); len(orphans) == 0 {
366                         delete(tp.orphansByPrev, spend)
367                 }
368         }
369         delete(tp.orphans, *hash)
370 }