9 "github.com/golang/groupcache/lru"
10 log "github.com/sirupsen/logrus"
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"
23 logModule = "protocol"
27 maxCachedErrTxs = 1000
32 orphanTTL = 60 * time.Second
33 orphanExpireScanInterval = 30 * time.Second
36 txExpireScanInterval = 20 * time.Minute
38 // ErrTransactionNotExist is the pre-defined error message
39 ErrTransactionNotExist = errors.New("transaction are not existed in the mempool")
40 // ErrPoolIsFull indicates the pool is full
41 ErrPoolIsFull = errors.New("transaction pool reach the max number")
42 // ErrDustTx indicates transaction is dust tx
43 ErrDustTx = errors.New("transaction is dust tx")
46 type TxMsgEvent struct{ TxMsg *TxPoolMsg }
48 // TxDesc store tx and related info for mining strategy
50 Tx *types.Tx `json:"transaction"`
51 Added time.Time `json:"-"`
52 StatusFail bool `json:"status_fail"`
53 Height uint64 `json:"-"`
54 Weight uint64 `json:"-"`
58 // TxPoolMsg is use for notify pool changes
59 type TxPoolMsg struct {
64 type orphanTx struct {
69 // TxPool is use for store the unconfirmed transaction
74 pool map[bc.Hash]*TxDesc
75 utxo map[bc.Hash]*types.Tx
76 orphans map[bc.Hash]*orphanTx
77 orphansByPrev map[bc.Hash]map[bc.Hash]*orphanTx
79 eventDispatcher *event.Dispatcher
82 // NewTxPool init a new TxPool
83 func NewTxPool(store Store, dispatcher *event.Dispatcher) *TxPool {
85 lastUpdated: time.Now().Unix(),
87 pool: make(map[bc.Hash]*TxDesc),
88 utxo: make(map[bc.Hash]*types.Tx),
89 orphans: make(map[bc.Hash]*orphanTx),
90 orphansByPrev: make(map[bc.Hash]map[bc.Hash]*orphanTx),
91 errCache: lru.New(maxCachedErrTxs),
92 eventDispatcher: dispatcher,
94 go tp.orphanExpireWorker()
95 go tp.txExpireWorker()
99 // AddErrCache add a failed transaction record to lru cache
100 func (tp *TxPool) AddErrCache(txHash *bc.Hash, err error) {
102 defer tp.mtx.Unlock()
104 tp.errCache.Add(txHash, err)
107 // expireOrphan expire all the orphans that before the input time range
108 func (tp *TxPool) expireOrphan(now time.Time) {
110 defer tp.mtx.Unlock()
112 for hash, orphan := range tp.orphans {
113 if orphan.expiration.Before(now) {
114 tp.removeOrphan(&hash)
119 // GetErrCache return the error of the transaction
120 func (tp *TxPool) GetErrCache(txHash *bc.Hash) error {
122 defer tp.mtx.Unlock()
124 v, ok := tp.errCache.Get(txHash)
131 // RemoveTransaction remove a transaction from the pool
132 func (tp *TxPool) RemoveTransaction(txHash *bc.Hash) {
134 defer tp.mtx.Unlock()
136 if txD := tp.removeTransaction(txHash); txD != nil {
137 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
138 tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgRemoveTx}})
139 log.WithFields(log.Fields{"module": logModule, "tx_id": txHash}).Debug("remove tx from mempool")
143 func (tp *TxPool) removeTransaction(txHash *bc.Hash) *TxDesc {
144 txD, ok := tp.pool[*txHash]
149 for _, output := range txD.Tx.ResultIds {
150 delete(tp.utxo, *output)
152 delete(tp.pool, *txHash)
156 // GetTransaction return the TxDesc by hash
157 func (tp *TxPool) GetTransaction(txHash *bc.Hash) (*TxDesc, error) {
159 defer tp.mtx.RUnlock()
161 if txD, ok := tp.pool[*txHash]; ok {
164 return nil, ErrTransactionNotExist
167 // GetTransactions return all the transactions in the pool
168 func (tp *TxPool) GetTransactions() []*TxDesc {
170 defer tp.mtx.RUnlock()
172 txDs := make([]*TxDesc, len(tp.pool))
174 for _, desc := range tp.pool {
181 // IsTransactionInPool check wheather a transaction in pool or not
182 func (tp *TxPool) IsTransactionInPool(txHash *bc.Hash) bool {
184 defer tp.mtx.RUnlock()
186 _, ok := tp.pool[*txHash]
190 // IsTransactionInErrCache check wheather a transaction in errCache or not
191 func (tp *TxPool) IsTransactionInErrCache(txHash *bc.Hash) bool {
193 defer tp.mtx.RUnlock()
195 _, ok := tp.errCache.Get(txHash)
199 // HaveTransaction IsTransactionInErrCache check is transaction in errCache or pool
200 func (tp *TxPool) HaveTransaction(txHash *bc.Hash) bool {
201 return tp.IsTransactionInPool(txHash) || tp.IsTransactionInErrCache(txHash)
204 func isTransactionZeroOutput(tx *types.Tx) bool {
205 for _, output := range tx.TxData.Outputs {
206 if value := output.AssetAmount(); value.Amount == uint64(0) {
213 //IsDust checks if a tx has zero output
214 func (tp *TxPool) IsDust(tx *types.Tx) bool {
215 return isTransactionZeroOutput(tx)
218 func (tp *TxPool) processTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
220 defer tp.mtx.Unlock()
224 StatusFail: statusFail,
225 Weight: tx.SerializedSize,
229 requireParents, err := tp.checkOrphanUtxos(tx)
234 if len(requireParents) > 0 {
235 return true, tp.addOrphan(txD, requireParents)
238 if err := tp.addTransaction(txD); err != nil {
242 tp.processOrphans(txD)
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) {
249 log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Warn("dust tx")
252 return tp.processTransaction(tx, statusFail, height, fee)
255 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
256 if len(tp.orphans) >= maxOrphanNum {
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)
266 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
271 func (tp *TxPool) addTransaction(txD *TxDesc) error {
272 if len(tp.pool) >= maxNewTxNum {
277 txD.Added = time.Now()
279 for _, id := range tx.ResultIds {
280 outputEntry, err := tx.Entry(*id)
285 var assetID bc.AssetID
286 switch output := outputEntry.(type) {
287 case *bc.IntraChainOutput:
288 assetID = *output.Source.Value.AssetId
290 assetID = *output.Source.Value.AssetId
295 if !txD.StatusFail || assetID == *consensus.BTMAssetID {
300 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
301 tp.eventDispatcher.Post(TxMsgEvent{TxMsg: &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}})
302 log.WithFields(log.Fields{"module": logModule, "tx_id": tx.ID.String()}).Debug("Add tx to mempool")
306 func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
307 view := state.NewUtxoViewpoint()
308 if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
312 hashes := []*bc.Hash{}
313 for _, hash := range tx.SpentOutputIDs {
314 if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
315 hashes = append(hashes, &hash)
321 func (tp *TxPool) orphanExpireWorker() {
322 ticker := time.NewTicker(orphanExpireScanInterval)
325 for now := range ticker.C {
330 func (tp *TxPool) processOrphans(txD *TxDesc) {
331 processOrphans := []*orphanTx{}
332 addRely := func(tx *types.Tx) {
333 for _, outHash := range tx.ResultIds {
334 orphans, ok := tp.orphansByPrev[*outHash]
339 for _, orphan := range orphans {
340 processOrphans = append(processOrphans, orphan)
342 delete(tp.orphansByPrev, *outHash)
347 for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
348 processOrphan := processOrphans[0]
349 requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
351 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("processOrphans got unexpect error")
355 if len(requireParents) == 0 {
356 addRely(processOrphan.Tx)
357 tp.removeOrphan(&processOrphan.Tx.ID)
358 tp.addTransaction(processOrphan.TxDesc)
363 func (tp *TxPool) removeOrphan(hash *bc.Hash) {
364 orphan, ok := tp.orphans[*hash]
369 for _, spend := range orphan.Tx.SpentOutputIDs {
370 orphans, ok := tp.orphansByPrev[spend]
375 if delete(orphans, *hash); len(orphans) == 0 {
376 delete(tp.orphansByPrev, spend)
379 delete(tp.orphans, *hash)
382 func (tp *TxPool) txExpireWorker() {
383 ticker := time.NewTicker(txExpireScanInterval)
386 for now := range ticker.C {
391 // expireTx expires all the Txs that before the input time range
392 func (tp *TxPool) expireTx(now time.Time) {
394 defer tp.mtx.Unlock()
396 cutOff := now.Add(-txTTL)
397 for hash, txD := range tp.pool {
398 if txD.Added.Before(cutOff) {
399 tp.removeTransaction(&hash)