github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/txpool/orgchain/subtx_queue.go (about) 1 package orgchain 2 3 import ( 4 "sort" 5 "sync" 6 "time" 7 8 "github.com/sixexorg/magnetic-ring/common" 9 "github.com/sixexorg/magnetic-ring/core/orgchain/types" 10 ) 11 12 /* 13 Transaction queue 14 */ 15 type SubTxQueue struct { 16 sync.RWMutex 17 txs map[int64]*queueTx 18 txhashMp map[common.Hash]int64 19 } 20 21 type Int64Slice []int64 22 23 func (p Int64Slice) Len() int { return len(p) } 24 func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] } 25 func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 26 27 type queueTx struct { 28 tx *types.Transaction 29 quTime int64 30 } 31 32 func newQueueTx(tx *types.Transaction) *queueTx { 33 qt := new(queueTx) 34 qt.tx = tx 35 qt.quTime = time.Now().UnixNano() 36 return qt 37 } 38 39 func NewSubTxQueue() *SubTxQueue { 40 queue := new(SubTxQueue) 41 queue.txs = make(map[int64]*queueTx) 42 queue.txhashMp = make(map[common.Hash]int64) 43 return queue 44 } 45 46 /** 47 Add a deal to the end of the queue 48 */ 49 func (queue *SubTxQueue) Enqueue(tx *types.Transaction) { 50 queue.Lock() 51 defer queue.Unlock() 52 qt := newQueueTx(tx) 53 queue.txs[qt.quTime] = qt 54 queue.txhashMp[tx.Hash()] = qt.quTime 55 } 56 57 /** 58 Remove and remove the transaction from the queue head 59 */ 60 func (queue *SubTxQueue) Dequeue() *types.Transaction { 61 if len(queue.txs) < 1 { 62 return nil 63 } 64 queue.Lock() 65 defer queue.Unlock() 66 67 timearr := make(Int64Slice, 0) 68 69 for k, _ := range queue.txs { 70 timearr = append(timearr, k) 71 } 72 73 sort.Sort(timearr) 74 75 got := queue.txs[timearr[0]] 76 delete(queue.txs, got.quTime) 77 delete(queue.txhashMp, got.tx.Hash()) 78 79 return got.tx 80 } 81 82 func (queue *SubTxQueue) Remove(hash common.Hash) *types.Transaction { 83 queue.Lock() 84 defer queue.Unlock() 85 86 if len(queue.txs) < 1 { 87 return nil 88 } 89 90 if tm, ok := queue.txhashMp[hash]; ok { 91 got := queue.txs[tm] 92 delete(queue.txs, got.quTime) 93 delete(queue.txhashMp, got.tx.Hash()) 94 return got.tx 95 } 96 97 return nil 98 } 99 100 /** 101 Determine if the transaction is empty 102 */ 103 func (q *SubTxQueue) IsEmpty() bool { 104 return len(q.txs) == 0 105 } 106 107 /** 108 Get the current number of transactions in the queue 109 */ 110 func (pool *SubTxQueue) Size() int { 111 return len(pool.txs) 112 }