9 "github.com/golang/groupcache/lru"
10 log "github.com/sirupsen/logrus"
12 "github.com/vapor/consensus"
13 "github.com/vapor/protocol/bc"
14 "github.com/vapor/protocol/bc/types"
15 "github.com/vapor/protocol/state"
25 maxCachedErrTxs = 1000
30 orphanTTL = 10 * time.Minute
31 orphanExpireScanInterval = 3 * time.Minute
33 // ErrTransactionNotExist is the pre-defined error message
34 ErrTransactionNotExist = errors.New("transaction are not existed in the mempool")
35 // ErrPoolIsFull indicates the pool is full
36 ErrPoolIsFull = errors.New("transaction pool reach the max number")
39 // TxDesc store tx and related info for mining strategy
49 // TxPoolMsg is use for notify pool changes
50 type TxPoolMsg struct {
55 type orphanTx struct {
60 // TxPool is use for store the unconfirmed transaction
65 pool map[bc.Hash]*TxDesc
66 utxo map[bc.Hash]*types.Tx
67 orphans map[bc.Hash]*orphanTx
68 orphansByPrev map[bc.Hash]map[bc.Hash]*orphanTx
73 // NewTxPool init a new TxPool
74 func NewTxPool(store Store) *TxPool {
76 lastUpdated: time.Now().Unix(),
78 pool: make(map[bc.Hash]*TxDesc),
79 utxo: make(map[bc.Hash]*types.Tx),
80 orphans: make(map[bc.Hash]*orphanTx),
81 orphansByPrev: make(map[bc.Hash]map[bc.Hash]*orphanTx),
82 errCache: lru.New(maxCachedErrTxs),
83 msgCh: make(chan *TxPoolMsg, maxMsgChSize),
85 go tp.orphanExpireWorker()
89 // AddErrCache add a failed transaction record to lru cache
90 func (tp *TxPool) AddErrCache(txHash *bc.Hash, err error) {
94 tp.errCache.Add(txHash, err)
97 // ExpireOrphan expire all the orphans that before the input time range
98 func (tp *TxPool) ExpireOrphan(now time.Time) {
100 defer tp.mtx.Unlock()
102 for hash, orphan := range tp.orphans {
103 if orphan.expiration.Before(now) {
104 tp.removeOrphan(&hash)
109 // GetErrCache return the error of the transaction
110 func (tp *TxPool) GetErrCache(txHash *bc.Hash) error {
112 defer tp.mtx.Unlock()
114 v, ok := tp.errCache.Get(txHash)
121 // GetMsgCh return a unconfirmed transaction feed channel
122 func (tp *TxPool) GetMsgCh() <-chan *TxPoolMsg {
126 // RemoveTransaction remove a transaction from the pool
127 func (tp *TxPool) RemoveTransaction(txHash *bc.Hash) {
129 defer tp.mtx.Unlock()
131 txD, ok := tp.pool[*txHash]
136 for _, output := range txD.Tx.ResultIds {
137 delete(tp.utxo, *output)
139 delete(tp.pool, *txHash)
141 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
142 tp.msgCh <- &TxPoolMsg{TxDesc: txD, MsgType: MsgRemoveTx}
143 log.WithField("tx_id", txHash).Debug("remove tx from mempool")
146 // GetTransaction return the TxDesc by hash
147 func (tp *TxPool) GetTransaction(txHash *bc.Hash) (*TxDesc, error) {
149 defer tp.mtx.RUnlock()
151 if txD, ok := tp.pool[*txHash]; ok {
154 return nil, ErrTransactionNotExist
157 // GetTransactions return all the transactions in the pool
158 func (tp *TxPool) GetTransactions() []*TxDesc {
160 defer tp.mtx.RUnlock()
162 txDs := make([]*TxDesc, len(tp.pool))
164 for _, desc := range tp.pool {
171 // IsTransactionInPool check wheather a transaction in pool or not
172 func (tp *TxPool) IsTransactionInPool(txHash *bc.Hash) bool {
174 defer tp.mtx.RUnlock()
176 _, ok := tp.pool[*txHash]
180 // IsTransactionInErrCache check wheather a transaction in errCache or not
181 func (tp *TxPool) IsTransactionInErrCache(txHash *bc.Hash) bool {
183 defer tp.mtx.RUnlock()
185 _, ok := tp.errCache.Get(txHash)
189 // HaveTransaction IsTransactionInErrCache check is transaction in errCache or pool
190 func (tp *TxPool) HaveTransaction(txHash *bc.Hash) bool {
191 return tp.IsTransactionInPool(txHash) || tp.IsTransactionInErrCache(txHash)
194 // ProcessTransaction is the main entry for txpool handle new tx
195 func (tp *TxPool) ProcessTransaction(tx *types.Tx, statusFail bool, height, fee uint64) (bool, error) {
197 defer tp.mtx.Unlock()
199 if tp.isWithdrawSpent(tx) {
200 return false, errors.New("pegin-already-claimed")
205 StatusFail: statusFail,
206 Weight: tx.SerializedSize,
210 requireParents, err := tp.checkOrphanUtxos(tx)
215 if len(requireParents) > 0 {
216 return true, tp.addOrphan(txD, requireParents)
218 if err := tp.addTransaction(txD); err != nil {
222 tp.processOrphans(txD)
226 func (tp *TxPool) isWithdrawSpent(tx *types.Tx) bool {
227 for key, value := range tx.Entries {
228 switch value.(type) {
230 return tp.store.IsWithdrawSpent(&key)
239 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
240 if len(tp.orphans) >= maxOrphanNum {
244 orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
245 tp.orphans[txD.Tx.ID] = orphan
246 for _, hash := range requireParents {
247 if _, ok := tp.orphansByPrev[*hash]; !ok {
248 tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
250 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
255 func (tp *TxPool) addTransaction(txD *TxDesc) error {
256 if len(tp.pool) >= maxNewTxNum {
261 txD.Added = time.Now()
263 for _, id := range tx.ResultIds {
264 output, err := tx.Output(*id)
266 // error due to it's a retirement, utxo doesn't care this output type so skip it
269 if !txD.StatusFail || *output.Source.Value.AssetId == *consensus.BTMAssetID {
274 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
275 tp.msgCh <- &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}
276 log.WithField("tx_id", tx.ID.String()).Debug("Add tx to mempool")
280 func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
281 view := state.NewUtxoViewpoint()
282 if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
286 hashes := []*bc.Hash{}
287 for _, hash := range tx.SpentOutputIDs {
288 if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
289 hashes = append(hashes, &hash)
295 func (tp *TxPool) orphanExpireWorker() {
296 ticker := time.NewTicker(orphanExpireScanInterval)
297 for now := range ticker.C {
302 func (tp *TxPool) processOrphans(txD *TxDesc) {
303 processOrphans := []*orphanTx{}
304 addRely := func(tx *types.Tx) {
305 for _, outHash := range tx.ResultIds {
306 orphans, ok := tp.orphansByPrev[*outHash]
311 for _, orphan := range orphans {
312 processOrphans = append(processOrphans, orphan)
314 delete(tp.orphansByPrev, *outHash)
319 for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
320 processOrphan := processOrphans[0]
321 requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
323 log.WithField("err", err).Error("processOrphans got unexpect error")
327 if len(requireParents) == 0 {
328 addRely(processOrphan.Tx)
329 tp.removeOrphan(&processOrphan.Tx.ID)
330 tp.addTransaction(processOrphan.TxDesc)
335 func (tp *TxPool) removeOrphan(hash *bc.Hash) {
336 orphan, ok := tp.orphans[*hash]
341 for _, spend := range orphan.Tx.SpentOutputIDs {
342 orphans, ok := tp.orphansByPrev[spend]
347 if delete(orphans, *hash); len(orphans) == 0 {
348 delete(tp.orphansByPrev, spend)
351 delete(tp.orphans, *hash)