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