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