github.com/sakundi/go-ethereum@v1.9.7/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 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) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 372 373 func (h priceHeap) Less(i, j int) bool { 374 // Sort primarily by price, returning the cheaper one 375 switch h[i].GasPrice().Cmp(h[j].GasPrice()) { 376 case -1: 377 return true 378 case 1: 379 return false 380 } 381 // If the prices match, stabilize via nonces (high nonce is worse) 382 return h[i].Nonce() > h[j].Nonce() 383 } 384 385 func (h *priceHeap) Push(x interface{}) { 386 *h = append(*h, x.(*types.Transaction)) 387 } 388 389 func (h *priceHeap) Pop() interface{} { 390 old := *h 391 n := len(old) 392 x := old[n-1] 393 *h = old[0 : n-1] 394 return x 395 } 396 397 // txPricedList is a price-sorted heap to allow operating on transactions pool 398 // contents in a price-incrementing way. 399 type txPricedList struct { 400 all *txLookup // Pointer to the map of all transactions 401 items *priceHeap // Heap of prices of all the stored transactions 402 stales int // Number of stale price points to (re-heap trigger) 403 } 404 405 // newTxPricedList creates a new price-sorted transaction heap. 406 func newTxPricedList(all *txLookup) *txPricedList { 407 return &txPricedList{ 408 all: all, 409 items: new(priceHeap), 410 } 411 } 412 413 // Put inserts a new transaction into the heap. 414 func (l *txPricedList) Put(tx *types.Transaction) { 415 heap.Push(l.items, tx) 416 } 417 418 // Removed notifies the prices transaction list that an old transaction dropped 419 // from the pool. The list will just keep a counter of stale objects and update 420 // the heap if a large enough ratio of transactions go stale. 421 func (l *txPricedList) Removed(count int) { 422 // Bump the stale counter, but exit if still too low (< 25%) 423 l.stales += count 424 if l.stales <= len(*l.items)/4 { 425 return 426 } 427 // Seems we've reached a critical number of stale transactions, reheap 428 reheap := make(priceHeap, 0, l.all.Count()) 429 430 l.stales, l.items = 0, &reheap 431 l.all.Range(func(hash common.Hash, tx *types.Transaction) bool { 432 *l.items = append(*l.items, tx) 433 return true 434 }) 435 heap.Init(l.items) 436 } 437 438 // Cap finds all the transactions below the given price threshold, drops them 439 // from the priced list and returns them for further removal from the entire pool. 440 func (l *txPricedList) Cap(threshold *big.Int, local *accountSet) types.Transactions { 441 drop := make(types.Transactions, 0, 128) // Remote underpriced transactions to drop 442 save := make(types.Transactions, 0, 64) // Local underpriced transactions to keep 443 444 for len(*l.items) > 0 { 445 // Discard stale transactions if found during cleanup 446 tx := heap.Pop(l.items).(*types.Transaction) 447 if l.all.Get(tx.Hash()) == nil { 448 l.stales-- 449 continue 450 } 451 // Stop the discards if we've reached the threshold 452 if tx.GasPrice().Cmp(threshold) >= 0 { 453 save = append(save, tx) 454 break 455 } 456 // Non stale transaction found, discard unless local 457 if local.containsTx(tx) { 458 save = append(save, tx) 459 } else { 460 drop = append(drop, tx) 461 } 462 } 463 for _, tx := range save { 464 heap.Push(l.items, tx) 465 } 466 return drop 467 } 468 469 // Underpriced checks whether a transaction is cheaper than (or as cheap as) the 470 // lowest priced transaction currently being tracked. 471 func (l *txPricedList) Underpriced(tx *types.Transaction, local *accountSet) bool { 472 // Local transactions cannot be underpriced 473 if local.containsTx(tx) { 474 return false 475 } 476 // Discard stale price points if found at the heap start 477 for len(*l.items) > 0 { 478 head := []*types.Transaction(*l.items)[0] 479 if l.all.Get(head.Hash()) == nil { 480 l.stales-- 481 heap.Pop(l.items) 482 continue 483 } 484 break 485 } 486 // Check if the transaction is underpriced or not 487 if len(*l.items) == 0 { 488 log.Error("Pricing query for empty pool") // This cannot happen, print to catch programming errors 489 return false 490 } 491 cheapest := []*types.Transaction(*l.items)[0] 492 return cheapest.GasPrice().Cmp(tx.GasPrice()) >= 0 493 } 494 495 // Discard finds a number of most underpriced transactions, removes them from the 496 // priced list and returns them for further removal from the entire pool. 497 func (l *txPricedList) Discard(count int, local *accountSet) types.Transactions { 498 drop := make(types.Transactions, 0, count) // Remote underpriced transactions to drop 499 save := make(types.Transactions, 0, 64) // Local underpriced transactions to keep 500 501 for len(*l.items) > 0 && count > 0 { 502 // Discard stale transactions if found during cleanup 503 tx := heap.Pop(l.items).(*types.Transaction) 504 if l.all.Get(tx.Hash()) == nil { 505 l.stales-- 506 continue 507 } 508 // Non stale transaction found, discard unless local 509 if local.containsTx(tx) { 510 save = append(save, tx) 511 } else { 512 drop = append(drop, tx) 513 count-- 514 } 515 } 516 for _, tx := range save { 517 heap.Push(l.items, tx) 518 } 519 return drop 520 }