github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/core/txpool/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 txpool 18 19 import ( 20 "container/heap" 21 "math" 22 "math/big" 23 "sort" 24 "sync" 25 "sync/atomic" 26 "time" 27 28 "github.com/tirogen/go-ethereum/common" 29 "github.com/tirogen/go-ethereum/core/types" 30 ) 31 32 // nonceHeap is a heap.Interface implementation over 64bit unsigned integers for 33 // retrieving sorted transactions from the possibly gapped future queue. 34 type nonceHeap []uint64 35 36 func (h nonceHeap) Len() int { return len(h) } 37 func (h nonceHeap) Less(i, j int) bool { return h[i] < h[j] } 38 func (h nonceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 39 40 func (h *nonceHeap) Push(x interface{}) { 41 *h = append(*h, x.(uint64)) 42 } 43 44 func (h *nonceHeap) Pop() interface{} { 45 old := *h 46 n := len(old) 47 x := old[n-1] 48 old[n-1] = 0 49 *h = old[0 : n-1] 50 return x 51 } 52 53 // sortedMap is a nonce->transaction hash map with a heap based index to allow 54 // iterating over the contents in a nonce-incrementing way. 55 type sortedMap struct { 56 items map[uint64]*types.Transaction // Hash map storing the transaction data 57 index *nonceHeap // Heap of nonces of all the stored transactions (non-strict mode) 58 cache types.Transactions // Cache of the transactions already sorted 59 } 60 61 // newSortedMap creates a new nonce-sorted transaction map. 62 func newSortedMap() *sortedMap { 63 return &sortedMap{ 64 items: make(map[uint64]*types.Transaction), 65 index: new(nonceHeap), 66 } 67 } 68 69 // Get retrieves the current transactions associated with the given nonce. 70 func (m *sortedMap) Get(nonce uint64) *types.Transaction { 71 return m.items[nonce] 72 } 73 74 // Put inserts a new transaction into the map, also updating the map's nonce 75 // index. If a transaction already exists with the same nonce, it's overwritten. 76 func (m *sortedMap) Put(tx *types.Transaction) { 77 nonce := tx.Nonce() 78 if m.items[nonce] == nil { 79 heap.Push(m.index, nonce) 80 } 81 m.items[nonce], m.cache = tx, nil 82 } 83 84 // Forward removes all transactions from the map with a nonce lower than the 85 // provided threshold. Every removed transaction is returned for any post-removal 86 // maintenance. 87 func (m *sortedMap) Forward(threshold uint64) types.Transactions { 88 var removed types.Transactions 89 90 // Pop off heap items until the threshold is reached 91 for m.index.Len() > 0 && (*m.index)[0] < threshold { 92 nonce := heap.Pop(m.index).(uint64) 93 removed = append(removed, m.items[nonce]) 94 delete(m.items, nonce) 95 } 96 // If we had a cached order, shift the front 97 if m.cache != nil { 98 m.cache = m.cache[len(removed):] 99 } 100 return removed 101 } 102 103 // Filter iterates over the list of transactions and removes all of them for which 104 // the specified function evaluates to true. 105 // Filter, as opposed to 'filter', re-initialises the heap after the operation is done. 106 // If you want to do several consecutive filterings, it's therefore better to first 107 // do a .filter(func1) followed by .Filter(func2) or reheap() 108 func (m *sortedMap) Filter(filter func(*types.Transaction) bool) types.Transactions { 109 removed := m.filter(filter) 110 // If transactions were removed, the heap and cache are ruined 111 if len(removed) > 0 { 112 m.reheap() 113 } 114 return removed 115 } 116 117 func (m *sortedMap) reheap() { 118 *m.index = make([]uint64, 0, len(m.items)) 119 for nonce := range m.items { 120 *m.index = append(*m.index, nonce) 121 } 122 heap.Init(m.index) 123 m.cache = nil 124 } 125 126 // filter is identical to Filter, but **does not** regenerate the heap. This method 127 // should only be used if followed immediately by a call to Filter or reheap() 128 func (m *sortedMap) filter(filter func(*types.Transaction) bool) types.Transactions { 129 var removed types.Transactions 130 131 // Collect all the transactions to filter out 132 for nonce, tx := range m.items { 133 if filter(tx) { 134 removed = append(removed, tx) 135 delete(m.items, nonce) 136 } 137 } 138 if len(removed) > 0 { 139 m.cache = nil 140 } 141 return removed 142 } 143 144 // Cap places a hard limit on the number of items, returning all transactions 145 // exceeding that limit. 146 func (m *sortedMap) Cap(threshold int) types.Transactions { 147 // Short circuit if the number of items is under the limit 148 if len(m.items) <= threshold { 149 return nil 150 } 151 // Otherwise gather and drop the highest nonce'd transactions 152 var drops types.Transactions 153 154 sort.Sort(*m.index) 155 for size := len(m.items); size > threshold; size-- { 156 drops = append(drops, m.items[(*m.index)[size-1]]) 157 delete(m.items, (*m.index)[size-1]) 158 } 159 *m.index = (*m.index)[:threshold] 160 heap.Init(m.index) 161 162 // If we had a cache, shift the back 163 if m.cache != nil { 164 m.cache = m.cache[:len(m.cache)-len(drops)] 165 } 166 return drops 167 } 168 169 // Remove deletes a transaction from the maintained map, returning whether the 170 // transaction was found. 171 func (m *sortedMap) Remove(nonce uint64) bool { 172 // Short circuit if no transaction is present 173 _, ok := m.items[nonce] 174 if !ok { 175 return false 176 } 177 // Otherwise delete the transaction and fix the heap index 178 for i := 0; i < m.index.Len(); i++ { 179 if (*m.index)[i] == nonce { 180 heap.Remove(m.index, i) 181 break 182 } 183 } 184 delete(m.items, nonce) 185 m.cache = nil 186 187 return true 188 } 189 190 // Ready retrieves a sequentially increasing list of transactions starting at the 191 // provided nonce that is ready for processing. The returned transactions will be 192 // removed from the list. 193 // 194 // Note, all transactions with nonces lower than start will also be returned to 195 // prevent getting into and invalid state. This is not something that should ever 196 // happen but better to be self correcting than failing! 197 func (m *sortedMap) Ready(start uint64) types.Transactions { 198 // Short circuit if no transactions are available 199 if m.index.Len() == 0 || (*m.index)[0] > start { 200 return nil 201 } 202 // Otherwise start accumulating incremental transactions 203 var ready types.Transactions 204 for next := (*m.index)[0]; m.index.Len() > 0 && (*m.index)[0] == next; next++ { 205 ready = append(ready, m.items[next]) 206 delete(m.items, next) 207 heap.Pop(m.index) 208 } 209 m.cache = nil 210 211 return ready 212 } 213 214 // Len returns the length of the transaction map. 215 func (m *sortedMap) Len() int { 216 return len(m.items) 217 } 218 219 func (m *sortedMap) flatten() types.Transactions { 220 // If the sorting was not cached yet, create and cache it 221 if m.cache == nil { 222 m.cache = make(types.Transactions, 0, len(m.items)) 223 for _, tx := range m.items { 224 m.cache = append(m.cache, tx) 225 } 226 sort.Sort(types.TxByNonce(m.cache)) 227 } 228 return m.cache 229 } 230 231 // Flatten creates a nonce-sorted slice of transactions based on the loosely 232 // sorted internal representation. The result of the sorting is cached in case 233 // it's requested again before any modifications are made to the contents. 234 func (m *sortedMap) Flatten() types.Transactions { 235 // Copy the cache to prevent accidental modifications 236 cache := m.flatten() 237 txs := make(types.Transactions, len(cache)) 238 copy(txs, cache) 239 return txs 240 } 241 242 // LastElement returns the last element of a flattened list, thus, the 243 // transaction with the highest nonce 244 func (m *sortedMap) LastElement() *types.Transaction { 245 cache := m.flatten() 246 return cache[len(cache)-1] 247 } 248 249 // list is a "list" of transactions belonging to an account, sorted by account 250 // nonce. The same type can be used both for storing contiguous transactions for 251 // the executable/pending queue; and for storing gapped transactions for the non- 252 // executable/future queue, with minor behavioral changes. 253 type list struct { 254 strict bool // Whether nonces are strictly continuous or not 255 txs *sortedMap // Heap indexed sorted hash map of the transactions 256 257 costcap *big.Int // Price of the highest costing transaction (reset only if exceeds balance) 258 gascap uint64 // Gas limit of the highest spending transaction (reset only if exceeds block limit) 259 } 260 261 // newList create a new transaction list for maintaining nonce-indexable fast, 262 // gapped, sortable transaction lists. 263 func newList(strict bool) *list { 264 return &list{ 265 strict: strict, 266 txs: newSortedMap(), 267 costcap: new(big.Int), 268 } 269 } 270 271 // Overlaps returns whether the transaction specified has the same nonce as one 272 // already contained within the list. 273 func (l *list) Overlaps(tx *types.Transaction) bool { 274 return l.txs.Get(tx.Nonce()) != nil 275 } 276 277 // Add tries to insert a new transaction into the list, returning whether the 278 // transaction was accepted, and if yes, any previous transaction it replaced. 279 // 280 // If the new transaction is accepted into the list, the lists' cost and gas 281 // thresholds are also potentially updated. 282 func (l *list) Add(tx *types.Transaction, priceBump uint64) (bool, *types.Transaction) { 283 // If there's an older better transaction, abort 284 old := l.txs.Get(tx.Nonce()) 285 if old != nil { 286 if old.GasFeeCapCmp(tx) >= 0 || old.GasTipCapCmp(tx) >= 0 { 287 return false, nil 288 } 289 // thresholdFeeCap = oldFC * (100 + priceBump) / 100 290 a := big.NewInt(100 + int64(priceBump)) 291 aFeeCap := new(big.Int).Mul(a, old.GasFeeCap()) 292 aTip := a.Mul(a, old.GasTipCap()) 293 294 // thresholdTip = oldTip * (100 + priceBump) / 100 295 b := big.NewInt(100) 296 thresholdFeeCap := aFeeCap.Div(aFeeCap, b) 297 thresholdTip := aTip.Div(aTip, b) 298 299 // We have to ensure that both the new fee cap and tip are higher than the 300 // old ones as well as checking the percentage threshold to ensure that 301 // this is accurate for low (Wei-level) gas price replacements. 302 if tx.GasFeeCapIntCmp(thresholdFeeCap) < 0 || tx.GasTipCapIntCmp(thresholdTip) < 0 { 303 return false, nil 304 } 305 } 306 // Otherwise overwrite the old transaction with the current one 307 l.txs.Put(tx) 308 if cost := tx.Cost(); l.costcap.Cmp(cost) < 0 { 309 l.costcap = cost 310 } 311 if gas := tx.Gas(); l.gascap < gas { 312 l.gascap = gas 313 } 314 return true, old 315 } 316 317 // Forward removes all transactions from the list with a nonce lower than the 318 // provided threshold. Every removed transaction is returned for any post-removal 319 // maintenance. 320 func (l *list) Forward(threshold uint64) types.Transactions { 321 return l.txs.Forward(threshold) 322 } 323 324 // Filter removes all transactions from the list with a cost or gas limit higher 325 // than the provided thresholds. Every removed transaction is returned for any 326 // post-removal maintenance. Strict-mode invalidated transactions are also 327 // returned. 328 // 329 // This method uses the cached costcap and gascap to quickly decide if there's even 330 // a point in calculating all the costs or if the balance covers all. If the threshold 331 // is lower than the costgas cap, the caps will be reset to a new high after removing 332 // the newly invalidated transactions. 333 func (l *list) Filter(costLimit *big.Int, gasLimit uint64) (types.Transactions, types.Transactions) { 334 // If all transactions are below the threshold, short circuit 335 if l.costcap.Cmp(costLimit) <= 0 && l.gascap <= gasLimit { 336 return nil, nil 337 } 338 l.costcap = new(big.Int).Set(costLimit) // Lower the caps to the thresholds 339 l.gascap = gasLimit 340 341 // Filter out all the transactions above the account's funds 342 removed := l.txs.Filter(func(tx *types.Transaction) bool { 343 return tx.Gas() > gasLimit || tx.Cost().Cmp(costLimit) > 0 344 }) 345 346 if len(removed) == 0 { 347 return nil, nil 348 } 349 var invalids types.Transactions 350 // If the list was strict, filter anything above the lowest nonce 351 if l.strict { 352 lowest := uint64(math.MaxUint64) 353 for _, tx := range removed { 354 if nonce := tx.Nonce(); lowest > nonce { 355 lowest = nonce 356 } 357 } 358 invalids = l.txs.filter(func(tx *types.Transaction) bool { return tx.Nonce() > lowest }) 359 } 360 l.txs.reheap() 361 return removed, invalids 362 } 363 364 // Cap places a hard limit on the number of items, returning all transactions 365 // exceeding that limit. 366 func (l *list) Cap(threshold int) types.Transactions { 367 return l.txs.Cap(threshold) 368 } 369 370 // Remove deletes a transaction from the maintained list, returning whether the 371 // transaction was found, and also returning any transaction invalidated due to 372 // the deletion (strict mode only). 373 func (l *list) Remove(tx *types.Transaction) (bool, types.Transactions) { 374 // Remove the transaction from the set 375 nonce := tx.Nonce() 376 if removed := l.txs.Remove(nonce); !removed { 377 return false, nil 378 } 379 // In strict mode, filter out non-executable transactions 380 if l.strict { 381 return true, l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > nonce }) 382 } 383 return true, nil 384 } 385 386 // Ready retrieves a sequentially increasing list of transactions starting at the 387 // provided nonce that is ready for processing. The returned transactions will be 388 // removed from the list. 389 // 390 // Note, all transactions with nonces lower than start will also be returned to 391 // prevent getting into and invalid state. This is not something that should ever 392 // happen but better to be self correcting than failing! 393 func (l *list) Ready(start uint64) types.Transactions { 394 return l.txs.Ready(start) 395 } 396 397 // Len returns the length of the transaction list. 398 func (l *list) Len() int { 399 return l.txs.Len() 400 } 401 402 // Empty returns whether the list of transactions is empty or not. 403 func (l *list) Empty() bool { 404 return l.Len() == 0 405 } 406 407 // Flatten creates a nonce-sorted slice of transactions based on the loosely 408 // sorted internal representation. The result of the sorting is cached in case 409 // it's requested again before any modifications are made to the contents. 410 func (l *list) Flatten() types.Transactions { 411 return l.txs.Flatten() 412 } 413 414 // LastElement returns the last element of a flattened list, thus, the 415 // transaction with the highest nonce 416 func (l *list) LastElement() *types.Transaction { 417 return l.txs.LastElement() 418 } 419 420 // priceHeap is a heap.Interface implementation over transactions for retrieving 421 // price-sorted transactions to discard when the pool fills up. If baseFee is set 422 // then the heap is sorted based on the effective tip based on the given base fee. 423 // If baseFee is nil then the sorting is based on gasFeeCap. 424 type priceHeap struct { 425 baseFee *big.Int // heap should always be re-sorted after baseFee is changed 426 list []*types.Transaction 427 } 428 429 func (h *priceHeap) Len() int { return len(h.list) } 430 func (h *priceHeap) Swap(i, j int) { h.list[i], h.list[j] = h.list[j], h.list[i] } 431 432 func (h *priceHeap) Less(i, j int) bool { 433 switch h.cmp(h.list[i], h.list[j]) { 434 case -1: 435 return true 436 case 1: 437 return false 438 default: 439 return h.list[i].Nonce() > h.list[j].Nonce() 440 } 441 } 442 443 func (h *priceHeap) cmp(a, b *types.Transaction) int { 444 if h.baseFee != nil { 445 // Compare effective tips if baseFee is specified 446 if c := a.EffectiveGasTipCmp(b, h.baseFee); c != 0 { 447 return c 448 } 449 } 450 // Compare fee caps if baseFee is not specified or effective tips are equal 451 if c := a.GasFeeCapCmp(b); c != 0 { 452 return c 453 } 454 // Compare tips if effective tips and fee caps are equal 455 return a.GasTipCapCmp(b) 456 } 457 458 func (h *priceHeap) Push(x interface{}) { 459 tx := x.(*types.Transaction) 460 h.list = append(h.list, tx) 461 } 462 463 func (h *priceHeap) Pop() interface{} { 464 old := h.list 465 n := len(old) 466 x := old[n-1] 467 old[n-1] = nil 468 h.list = old[0 : n-1] 469 return x 470 } 471 472 // pricedList is a price-sorted heap to allow operating on transactions pool 473 // contents in a price-incrementing way. It's built upon the all transactions 474 // in txpool but only interested in the remote part. It means only remote transactions 475 // will be considered for tracking, sorting, eviction, etc. 476 // 477 // Two heaps are used for sorting: the urgent heap (based on effective tip in the next 478 // block) and the floating heap (based on gasFeeCap). Always the bigger heap is chosen for 479 // eviction. Transactions evicted from the urgent heap are first demoted into the floating heap. 480 // In some cases (during a congestion, when blocks are full) the urgent heap can provide 481 // better candidates for inclusion while in other cases (at the top of the baseFee peak) 482 // the floating heap is better. When baseFee is decreasing they behave similarly. 483 type pricedList struct { 484 // Number of stale price points to (re-heap trigger). 485 // This field is accessed atomically, and must be the first field 486 // to ensure it has correct alignment for atomic.AddInt64. 487 // See https://golang.org/pkg/sync/atomic/#pkg-note-BUG. 488 stales int64 489 490 all *lookup // Pointer to the map of all transactions 491 urgent, floating priceHeap // Heaps of prices of all the stored **remote** transactions 492 reheapMu sync.Mutex // Mutex asserts that only one routine is reheaping the list 493 } 494 495 const ( 496 // urgentRatio : floatingRatio is the capacity ratio of the two queues 497 urgentRatio = 4 498 floatingRatio = 1 499 ) 500 501 // newPricedList creates a new price-sorted transaction heap. 502 func newPricedList(all *lookup) *pricedList { 503 return &pricedList{ 504 all: all, 505 } 506 } 507 508 // Put inserts a new transaction into the heap. 509 func (l *pricedList) Put(tx *types.Transaction, local bool) { 510 if local { 511 return 512 } 513 // Insert every new transaction to the urgent heap first; Discard will balance the heaps 514 heap.Push(&l.urgent, tx) 515 } 516 517 // Removed notifies the prices transaction list that an old transaction dropped 518 // from the pool. The list will just keep a counter of stale objects and update 519 // the heap if a large enough ratio of transactions go stale. 520 func (l *pricedList) Removed(count int) { 521 // Bump the stale counter, but exit if still too low (< 25%) 522 stales := atomic.AddInt64(&l.stales, int64(count)) 523 if int(stales) <= (len(l.urgent.list)+len(l.floating.list))/4 { 524 return 525 } 526 // Seems we've reached a critical number of stale transactions, reheap 527 l.Reheap() 528 } 529 530 // Underpriced checks whether a transaction is cheaper than (or as cheap as) the 531 // lowest priced (remote) transaction currently being tracked. 532 func (l *pricedList) Underpriced(tx *types.Transaction) bool { 533 // Note: with two queues, being underpriced is defined as being worse than the worst item 534 // in all non-empty queues if there is any. If both queues are empty then nothing is underpriced. 535 return (l.underpricedFor(&l.urgent, tx) || len(l.urgent.list) == 0) && 536 (l.underpricedFor(&l.floating, tx) || len(l.floating.list) == 0) && 537 (len(l.urgent.list) != 0 || len(l.floating.list) != 0) 538 } 539 540 // underpricedFor checks whether a transaction is cheaper than (or as cheap as) the 541 // lowest priced (remote) transaction in the given heap. 542 func (l *pricedList) underpricedFor(h *priceHeap, tx *types.Transaction) bool { 543 // Discard stale price points if found at the heap start 544 for len(h.list) > 0 { 545 head := h.list[0] 546 if l.all.GetRemote(head.Hash()) == nil { // Removed or migrated 547 atomic.AddInt64(&l.stales, -1) 548 heap.Pop(h) 549 continue 550 } 551 break 552 } 553 // Check if the transaction is underpriced or not 554 if len(h.list) == 0 { 555 return false // There is no remote transaction at all. 556 } 557 // If the remote transaction is even cheaper than the 558 // cheapest one tracked locally, reject it. 559 return h.cmp(h.list[0], tx) >= 0 560 } 561 562 // Discard finds a number of most underpriced transactions, removes them from the 563 // priced list and returns them for further removal from the entire pool. 564 // 565 // Note local transaction won't be considered for eviction. 566 func (l *pricedList) Discard(slots int, force bool) (types.Transactions, bool) { 567 drop := make(types.Transactions, 0, slots) // Remote underpriced transactions to drop 568 for slots > 0 { 569 if len(l.urgent.list)*floatingRatio > len(l.floating.list)*urgentRatio || floatingRatio == 0 { 570 // Discard stale transactions if found during cleanup 571 tx := heap.Pop(&l.urgent).(*types.Transaction) 572 if l.all.GetRemote(tx.Hash()) == nil { // Removed or migrated 573 atomic.AddInt64(&l.stales, -1) 574 continue 575 } 576 // Non stale transaction found, move to floating heap 577 heap.Push(&l.floating, tx) 578 } else { 579 if len(l.floating.list) == 0 { 580 // Stop if both heaps are empty 581 break 582 } 583 // Discard stale transactions if found during cleanup 584 tx := heap.Pop(&l.floating).(*types.Transaction) 585 if l.all.GetRemote(tx.Hash()) == nil { // Removed or migrated 586 atomic.AddInt64(&l.stales, -1) 587 continue 588 } 589 // Non stale transaction found, discard it 590 drop = append(drop, tx) 591 slots -= numSlots(tx) 592 } 593 } 594 // If we still can't make enough room for the new transaction 595 if slots > 0 && !force { 596 for _, tx := range drop { 597 heap.Push(&l.urgent, tx) 598 } 599 return nil, false 600 } 601 return drop, true 602 } 603 604 // Reheap forcibly rebuilds the heap based on the current remote transaction set. 605 func (l *pricedList) Reheap() { 606 l.reheapMu.Lock() 607 defer l.reheapMu.Unlock() 608 start := time.Now() 609 atomic.StoreInt64(&l.stales, 0) 610 l.urgent.list = make([]*types.Transaction, 0, l.all.RemoteCount()) 611 l.all.Range(func(hash common.Hash, tx *types.Transaction, local bool) bool { 612 l.urgent.list = append(l.urgent.list, tx) 613 return true 614 }, false, true) // Only iterate remotes 615 heap.Init(&l.urgent) 616 617 // balance out the two heaps by moving the worse half of transactions into the 618 // floating heap 619 // Note: Discard would also do this before the first eviction but Reheap can do 620 // is more efficiently. Also, Underpriced would work suboptimally the first time 621 // if the floating queue was empty. 622 floatingCount := len(l.urgent.list) * floatingRatio / (urgentRatio + floatingRatio) 623 l.floating.list = make([]*types.Transaction, floatingCount) 624 for i := 0; i < floatingCount; i++ { 625 l.floating.list[i] = heap.Pop(&l.urgent).(*types.Transaction) 626 } 627 heap.Init(&l.floating) 628 reheapTimer.Update(time.Since(start)) 629 } 630 631 // SetBaseFee updates the base fee and triggers a re-heap. Note that Removed is not 632 // necessary to call right before SetBaseFee when processing a new block. 633 func (l *pricedList) SetBaseFee(baseFee *big.Int) { 634 l.urgent.baseFee = baseFee 635 l.Reheap() 636 }