OSDN Git Service

update fedProg (#330)
[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     = 65536
30         maxOrphanNum    = 32768
31
32         orphanTTL                = 60 * time.Second
33         orphanExpireScanInterval = 30 * time.Second
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 isTransactionZeroOutput(tx *types.Tx) bool {
196         for _, output := range tx.TxData.Outputs {
197                 if value := output.AssetAmount(); value.Amount == uint64(0) {
198                         return true
199                 }
200         }
201         return false
202 }
203
204 func (tp *TxPool) IsDust(tx *types.Tx) bool {
205         return isTransactionZeroOutput(tx)
206 }
207
208 func (tp *TxPool) processTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
209         tp.mtx.Lock()
210         defer tp.mtx.Unlock()
211
212         txD := &TxDesc{
213                 Tx:         tx,
214                 StatusFail: statusFail,
215                 Weight:     tx.SerializedSize,
216                 Height:     height,
217                 Fee:        fee,
218         }
219         requireParents, err := tp.checkOrphanUtxos(tx)
220         if err != nil {
221                 return false, err
222         }
223
224         if len(requireParents) > 0 {
225                 return true, tp.addOrphan(txD, requireParents)
226         }
227
228         if err := tp.addTransaction(txD); err != nil {
229                 return false, err
230         }
231
232         tp.processOrphans(txD)
233         return false, nil
234 }
235
236 // ProcessTransaction is the main entry for txpool handle new tx, ignore dust tx.
237 func (tp *TxPool) ProcessTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
238         if tp.IsDust(tx) {
239                 log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Warn("dust tx")
240                 return false, nil
241         }
242         return tp.processTransaction(tx, statusFail, height, fee)
243 }
244
245 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
246         if len(tp.orphans) >= maxOrphanNum {
247                 return ErrPoolIsFull
248         }
249
250         orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
251         tp.orphans[txD.Tx.ID] = orphan
252         for _, hash := range requireParents {
253                 if _, ok := tp.orphansByPrev[*hash]; !ok {
254                         tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
255                 }
256                 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
257         }
258         return nil
259 }
260
261 func (tp *TxPool) addTransaction(txD *TxDesc) error {
262         if len(tp.pool) >= maxNewTxNum {
263                 return ErrPoolIsFull
264         }
265
266         tx := txD.Tx
267         txD.Added = time.Now()
268         tp.pool[tx.ID] = txD
269         for _, id := range tx.ResultIds {
270                 outputEntry, err := tx.Entry(*id)
271                 if err != nil {
272                         return err
273                 }
274
275                 var assetID bc.AssetID
276                 switch output := outputEntry.(type) {
277                 case *bc.IntraChainOutput:
278                         assetID = *output.Source.Value.AssetId
279                 case *bc.VoteOutput:
280                         assetID = *output.Source.Value.AssetId
281                 default:
282                         continue
283                 }
284
285                 if !txD.StatusFail || 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 }