9 "github.com/golang/groupcache/lru"
10 log "github.com/sirupsen/logrus"
12 "github.com/bytom/consensus"
13 "github.com/bytom/protocol/bc"
14 "github.com/bytom/protocol/bc/types"
15 "github.com/bytom/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.RUnlock()
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.RUnlock()
201 StatusFail: statusFail,
202 Weight: tx.SerializedSize,
206 requireParents, err := tp.checkOrphanUtxos(tx)
211 if len(requireParents) > 0 {
212 return true, tp.addOrphan(txD, requireParents)
215 if err := tp.addTransaction(txD); err != nil {
219 tp.processOrphans(txD)
223 func (tp *TxPool) addOrphan(txD *TxDesc, requireParents []*bc.Hash) error {
224 if len(tp.orphans) >= maxOrphanNum {
228 orphan := &orphanTx{txD, time.Now().Add(orphanTTL)}
229 tp.orphans[txD.Tx.ID] = orphan
230 for _, hash := range requireParents {
231 if _, ok := tp.orphansByPrev[*hash]; !ok {
232 tp.orphansByPrev[*hash] = make(map[bc.Hash]*orphanTx)
234 tp.orphansByPrev[*hash][txD.Tx.ID] = orphan
239 func (tp *TxPool) addTransaction(txD *TxDesc) error {
240 if len(tp.pool) >= maxNewTxNum {
245 txD.Added = time.Now()
247 for _, id := range tx.ResultIds {
248 output, err := tx.Output(*id)
250 // error due to it's a retirement, utxo doesn't care this output type so skip it
253 if !txD.StatusFail || *output.Source.Value.AssetId == *consensus.BTMAssetID {
258 atomic.StoreInt64(&tp.lastUpdated, time.Now().Unix())
259 tp.msgCh <- &TxPoolMsg{TxDesc: txD, MsgType: MsgNewTx}
260 log.WithField("tx_id", tx.ID.String()).Debug("Add tx to mempool")
264 func (tp *TxPool) checkOrphanUtxos(tx *types.Tx) ([]*bc.Hash, error) {
265 view := state.NewUtxoViewpoint()
266 if err := tp.store.GetTransactionsUtxo(view, []*bc.Tx{tx.Tx}); err != nil {
270 hashes := []*bc.Hash{}
271 for _, hash := range tx.SpentOutputIDs {
272 if !view.CanSpend(&hash) && tp.utxo[hash] == nil {
273 hashes = append(hashes, &hash)
279 func (tp *TxPool) orphanExpireWorker() {
280 ticker := time.NewTicker(orphanExpireScanInterval)
281 for now := range ticker.C {
286 func (tp *TxPool) processOrphans(txD *TxDesc) {
287 processOrphans := []*orphanTx{}
288 addRely := func(tx *types.Tx) {
289 for _, outHash := range tx.ResultIds {
290 orphans, ok := tp.orphansByPrev[*outHash]
295 for _, orphan := range orphans {
296 processOrphans = append(processOrphans, orphan)
298 delete(tp.orphansByPrev, *outHash)
303 for ; len(processOrphans) > 0; processOrphans = processOrphans[1:] {
304 processOrphan := processOrphans[0]
305 requireParents, err := tp.checkOrphanUtxos(processOrphan.Tx)
307 log.WithField("err", err).Error("processOrphans got unexpect error")
311 if len(requireParents) == 0 {
312 addRely(processOrphan.Tx)
313 tp.removeOrphan(&processOrphan.Tx.ID)
314 tp.addTransaction(processOrphan.TxDesc)
319 func (tp *TxPool) removeOrphan(hash *bc.Hash) {
320 orphan, ok := tp.orphans[*hash]
325 for _, spend := range orphan.Tx.SpentOutputIDs {
326 orphans, ok := tp.orphansByPrev[spend]
331 if delete(orphans, *hash); len(orphans) == 0 {
332 delete(tp.orphansByPrev, spend)
335 delete(tp.orphans, *hash)