github.com/pixichain/go-pixicoin@v0.0.0-20220708132717-27ba739265ff/core/tx_list.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum 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 go-ethereum 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 go-ethereum 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  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/log"
    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  *big.Int // 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  		gascap:  new(big.Int),
   238  	}
   239  }
   240  
   241  // Overlaps returns whether the transaction specified has the same nonce as one
   242  // already contained within the list.
   243  func (l *txList) Overlaps(tx *types.Transaction) bool {
   244  	return l.txs.Get(tx.Nonce()) != nil
   245  }
   246  
   247  // Add tries to insert a new transaction into the list, returning whether the
   248  // transaction was accepted, and if yes, any previous transaction it replaced.
   249  //
   250  // If the new transaction is accepted into the list, the lists' cost and gas
   251  // thresholds are also potentially updated.
   252  func (l *txList) Add(tx *types.Transaction, priceBump uint64) (bool, *types.Transaction) {
   253  	// If there's an older better transaction, abort
   254  	old := l.txs.Get(tx.Nonce())
   255  	if old != nil {
   256  		threshold := new(big.Int).Div(new(big.Int).Mul(old.GasPrice(), big.NewInt(100+int64(priceBump))), big.NewInt(100))
   257  		// Have to ensure that the new gas price is higher than the old gas
   258  		// price as well as checking the percentage threshold to ensure that
   259  		// this is accurate for low (Wei-level) gas price replacements
   260  		if old.GasPrice().Cmp(tx.GasPrice()) >= 0 || threshold.Cmp(tx.GasPrice()) > 0 {
   261  			return false, nil
   262  		}
   263  	}
   264  	// Otherwise overwrite the old transaction with the current one
   265  	l.txs.Put(tx)
   266  	if cost := tx.Cost(); l.costcap.Cmp(cost) < 0 {
   267  		l.costcap = cost
   268  	}
   269  	if gas := tx.Gas(); l.gascap.Cmp(gas) < 0 {
   270  		l.gascap = gas
   271  	}
   272  	return true, old
   273  }
   274  
   275  // Forward removes all transactions from the list with a nonce lower than the
   276  // provided threshold. Every removed transaction is returned for any post-removal
   277  // maintenance.
   278  func (l *txList) Forward(threshold uint64) types.Transactions {
   279  	return l.txs.Forward(threshold)
   280  }
   281  
   282  // Filter removes all transactions from the list with a cost or gas limit higher
   283  // than the provided thresholds. Every removed transaction is returned for any
   284  // post-removal maintenance. Strict-mode invalidated transactions are also
   285  // returned.
   286  //
   287  // This method uses the cached costcap and gascap to quickly decide if there's even
   288  // a point in calculating all the costs or if the balance covers all. If the threshold
   289  // is lower than the costgas cap, the caps will be reset to a new high after removing
   290  // the newly invalidated transactions.
   291  func (l *txList) Filter(costLimit, gasLimit *big.Int) (types.Transactions, types.Transactions) {
   292  	// If all transactions are below the threshold, short circuit
   293  	if l.costcap.Cmp(costLimit) <= 0 && l.gascap.Cmp(gasLimit) <= 0 {
   294  		return nil, nil
   295  	}
   296  	l.costcap = new(big.Int).Set(costLimit) // Lower the caps to the thresholds
   297  	l.gascap = new(big.Int).Set(gasLimit)
   298  
   299  	// Filter out all the transactions above the account's funds
   300  	removed := l.txs.Filter(func(tx *types.Transaction) bool { return tx.Cost().Cmp(costLimit) > 0 || tx.Gas().Cmp(gasLimit) > 0 })
   301  
   302  	// If the list was strict, filter anything above the lowest nonce
   303  	var invalids types.Transactions
   304  
   305  	if l.strict && len(removed) > 0 {
   306  		lowest := uint64(math.MaxUint64)
   307  		for _, tx := range removed {
   308  			if nonce := tx.Nonce(); lowest > nonce {
   309  				lowest = nonce
   310  			}
   311  		}
   312  		invalids = l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > lowest })
   313  	}
   314  	return removed, invalids
   315  }
   316  
   317  // Cap places a hard limit on the number of items, returning all transactions
   318  // exceeding that limit.
   319  func (l *txList) Cap(threshold int) types.Transactions {
   320  	return l.txs.Cap(threshold)
   321  }
   322  
   323  // Remove deletes a transaction from the maintained list, returning whether the
   324  // transaction was found, and also returning any transaction invalidated due to
   325  // the deletion (strict mode only).
   326  func (l *txList) Remove(tx *types.Transaction) (bool, types.Transactions) {
   327  	// Remove the transaction from the set
   328  	nonce := tx.Nonce()
   329  	if removed := l.txs.Remove(nonce); !removed {
   330  		return false, nil
   331  	}
   332  	// In strict mode, filter out non-executable transactions
   333  	if l.strict {
   334  		return true, l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > nonce })
   335  	}
   336  	return true, nil
   337  }
   338  
   339  // Ready retrieves a sequentially increasing list of transactions starting at the
   340  // provided nonce that is ready for processing. The returned transactions will be
   341  // removed from the list.
   342  //
   343  // Note, all transactions with nonces lower than start will also be returned to
   344  // prevent getting into and invalid state. This is not something that should ever
   345  // happen but better to be self correcting than failing!
   346  func (l *txList) Ready(start uint64) types.Transactions {
   347  	return l.txs.Ready(start)
   348  }
   349  
   350  // Len returns the length of the transaction list.
   351  func (l *txList) Len() int {
   352  	return l.txs.Len()
   353  }
   354  
   355  // Empty returns whether the list of transactions is empty or not.
   356  func (l *txList) Empty() bool {
   357  	return l.Len() == 0
   358  }
   359  
   360  // Flatten creates a nonce-sorted slice of transactions based on the loosely
   361  // sorted internal representation. The result of the sorting is cached in case
   362  // it's requested again before any modifications are made to the contents.
   363  func (l *txList) Flatten() types.Transactions {
   364  	return l.txs.Flatten()
   365  }
   366  
   367  // priceHeap is a heap.Interface implementation over transactions for retrieving
   368  // price-sorted transactions to discard when the pool fills up.
   369  type priceHeap []*types.Transaction
   370  
   371  func (h priceHeap) Len() int           { return len(h) }
   372  func (h priceHeap) Less(i, j int) bool { return h[i].GasPrice().Cmp(h[j].GasPrice()) < 0 }
   373  func (h priceHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
   374  
   375  func (h *priceHeap) Push(x interface{}) {
   376  	*h = append(*h, x.(*types.Transaction))
   377  }
   378  
   379  func (h *priceHeap) Pop() interface{} {
   380  	old := *h
   381  	n := len(old)
   382  	x := old[n-1]
   383  	*h = old[0 : n-1]
   384  	return x
   385  }
   386  
   387  // txPricedList is a price-sorted heap to allow operating on transactions pool
   388  // contents in a price-incrementing way.
   389  type txPricedList struct {
   390  	all    *map[common.Hash]*types.Transaction // Pointer to the map of all transactions
   391  	items  *priceHeap                          // Heap of prices of all the stored transactions
   392  	stales int                                 // Number of stale price points to (re-heap trigger)
   393  }
   394  
   395  // newTxPricedList creates a new price-sorted transaction heap.
   396  func newTxPricedList(all *map[common.Hash]*types.Transaction) *txPricedList {
   397  	return &txPricedList{
   398  		all:   all,
   399  		items: new(priceHeap),
   400  	}
   401  }
   402  
   403  // Put inserts a new transaction into the heap.
   404  func (l *txPricedList) Put(tx *types.Transaction) {
   405  	heap.Push(l.items, tx)
   406  }
   407  
   408  // Removed notifies the prices transaction list that an old transaction dropped
   409  // from the pool. The list will just keep a counter of stale objects and update
   410  // the heap if a large enough ratio of transactions go stale.
   411  func (l *txPricedList) Removed() {
   412  	// Bump the stale counter, but exit if still too low (< 25%)
   413  	l.stales++
   414  	if l.stales <= len(*l.items)/4 {
   415  		return
   416  	}
   417  	// Seems we've reached a critical number of stale transactions, reheap
   418  	reheap := make(priceHeap, 0, len(*l.all))
   419  
   420  	l.stales, l.items = 0, &reheap
   421  	for _, tx := range *l.all {
   422  		*l.items = append(*l.items, tx)
   423  	}
   424  	heap.Init(l.items)
   425  }
   426  
   427  // Cap finds all the transactions below the given price threshold, drops them
   428  // from the priced list and returs them for further removal from the entire pool.
   429  func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transactions {
   430  	drop := make(types.Transactions, 0, 128) // Remote underpriced transactions to drop
   431  	save := make(types.Transactions, 0, 64)  // Local underpriced transactions to keep
   432  
   433  	for len(*l.items) > 0 {
   434  		// Discard stale transactions if found during cleanup
   435  		tx := heap.Pop(l.items).(*types.Transaction)
   436  		if _, ok := (*l.all)[tx.Hash()]; !ok {
   437  			l.stales--
   438  			continue
   439  		}
   440  		// Stop the discards if we've reached the threshold
   441  		if tx.GasPrice().Cmp(threshold) >= 0 {
   442  			save = append(save, tx)
   443  			break
   444  		}
   445  		// Non stale transaction found, discard unless local
   446  		if local.containsTx(tx) {
   447  			save = append(save, tx)
   448  		} else {
   449  			drop = append(drop, tx)
   450  		}
   451  	}
   452  	for _, tx := range save {
   453  		heap.Push(l.items, tx)
   454  	}
   455  	return drop
   456  }
   457  
   458  // Underpriced checks whether a transaction is cheaper than (or as cheap as) the
   459  // lowest priced transaction currently being tracked.
   460  func (l *txPricedList) Underpriced(tx *types.Transaction, local *accountSet) bool {
   461  	// Local transactions cannot be underpriced
   462  	if local.containsTx(tx) {
   463  		return false
   464  	}
   465  	// Discard stale price points if found at the heap start
   466  	for len(*l.items) > 0 {
   467  		head := []*types.Transaction(*l.items)[0]
   468  		if _, ok := (*l.all)[head.Hash()]; !ok {
   469  			l.stales--
   470  			heap.Pop(l.items)
   471  			continue
   472  		}
   473  		break
   474  	}
   475  	// Check if the transaction is underpriced or not
   476  	if len(*l.items) == 0 {
   477  		log.Error("Pricing query for empty pool") // This cannot happen, print to catch programming errors
   478  		return false
   479  	}
   480  	cheapest := []*types.Transaction(*l.items)[0]
   481  	return cheapest.GasPrice().Cmp(tx.GasPrice()) >= 0
   482  }
   483  
   484  // Discard finds a number of most underpriced transactions, removes them from the
   485  // priced list and returns them for further removal from the entire pool.
   486  func (l *txPricedList) Discard(count int, local *accountSet) types.Transactions {
   487  	drop := make(types.Transactions, 0, count) // Remote underpriced transactions to drop
   488  	save := make(types.Transactions, 0, 64)    // Local underpriced transactions to keep
   489  
   490  	for len(*l.items) > 0 && count > 0 {
   491  		// Discard stale transactions if found during cleanup
   492  		tx := heap.Pop(l.items).(*types.Transaction)
   493  		if _, ok := (*l.all)[tx.Hash()]; !ok {
   494  			l.stales--
   495  			continue
   496  		}
   497  		// Non stale transaction found, discard unless local
   498  		if local.containsTx(tx) {
   499  			save = append(save, tx)
   500  		} else {
   501  			drop = append(drop, tx)
   502  			count--
   503  		}
   504  	}
   505  	for _, tx := range save {
   506  		heap.Push(l.items, tx)
   507  	}
   508  	return drop
   509  }