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 log.WithFields(log.Fields{"module": "ProcessTransaction", "error": "pegin-already-claimed"}).Error("ProcessTransaction error")
201 return false, errors.New("pegin-already-claimed")
206 StatusFail: statusFail,
207 Weight: tx.SerializedSize,
211 requireParents, err := tp.checkOrphanUtxos(tx)
216 if len(requireParents) > 0 {
217 return true, tp.addOrphan(txD, requireParents)
219 if err := tp.addTransaction(txD); err != nil {
223 tp.processOrphans(txD)
227 func (tp *TxPool) isWithdrawSpent(tx *types.Tx) bool {
228 for key, value := range tx.Entries {
229 switch value.(type) {
231 return tp.store.IsWithdrawSpent(&key)
240 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
241 if len(tp.orphans) >= maxOrphanNum {
245 orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
246 tp.orphans[txD.Tx.ID] = orphan
247 for _, hash := range requireParents {
248 if _, ok := tp.orphansByPrev[*hash]; !ok {
249 tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
251 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
256 func (tp *TxPool) addTransaction(txD *TxDesc) error {
257 if len(tp.pool) >= maxNewTxNum {
262 txD.Added = time.Now()
264 for _, id := range tx.ResultIds {
265 output, err := tx.Output(*id)
267 // error due to it's a retirement, utxo doesn't care this output type so skip it
270 if !txD.StatusFail || *output.Source.Value.AssetId == *consensus.BTMAssetID {
275 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
276 tp.msgCh <- &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}
277 log.WithField("tx_id", tx.ID.String()).Debug("Add tx to mempool")
281 func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
282 view := state.NewUtxoViewpoint()
283 if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
287 hashes := []*bc.Hash{}
288 for _, hash := range tx.SpentOutputIDs {
289 if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
290 hashes = append(hashes, &hash)
296 func (tp *TxPool) orphanExpireWorker() {
297 ticker := time.NewTicker(orphanExpireScanInterval)
298 for now := range ticker.C {
303 func (tp *TxPool) processOrphans(txD *TxDesc) {
304 processOrphans := []*orphanTx{}
305 addRely := func(tx *types.Tx) {
306 for _, outHash := range tx.ResultIds {
307 orphans, ok := tp.orphansByPrev[*outHash]
312 for _, orphan := range orphans {
313 processOrphans = append(processOrphans, orphan)
315 delete(tp.orphansByPrev, *outHash)
320 for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
321 processOrphan := processOrphans[0]
322 requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
324 log.WithField("err", err).Error("processOrphans got unexpect error")
328 if len(requireParents) == 0 {
329 addRely(processOrphan.Tx)
330 tp.removeOrphan(&processOrphan.Tx.ID)
331 tp.addTransaction(processOrphan.TxDesc)
336 func (tp *TxPool) removeOrphan(hash *bc.Hash) {
337 orphan, ok := tp.orphans[*hash]
342 for _, spend := range orphan.Tx.SpentOutputIDs {
343 orphans, ok := tp.orphansByPrev[spend]
348 if delete(orphans, *hash); len(orphans) == 0 {
349 delete(tp.orphansByPrev, spend)
352 delete(tp.orphans, *hash)