github.com/aquanetwork/aquachain@v1.7.8/core/tx_list.go (about)

     1  // Copyright 2016 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The aquachain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the aquachain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package core
    18  
    19  import (
    20  	"container/heap"
    21  	"math"
    22  	"math/big"
    23  	"sort"
    24  
    25  	"gitlab.com/aquachain/aquachain/common"
    26  	"gitlab.com/aquachain/aquachain/common/log"
    27  	"gitlab.com/aquachain/aquachain/core/types"
    28  )
    29  
    30  // nonceHeap is a heap.Interface implementation over 64bit unsigned integers for
    31  // retrieving sorted transactions from the possibly gapped future queue.
    32  type nonceHeap []uint64
    33  
    34  func (h nonceHeap) Len() int           { return len(h) }
    35  func (h nonceHeap) Less(i, j int) bool { return h[i] < h[j] }
    36  func (h nonceHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
    37  
    38  func (h *nonceHeap) Push(x interface{}) {
    39  	*h = append(*h, x.(uint64))
    40  }
    41  
    42  func (h *nonceHeap) Pop() interface{} {
    43  	old := *h
    44  	n := len(old)
    45  	x := old[n-1]
    46  	*h = old[0 : n-1]
    47  	return x
    48  }
    49  
    50  // txSortedMap is a nonce->transaction hash map with a heap based index to allow
    51  // iterating over the contents in a nonce-incrementing way.
    52  type txSortedMap struct {
    53  	items map[uint64]*types.Transaction // Hash map storing the transaction data
    54  	index *nonceHeap                    // Heap of nonces of all the stored transactions (non-strict mode)
    55  	cache types.Transactions            // Cache of the transactions already sorted
    56  }
    57  
    58  // newTxSortedMap creates a new nonce-sorted transaction map.
    59  func newTxSortedMap() *txSortedMap {
    60  	return &txSortedMap{
    61  		items: make(map[uint64]*types.Transaction),
    62  		index: new(nonceHeap),
    63  	}
    64  }
    65  
    66  // Get retrieves the current transactions associated with the given nonce.
    67  func (m *txSortedMap) Get(nonce uint64) *types.Transaction {
    68  	return m.items[nonce]
    69  }
    70  
    71  // Put inserts a new transaction into the map, also updating the map's nonce
    72  // index. If a transaction already exists with the same nonce, it's overwritten.
    73  func (m *txSortedMap) Put(tx *types.Transaction) {
    74  	nonce := tx.Nonce()
    75  	if m.items[nonce] == nil {
    76  		heap.Push(m.index, nonce)
    77  	}
    78  	m.items[nonce], m.cache = tx, nil
    79  }
    80  
    81  // Forward removes all transactions from the map with a nonce lower than the
    82  // provided threshold. Every removed transaction is returned for any post-removal
    83  // maintenance.
    84  func (m *txSortedMap) Forward(threshold uint64) types.Transactions {
    85  	var removed types.Transactions
    86  
    87  	// Pop off heap items until the threshold is reached
    88  	for m.index.Len() > 0 && (*m.index)[0] < threshold {
    89  		nonce := heap.Pop(m.index).(uint64)
    90  		removed = append(removed, m.items[nonce])
    91  		delete(m.items, nonce)
    92  	}
    93  	// If we had a cached order, shift the front
    94  	if m.cache != nil {
    95  		m.cache = m.cache[len(removed):]
    96  	}
    97  	return removed
    98  }
    99  
   100  // Filter iterates over the list of transactions and removes all of them for which
   101  // the specified function evaluates to true.
   102  func (m *txSortedMap) Filter(filter func(*types.Transaction) bool) types.Transactions {
   103  	var removed types.Transactions
   104  
   105  	// Collect all the transactions to filter out
   106  	for nonce, tx := range m.items {
   107  		if filter(tx) {
   108  			removed = append(removed, tx)
   109  			delete(m.items, nonce)
   110  		}
   111  	}
   112  	// If transactions were removed, the heap and cache are ruined
   113  	if len(removed) > 0 {
   114  		*m.index = make([]uint64, 0, len(m.items))
   115  		for nonce := range m.items {
   116  			*m.index = append(*m.index, nonce)
   117  		}
   118  		heap.Init(m.index)
   119  
   120  		m.cache = nil
   121  	}
   122  	return removed
   123  }
   124  
   125  // Cap places a hard limit on the number of items, returning all transactions
   126  // exceeding that limit.
   127  func (m *txSortedMap) Cap(threshold int) types.Transactions {
   128  	// Short circuit if the number of items is under the limit
   129  	if len(m.items) <= threshold {
   130  		return nil
   131  	}
   132  	// Otherwise gather and drop the highest nonce'd transactions
   133  	var drops types.Transactions
   134  
   135  	sort.Sort(*m.index)
   136  	for size := len(m.items); size > threshold; size-- {
   137  		drops = append(drops, m.items[(*m.index)[size-1]])
   138  		delete(m.items, (*m.index)[size-1])
   139  	}
   140  	*m.index = (*m.index)[:threshold]
   141  	heap.Init(m.index)
   142  
   143  	// If we had a cache, shift the back
   144  	if m.cache != nil {
   145  		m.cache = m.cache[:len(m.cache)-len(drops)]
   146  	}
   147  	return drops
   148  }
   149  
   150  // Remove deletes a transaction from the maintained map, returning whether the
   151  // transaction was found.
   152  func (m *txSortedMap) Remove(nonce uint64) bool {
   153  	// Short circuit if no transaction is present
   154  	_, ok := m.items[nonce]
   155  	if !ok {
   156  		return false
   157  	}
   158  	// Otherwise delete the transaction and fix the heap index
   159  	for i := 0; i < m.index.Len(); i++ {
   160  		if (*m.index)[i] == nonce {
   161  			heap.Remove(m.index, i)
   162  			break
   163  		}
   164  	}
   165  	delete(m.items, nonce)
   166  	m.cache = nil
   167  
   168  	return true
   169  }
   170  
   171  // Ready retrieves a sequentially increasing list of transactions starting at the
   172  // provided nonce that is ready for processing. The returned transactions will be
   173  // removed from the list.
   174  //
   175  // Note, all transactions with nonces lower than start will also be returned to
   176  // prevent getting into and invalid state. This is not something that should ever
   177  // happen but better to be self correcting than failing!
   178  func (m *txSortedMap) Ready(start uint64) types.Transactions {
   179  	// Short circuit if no transactions are available
   180  	if m.index.Len() == 0 || (*m.index)[0] > start {
   181  		return nil
   182  	}
   183  	// Otherwise start accumulating incremental transactions
   184  	var ready types.Transactions
   185  	for next := (*m.index)[0]; m.index.Len() > 0 && (*m.index)[0] == next; next++ {
   186  		ready = append(ready, m.items[next])
   187  		delete(m.items, next)
   188  		heap.Pop(m.index)
   189  	}
   190  	m.cache = nil
   191  
   192  	return ready
   193  }
   194  
   195  // Len returns the length of the transaction map.
   196  func (m *txSortedMap) Len() int {
   197  	return len(m.items)
   198  }
   199  
   200  // Flatten creates a nonce-sorted slice of transactions based on the loosely
   201  // sorted internal representation. The result of the sorting is cached in case
   202  // it's requested again before any modifications are made to the contents.
   203  func (m *txSortedMap) Flatten() types.Transactions {
   204  	// If the sorting was not cached yet, create and cache it
   205  	if m.cache == nil {
   206  		m.cache = make(types.Transactions, 0, len(m.items))
   207  		for _, tx := range m.items {
   208  			m.cache = append(m.cache, tx)
   209  		}
   210  		sort.Sort(types.TxByNonce(m.cache))
   211  	}
   212  	// Copy the cache to prevent accidental modifications
   213  	txs := make(types.Transactions, len(m.cache))
   214  	copy(txs, m.cache)
   215  	return txs
   216  }
   217  
   218  // txList is a "list" of transactions belonging to an account, sorted by account
   219  // nonce. The same type can be used both for storing contiguous transactions for
   220  // the executable/pending queue; and for storing gapped transactions for the non-
   221  // executable/future queue, with minor behavioral changes.
   222  type txList struct {
   223  	strict bool         // Whether nonces are strictly continuous or not
   224  	txs    *txSortedMap // Heap indexed sorted hash map of the transactions
   225  
   226  	costcap *big.Int // Price of the highest costing transaction (reset only if exceeds balance)
   227  	gascap  uint64   // Gas limit of the highest spending transaction (reset only if exceeds block limit)
   228  }
   229  
   230  // newTxList create a new transaction list for maintaining nonce-indexable fast,
   231  // gapped, sortable transaction lists.
   232  func newTxList(strict bool) *txList {
   233  	return &txList{
   234  		strict:  strict,
   235  		txs:     newTxSortedMap(),
   236  		costcap: new(big.Int),
   237  	}
   238  }
   239  
   240  // Overlaps returns whether the transaction specified has the same nonce as one
   241  // already contained within the list.
   242  func (l *txList) Overlaps(tx *types.Transaction) bool {
   243  	return l.txs.Get(tx.Nonce()) != nil
   244  }
   245  
   246  // Add tries to insert a new transaction into the list, returning whether the
   247  // transaction was accepted, and if yes, any previous transaction it replaced.
   248  //
   249  // If the new transaction is accepted into the list, the lists' cost and gas
   250  // thresholds are also potentially updated.
   251  func (l *txList) Add(tx *types.Transaction, priceBump uint64) (bool, *types.Transaction) {
   252  	// If there's an older better transaction, abort
   253  	old := l.txs.Get(tx.Nonce())
   254  	if old != nil {
   255  		threshold := new(big.Int).Div(new(big.Int).Mul(old.GasPrice(), big.NewInt(100+int64(priceBump))), big.NewInt(100))
   256  		// Have to ensure that the new gas price is higher than the old gas
   257  		// price as well as checking the percentage threshold to ensure that
   258  		// this is accurate for low (Wei-level) gas price replacements
   259  		if old.GasPrice().Cmp(tx.GasPrice()) >= 0 || threshold.Cmp(tx.GasPrice()) > 0 {
   260  			return false, nil
   261  		}
   262  	}
   263  	// Otherwise overwrite the old transaction with the current one
   264  	l.txs.Put(tx)
   265  	if cost := tx.Cost(); l.costcap.Cmp(cost) < 0 {
   266  		l.costcap = cost
   267  	}
   268  	if gas := tx.Gas(); l.gascap < gas {
   269  		l.gascap = gas
   270  	}
   271  	return true, old
   272  }
   273  
   274  // Forward removes all transactions from the list with a nonce lower than the
   275  // provided threshold. Every removed transaction is returned for any post-removal
   276  // maintenance.
   277  func (l *txList) Forward(threshold uint64) types.Transactions {
   278  	return l.txs.Forward(threshold)
   279  }
   280  
   281  // Filter removes all transactions from the list with a cost or gas limit higher
   282  // than the provided thresholds. Every removed transaction is returned for any
   283  // post-removal maintenance. Strict-mode invalidated transactions are also
   284  // returned.
   285  //
   286  // This method uses the cached costcap and gascap to quickly decide if there's even
   287  // a point in calculating all the costs or if the balance covers all. If the threshold
   288  // is lower than the costgas cap, the caps will be reset to a new high after removing
   289  // the newly invalidated transactions.
   290  func (l *txList) Filter(costLimit *big.Int, gasLimit uint64) (types.Transactions, types.Transactions) {
   291  	// If all transactions are below the threshold, short circuit
   292  	if l.costcap.Cmp(costLimit) <= 0 && l.gascap <= gasLimit {
   293  		return nil, nil
   294  	}
   295  	l.costcap = new(big.Int).Set(costLimit) // Lower the caps to the thresholds
   296  	l.gascap = gasLimit
   297  
   298  	// Filter out all the transactions above the account's funds
   299  	removed := l.txs.Filter(func(tx *types.Transaction) bool { return tx.Cost().Cmp(costLimit) > 0 || tx.Gas() > gasLimit })
   300  
   301  	// If the list was strict, filter anything above the lowest nonce
   302  	var invalids types.Transactions
   303  
   304  	if l.strict && len(removed) > 0 {
   305  		lowest := uint64(math.MaxUint64)
   306  		for _, tx := range removed {
   307  			if nonce := tx.Nonce(); lowest > nonce {
   308  				lowest = nonce
   309  			}
   310  		}
   311  		invalids = l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > lowest })
   312  	}
   313  	return removed, invalids
   314  }
   315  
   316  // Cap places a hard limit on the number of items, returning all transactions
   317  // exceeding that limit.
   318  func (l *txList) Cap(threshold int) types.Transactions {
   319  	return l.txs.Cap(threshold)
   320  }
   321  
   322  // Remove deletes a transaction from the maintained list, returning whether the
   323  // transaction was found, and also returning any transaction invalidated due to
   324  // the deletion (strict mode only).
   325  func (l *txList) Remove(tx *types.Transaction) (bool, types.Transactions) {
   326  	// Remove the transaction from the set
   327  	nonce := tx.Nonce()
   328  	if removed := l.txs.Remove(nonce); !removed {
   329  		return false, nil
   330  	}
   331  	// In strict mode, filter out non-executable transactions
   332  	if l.strict {
   333  		return true, l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > nonce })
   334  	}
   335  	return true, nil
   336  }
   337  
   338  // Ready retrieves a sequentially increasing list of transactions starting at the
   339  // provided nonce that is ready for processing. The returned transactions will be
   340  // removed from the list.
   341  //
   342  // Note, all transactions with nonces lower than start will also be returned to
   343  // prevent getting into and invalid state. This is not something that should ever
   344  // happen but better to be self correcting than failing!
   345  func (l *txList) Ready(start uint64) types.Transactions {
   346  	return l.txs.Ready(start)
   347  }
   348  
   349  // Len returns the length of the transaction list.
   350  func (l *txList) Len() int {
   351  	return l.txs.Len()
   352  }
   353  
   354  // Empty returns whether the list of transactions is empty or not.
   355  func (l *txList) Empty() bool {
   356  	return l.Len() == 0
   357  }
   358  
   359  // Flatten creates a nonce-sorted slice of transactions based on the loosely
   360  // sorted internal representation. The result of the sorting is cached in case
   361  // it's requested again before any modifications are made to the contents.
   362  func (l *txList) Flatten() types.Transactions {
   363  	return l.txs.Flatten()
   364  }
   365  
   366  // priceHeap is a heap.Interface implementation over transactions for retrieving
   367  // price-sorted transactions to discard when the pool fills up.
   368  type priceHeap []*types.Transaction
   369  
   370  func (h priceHeap) Len() int           { return len(h) }
   371  func (h priceHeap) Less(i, j int) bool { return h[i].GasPrice().Cmp(h[j].GasPrice()) < 0 }
   372  func (h priceHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
   373  
   374  func (h *priceHeap) Push(x interface{}) {
   375  	*h = append(*h, x.(*types.Transaction))
   376  }
   377  
   378  func (h *priceHeap) Pop() interface{} {
   379  	old := *h
   380  	n := len(old)
   381  	x := old[n-1]
   382  	*h = old[0 : n-1]
   383  	return x
   384  }
   385  
   386  // txPricedList is a price-sorted heap to allow operating on transactions pool
   387  // contents in a price-incrementing way.
   388  type txPricedList struct {
   389  	all    *map[common.Hash]*types.Transaction // Pointer to the map of all transactions
   390  	items  *priceHeap                          // Heap of prices of all the stored transactions
   391  	stales int                                 // Number of stale price points to (re-heap trigger)
   392  }
   393  
   394  // newTxPricedList creates a new price-sorted transaction heap.
   395  func newTxPricedList(all *map[common.Hash]*types.Transaction) *txPricedList {
   396  	return &txPricedList{
   397  		all:   all,
   398  		items: new(priceHeap),
   399  	}
   400  }
   401  
   402  // Put inserts a new transaction into the heap.
   403  func (l *txPricedList) Put(tx *types.Transaction) {
   404  	heap.Push(l.items, tx)
   405  }
   406  
   407  // Removed notifies the prices transaction list that an old transaction dropped
   408  // from the pool. The list will just keep a counter of stale objects and update
   409  // the heap if a large enough ratio of transactions go stale.
   410  func (l *txPricedList) Removed() {
   411  	// Bump the stale counter, but exit if still too low (< 25%)
   412  	l.stales++
   413  	if l.stales <= len(*l.items)/4 {
   414  		return
   415  	}
   416  	// Seems we've reached a critical number of stale transactions, reheap
   417  	reheap := make(priceHeap, 0, len(*l.all))
   418  
   419  	l.stales, l.items = 0, &reheap
   420  	for _, tx := range *l.all {
   421  		*l.items = append(*l.items, tx)
   422  	}
   423  	heap.Init(l.items)
   424  }
   425  
   426  // Cap finds all the transactions below the given price threshold, drops them
   427  // from the priced list and returs them for further removal from the entire pool.
   428  func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transactions {
   429  	drop := make(types.Transactions, 0, 128) // Remote underpriced transactions to drop
   430  	save := make(types.Transactions, 0, 64)  // Local underpriced transactions to keep
   431  
   432  	for len(*l.items) > 0 {
   433  		// Discard stale transactions if found during cleanup
   434  		tx := heap.Pop(l.items).(*types.Transaction)
   435  		if _, ok := (*l.all)[tx.Hash()]; !ok {
   436  			l.stales--
   437  			continue
   438  		}
   439  		// Stop the discards if we've reached the threshold
   440  		if tx.GasPrice().Cmp(threshold) >= 0 {
   441  			save = append(save, tx)
   442  			break
   443  		}
   444  		// Non stale transaction found, discard unless local
   445  		if local.containsTx(tx) {
   446  			save = append(save, tx)
   447  		} else {
   448  			drop = append(drop, tx)
   449  		}
   450  	}
   451  	for _, tx := range save {
   452  		heap.Push(l.items, tx)
   453  	}
   454  	return drop
   455  }
   456  
   457  // Underpriced checks whether a transaction is cheaper than (or as cheap as) the
   458  // lowest priced transaction currently being tracked.
   459  func (l *txPricedList) Underpriced(tx *types.Transaction, local *accountSet) bool {
   460  	// Local transactions cannot be underpriced
   461  	if local.containsTx(tx) {
   462  		return false
   463  	}
   464  	// Discard stale price points if found at the heap start
   465  	for len(*l.items) > 0 {
   466  		head := []*types.Transaction(*l.items)[0]
   467  		if _, ok := (*l.all)[head.Hash()]; !ok {
   468  			l.stales--
   469  			heap.Pop(l.items)
   470  			continue
   471  		}
   472  		break
   473  	}
   474  	// Check if the transaction is underpriced or not
   475  	if len(*l.items) == 0 {
   476  		log.Error("Pricing query for empty pool") // This cannot happen, print to catch programming errors
   477  		return false
   478  	}
   479  	cheapest := []*types.Transaction(*l.items)[0]
   480  	return cheapest.GasPrice().Cmp(tx.GasPrice()) >= 0
   481  }
   482  
   483  // Discard finds a number of most underpriced transactions, removes them from the
   484  // priced list and returns them for further removal from the entire pool.
   485  func (l *txPricedList) Discard(count int, local *accountSet) types.Transactions {
   486  	drop := make(types.Transactions, 0, count) // Remote underpriced transactions to drop
   487  	save := make(types.Transactions, 0, 64)    // Local underpriced transactions to keep
   488  
   489  	for len(*l.items) > 0 && count > 0 {
   490  		// Discard stale transactions if found during cleanup
   491  		tx := heap.Pop(l.items).(*types.Transaction)
   492  		if _, ok := (*l.all)[tx.Hash()]; !ok {
   493  			l.stales--
   494  			continue
   495  		}
   496  		// Non stale transaction found, discard unless local
   497  		if local.containsTx(tx) {
   498  			save = append(save, tx)
   499  		} else {
   500  			drop = append(drop, tx)
   501  			count--
   502  		}
   503  	}
   504  	for _, tx := range save {
   505  		heap.Push(l.items, tx)
   506  	}
   507  	return drop
   508  }